• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

umputun / tg-spam / 13663115073

04 Mar 2025 09:17PM UTC coverage: 78.872% (+0.04%) from 78.831%
13663115073

push

github

web-flow
Merge pull request #256 from umputun/improved-settings-page

Improve Settings Page UI and Organization

59 of 72 new or added lines in 1 file covered. (81.94%)

3957 of 5017 relevant lines covered (78.87%)

65.67 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.67
/app/webapi/webapi.go
1
// Package webapi provides a web API spam detection service.
2
package webapi
3

4
import (
5
        "compress/gzip"
6
        "context"
7
        "crypto/rand"
8
        "crypto/sha1" //nolint
9
        "embed"
10
        "encoding/json"
11
        "errors"
12
        "fmt"
13
        "html/template"
14
        "io"
15
        "io/fs"
16
        "math/big"
17
        "net/http"
18
        "path"
19
        "strconv"
20
        "strings"
21
        "time"
22

23
        "github.com/didip/tollbooth/v8"
24
        log "github.com/go-pkgz/lgr"
25
        "github.com/go-pkgz/rest"
26
        "github.com/go-pkgz/rest/logger"
27
        "github.com/go-pkgz/routegroup"
28

29
        "github.com/umputun/tg-spam/app/storage"
30
        "github.com/umputun/tg-spam/app/storage/engine"
31
        "github.com/umputun/tg-spam/lib/approved"
32
        "github.com/umputun/tg-spam/lib/spamcheck"
33
)
34

35
//go:generate moq --out mocks/detector.go --pkg mocks --with-resets --skip-ensure . Detector
36
//go:generate moq --out mocks/spam_filter.go --pkg mocks --with-resets --skip-ensure . SpamFilter
37
//go:generate moq --out mocks/locator.go --pkg mocks --with-resets --skip-ensure . Locator
38
//go:generate moq --out mocks/detected_spam.go --pkg mocks --with-resets --skip-ensure . DetectedSpam
39
//go:generate moq --out mocks/storage_engine.go --pkg mocks --with-resets --skip-ensure . StorageEngine
40

41
//go:embed assets/* assets/components/*
42
var templateFS embed.FS
43
var tmpl = template.Must(template.ParseFS(templateFS, "assets/*.html", "assets/components/*.html"))
44

45
// startTime tracks when the server started
46
var startTime = time.Now()
47

48
// Server is a web API server.
49
type Server struct {
50
        Config
51
}
52

53
// Config defines  server parameters
54
type Config struct {
55
        Version       string        // version to show in /ping
56
        ListenAddr    string        // listen address
57
        Detector      Detector      // spam detector
58
        SpamFilter    SpamFilter    // spam filter (bot)
59
        DetectedSpam  DetectedSpam  // detected spam accessor
60
        Locator       Locator       // locator for user info
61
        StorageEngine StorageEngine // database engine access for backups
62
        AuthPasswd    string        // basic auth password for user "tg-spam"
63
        AuthHash      string        // basic auth hash for user "tg-spam". If both AuthPasswd and AuthHash are provided, AuthHash is used
64
        Dbg           bool          // debug mode
65
        Settings      Settings      // application settings
66
}
67

68
// Settings contains all application settings
69
type Settings struct {
70
        InstanceID              string        `json:"instance_id"`
71
        PrimaryGroup            string        `json:"primary_group"`
72
        AdminGroup              string        `json:"admin_group"`
73
        DisableAdminSpamForward bool          `json:"disable_admin_spam_forward"`
74
        LoggerEnabled           bool          `json:"logger_enabled"`
75
        SuperUsers              []string      `json:"super_users"`
76
        NoSpamReply             bool          `json:"no_spam_reply"`
77
        CasEnabled              bool          `json:"cas_enabled"`
78
        MetaEnabled             bool          `json:"meta_enabled"`
79
        MetaLinksLimit          int           `json:"meta_links_limit"`
80
        MetaLinksOnly           bool          `json:"meta_links_only"`
81
        MetaImageOnly           bool          `json:"meta_image_only"`
82
        MetaVideoOnly           bool          `json:"meta_video_only"`
83
        MetaAudioOnly           bool          `json:"meta_audio_only"`
84
        MetaForwarded           bool          `json:"meta_forwarded"`
85
        MultiLangLimit          int           `json:"multi_lang_limit"`
86
        OpenAIEnabled           bool          `json:"openai_enabled"`
87
        SamplesDataPath         string        `json:"samples_data_path"`
88
        DynamicDataPath         string        `json:"dynamic_data_path"`
89
        WatchIntervalSecs       int           `json:"watch_interval_secs"`
90
        SimilarityThreshold     float64       `json:"similarity_threshold"`
91
        MinMsgLen               int           `json:"min_msg_len"`
92
        MaxEmoji                int           `json:"max_emoji"`
93
        MinSpamProbability      float64       `json:"min_spam_probability"`
94
        ParanoidMode            bool          `json:"paranoid_mode"`
95
        FirstMessagesCount      int           `json:"first_messages_count"`
96
        StartupMessageEnabled   bool          `json:"startup_message_enabled"`
97
        TrainingEnabled         bool          `json:"training_enabled"`
98
        StorageTimeout          time.Duration `json:"storage_timeout"`
99
        OpenAIVeto              bool          `json:"openai_veto"`
100
        OpenAIHistorySize       int           `json:"openai_history_size"`
101
        OpenAIModel             string        `json:"openai_model"`
102
        SoftBanEnabled          bool          `json:"soft_ban_enabled"`
103
        AbnormalSpacingEnabled  bool          `json:"abnormal_spacing_enabled"`
104
        HistorySize             int           `json:"history_size"`
105
        DebugModeEnabled        bool          `json:"debug_mode_enabled"`
106
        DryModeEnabled          bool          `json:"dry_mode_enabled"`
107
        TGDebugModeEnabled      bool          `json:"tg_debug_mode_enabled"`
108
}
109

110
// Detector is a spam detector interface.
111
type Detector interface {
112
        Check(req spamcheck.Request) (spam bool, cr []spamcheck.Response)
113
        ApprovedUsers() []approved.UserInfo
114
        AddApprovedUser(user approved.UserInfo) error
115
        RemoveApprovedUser(id string) error
116
}
117

118
// SpamFilter is a spam filter, bot interface.
119
type SpamFilter interface {
120
        UpdateSpam(msg string) error
121
        UpdateHam(msg string) error
122
        ReloadSamples() (err error)
123
        DynamicSamples() (spam, ham []string, err error)
124
        RemoveDynamicSpamSample(sample string) error
125
        RemoveDynamicHamSample(sample string) error
126
}
127

128
// Locator is a storage interface used to get user id by name and vice versa.
129
type Locator interface {
130
        UserIDByName(ctx context.Context, userName string) int64
131
        UserNameByID(ctx context.Context, userID int64) string
132
}
133

134
// DetectedSpam is a storage interface used to get detected spam messages and set added flag.
135
type DetectedSpam interface {
136
        Read(ctx context.Context) ([]storage.DetectedSpamInfo, error)
137
        SetAddedToSamplesFlag(ctx context.Context, id int64) error
138
        FindByUserID(ctx context.Context, userID int64) (*storage.DetectedSpamInfo, error)
139
}
140

141
// StorageEngine provides access to the database engine for operations like backup
142
type StorageEngine interface {
143
        Backup(ctx context.Context, w io.Writer) error
144
}
145

146
// NewServer creates a new web API server.
147
func NewServer(config Config) *Server {
25✔
148
        return &Server{Config: config}
25✔
149
}
25✔
150

151
// Run starts server and accepts requests checking for spam messages.
152
func (s *Server) Run(ctx context.Context) error {
3✔
153
        router := routegroup.New(http.NewServeMux())
3✔
154
        router.Use(rest.Recoverer(log.Default()))
3✔
155
        router.Use(logger.New(logger.Log(log.Default()), logger.Prefix("[DEBUG]")).Handler)
3✔
156
        router.Use(rest.Throttle(1000))
3✔
157
        router.Use(rest.AppInfo("tg-spam", "umputun", s.Version), rest.Ping)
3✔
158
        router.Use(tollbooth.HTTPMiddleware(tollbooth.NewLimiter(50, nil)))
3✔
159
        router.Use(rest.SizeLimit(1024 * 1024)) // 1M max request size
3✔
160

3✔
161
        if s.AuthPasswd != "" || s.AuthHash != "" {
6✔
162
                log.Printf("[INFO] basic auth enabled for webapi server")
3✔
163
                if s.AuthHash != "" {
4✔
164
                        router.Use(rest.BasicAuthWithBcryptHashAndPrompt("tg-spam", s.AuthHash))
1✔
165
                } else {
3✔
166
                        router.Use(rest.BasicAuthWithPrompt("tg-spam", s.AuthPasswd))
2✔
167
                }
2✔
168
        } else {
×
169
                log.Printf("[WARN] basic auth disabled, access to webapi is not protected")
×
170
        }
×
171

172
        router = s.routes(router) // setup routes
3✔
173

3✔
174
        srv := &http.Server{Addr: s.ListenAddr, Handler: router, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second}
3✔
175
        go func() {
6✔
176
                <-ctx.Done()
3✔
177
                if err := srv.Shutdown(ctx); err != nil {
3✔
178
                        log.Printf("[WARN] failed to shutdown webapi server: %v", err)
×
179
                } else {
3✔
180
                        log.Printf("[INFO] webapi server stopped")
3✔
181
                }
3✔
182
        }()
183

184
        log.Printf("[INFO] start webapi server on %s", s.ListenAddr)
3✔
185
        if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
3✔
186
                return fmt.Errorf("failed to run server: %w", err)
×
187
        }
×
188
        return nil
3✔
189
}
190

191
func (s *Server) routes(router *routegroup.Bundle) *routegroup.Bundle {
5✔
192
        // auth api routes
5✔
193
        router.Route(func(authApi *routegroup.Bundle) {
10✔
194
                authApi.Use(s.authMiddleware(rest.BasicAuthWithUserPasswd("tg-spam", s.AuthPasswd)))
5✔
195
                authApi.HandleFunc("POST /check", s.checkMsgHandler)         // check a message for spam
5✔
196
                authApi.HandleFunc("GET /check/{user_id}", s.checkIDHandler) // check user id for spam
5✔
197

5✔
198
                authApi.Mount("/update").Route(func(r *routegroup.Bundle) {
10✔
199
                        // update spam/ham samples
5✔
200
                        r.HandleFunc("POST /spam", s.updateSampleHandler(s.SpamFilter.UpdateSpam)) // update spam samples
5✔
201
                        r.HandleFunc("POST /ham", s.updateSampleHandler(s.SpamFilter.UpdateHam))   // update ham samples
5✔
202
                })
5✔
203

204
                authApi.Mount("/delete").Route(func(r *routegroup.Bundle) {
10✔
205
                        // delete spam/ham samples
5✔
206
                        r.HandleFunc("POST /spam", s.deleteSampleHandler(s.SpamFilter.RemoveDynamicSpamSample))
5✔
207
                        r.HandleFunc("POST /ham", s.deleteSampleHandler(s.SpamFilter.RemoveDynamicHamSample))
5✔
208
                })
5✔
209

210
                authApi.Mount("/download").Route(func(r *routegroup.Bundle) {
10✔
211
                        r.HandleFunc("GET /spam", s.downloadSampleHandler(func(spam, _ []string) ([]string, string) {
5✔
212
                                return spam, "spam.txt"
×
213
                        }))
×
214
                        r.HandleFunc("GET /ham", s.downloadSampleHandler(func(_, ham []string) ([]string, string) {
5✔
215
                                return ham, "ham.txt"
×
216
                        }))
×
217
                        r.HandleFunc("GET /detected_spam", s.downloadDetectedSpamHandler)
5✔
218
                        r.HandleFunc("GET /backup", s.downloadBackupHandler)
5✔
219
                })
220

221
                authApi.HandleFunc("GET /samples", s.getDynamicSamplesHandler)    // get dynamic samples
5✔
222
                authApi.HandleFunc("PUT /samples", s.reloadDynamicSamplesHandler) // reload samples
5✔
223

5✔
224
                authApi.Mount("/users").Route(func(r *routegroup.Bundle) { // manage approved users
10✔
225
                        // add user to the approved list and storage
5✔
226
                        r.HandleFunc("POST /add", s.updateApprovedUsersHandler(s.Detector.AddApprovedUser))
5✔
227
                        // remove user from an approved list and storage
5✔
228
                        r.HandleFunc("POST /delete", s.updateApprovedUsersHandler(s.removeApprovedUser))
5✔
229
                        // get approved users
5✔
230
                        r.HandleFunc("GET /", s.getApprovedUsersHandler)
5✔
231
                })
5✔
232

233
                authApi.HandleFunc("GET /settings", func(w http.ResponseWriter, _ *http.Request) {
6✔
234
                        rest.RenderJSON(w, s.Settings)
1✔
235
                })
1✔
236
        })
237

238
        router.Route(func(webUI *routegroup.Bundle) {
10✔
239
                webUI.Use(s.authMiddleware(rest.BasicAuthWithPrompt("tg-spam", s.AuthPasswd)))
5✔
240
                webUI.HandleFunc("GET /", s.htmlSpamCheckHandler)                         // serve template for webUI UI
5✔
241
                webUI.HandleFunc("GET /manage_samples", s.htmlManageSamplesHandler)       // serve manage samples page
5✔
242
                webUI.HandleFunc("GET /manage_users", s.htmlManageUsersHandler)           // serve manage users page
5✔
243
                webUI.HandleFunc("GET /detected_spam", s.htmlDetectedSpamHandler)         // serve detected spam page
5✔
244
                webUI.HandleFunc("GET /list_settings", s.htmlSettingsHandler)             // serve settings
5✔
245
                webUI.HandleFunc("POST /detected_spam/add", s.htmlAddDetectedSpamHandler) // add detected spam to samples
5✔
246

5✔
247
                // handle logout - force Basic Auth re-authentication
5✔
248
                webUI.HandleFunc("GET /logout", func(w http.ResponseWriter, _ *http.Request) {
5✔
249
                        w.Header().Set("WWW-Authenticate", `Basic realm="tg-spam"`)
×
250
                        w.WriteHeader(http.StatusUnauthorized)
×
251
                        fmt.Fprintln(w, "Logged out successfully")
×
252
                })
×
253

254
                // serve only specific static files at root level
255
                staticFiles := newStaticFS(templateFS,
5✔
256
                        staticFileMapping{urlPath: "styles.css", filesysPath: "assets/styles.css"},
5✔
257
                        staticFileMapping{urlPath: "logo.png", filesysPath: "assets/logo.png"},
5✔
258
                        staticFileMapping{urlPath: "spinner.svg", filesysPath: "assets/spinner.svg"},
5✔
259
                )
5✔
260
                webUI.HandleFiles("/", http.FS(staticFiles))
5✔
261
        })
262

263
        return router
5✔
264
}
265

266
// checkMsgHandler handles POST /check request.
267
// it gets message text and user id from request body and returns spam status and check results.
268
func (s *Server) checkMsgHandler(w http.ResponseWriter, r *http.Request) {
7✔
269
        type CheckResultDisplay struct {
7✔
270
                Spam   bool
7✔
271
                Checks []spamcheck.Response
7✔
272
        }
7✔
273

7✔
274
        isHtmxRequest := r.Header.Get("HX-Request") == "true"
7✔
275

7✔
276
        req := spamcheck.Request{CheckOnly: true}
7✔
277
        if !isHtmxRequest {
13✔
278
                // API request
6✔
279
                if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
7✔
280
                        w.WriteHeader(http.StatusBadRequest)
1✔
281
                        rest.RenderJSON(w, rest.JSON{"error": "can't decode request", "details": err.Error()})
1✔
282
                        log.Printf("[WARN] can't decode request: %v", err)
1✔
283
                        return
1✔
284
                }
1✔
285
        } else {
1✔
286
                // for hx-request (HTMX) we need to get the values from the form
1✔
287
                req.UserID = r.FormValue("user_id")
1✔
288
                req.UserName = r.FormValue("user_name")
1✔
289
                req.Msg = r.FormValue("msg")
1✔
290
        }
1✔
291

292
        spam, cr := s.Detector.Check(req)
6✔
293
        if !isHtmxRequest {
11✔
294
                // for API request return JSON
5✔
295
                rest.RenderJSON(w, rest.JSON{"spam": spam, "checks": cr})
5✔
296
                return
5✔
297
        }
5✔
298

299
        if req.Msg == "" || req.UserID == "" || req.UserID == "0" {
1✔
300
                w.Header().Set("HX-Retarget", "#error-message")
×
301
                fmt.Fprintln(w, "<div class='alert alert-danger'>userid and valid message required.</div>")
×
302
                return
×
303
        }
×
304

305
        // render result for HTMX request
306
        resultDisplay := CheckResultDisplay{
1✔
307
                Spam:   spam,
1✔
308
                Checks: cr,
1✔
309
        }
1✔
310

1✔
311
        if err := tmpl.ExecuteTemplate(w, "check_results", resultDisplay); err != nil {
1✔
312
                log.Printf("[WARN] can't execute result template: %v", err)
×
313
                http.Error(w, "Error rendering result", http.StatusInternalServerError)
×
314
                return
×
315
        }
×
316
}
317

318
// checkIDHandler handles GET /check/{user_id} request.
319
// it returns JSON with the status "spam" or "ham" for a given user id.
320
// if user is spammer, it also returns check results.
321
func (s *Server) checkIDHandler(w http.ResponseWriter, r *http.Request) {
2✔
322
        type info struct {
2✔
323
                UserName  string               `json:"user_name,omitempty"`
2✔
324
                Message   string               `json:"message,omitempty"`
2✔
325
                Timestamp time.Time            `json:"timestamp,omitempty"`
2✔
326
                Checks    []spamcheck.Response `json:"checks,omitempty"`
2✔
327
        }
2✔
328
        resp := struct {
2✔
329
                Status string `json:"status"`
2✔
330
                Info   *info  `json:"info,omitempty"`
2✔
331
        }{
2✔
332
                Status: "ham",
2✔
333
        }
2✔
334

2✔
335
        userID, err := strconv.ParseInt(r.PathValue("user_id"), 10, 64)
2✔
336
        if err != nil {
2✔
337
                w.WriteHeader(http.StatusBadRequest)
×
338
                rest.RenderJSON(w, rest.JSON{"error": "can't parse user id", "details": err.Error()})
×
339
                return
×
340
        }
×
341

342
        si, err := s.DetectedSpam.FindByUserID(r.Context(), userID)
2✔
343
        if err != nil {
2✔
344
                w.WriteHeader(http.StatusInternalServerError)
×
345
                rest.RenderJSON(w, rest.JSON{"error": "can't get user info", "details": err.Error()})
×
346
                return
×
347
        }
×
348
        if si != nil {
3✔
349
                resp.Status = "spam"
1✔
350
                resp.Info = &info{
1✔
351
                        UserName:  si.UserName,
1✔
352
                        Message:   si.Text,
1✔
353
                        Timestamp: si.Timestamp,
1✔
354
                        Checks:    si.Checks,
1✔
355
                }
1✔
356
        }
1✔
357
        rest.RenderJSON(w, resp)
2✔
358
}
359

360
// getDynamicSamplesHandler handles GET /samples request. It returns dynamic samples both for spam and ham.
361
func (s *Server) getDynamicSamplesHandler(w http.ResponseWriter, _ *http.Request) {
×
362
        spam, ham, err := s.SpamFilter.DynamicSamples()
×
363
        if err != nil {
×
364
                w.WriteHeader(http.StatusInternalServerError)
×
365
                rest.RenderJSON(w, rest.JSON{"error": "can't get dynamic samples", "details": err.Error()})
×
366
                return
×
367
        }
×
368
        rest.RenderJSON(w, rest.JSON{"spam": spam, "ham": ham})
×
369
}
370

371
// downloadSampleHandler handles GET /download/spam|ham request. It returns dynamic samples both for spam and ham.
372
func (s *Server) downloadSampleHandler(pickFn func(spam, ham []string) ([]string, string)) func(w http.ResponseWriter, r *http.Request) {
13✔
373
        return func(w http.ResponseWriter, _ *http.Request) {
16✔
374
                spam, ham, err := s.SpamFilter.DynamicSamples()
3✔
375
                if err != nil {
4✔
376
                        w.WriteHeader(http.StatusInternalServerError)
1✔
377
                        rest.RenderJSON(w, rest.JSON{"error": "can't get dynamic samples", "details": err.Error()})
1✔
378
                        return
1✔
379
                }
1✔
380
                samples, name := pickFn(spam, ham)
2✔
381
                body := strings.Join(samples, "\n")
2✔
382
                w.Header().Set("Content-Type", "text/plain; charset=utf-8")
2✔
383
                w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", name))
2✔
384
                w.Header().Set("Content-Length", strconv.Itoa(len(body)))
2✔
385
                w.WriteHeader(http.StatusOK)
2✔
386
                _, _ = w.Write([]byte(body))
2✔
387
        }
388
}
389

390
// updateSampleHandler handles POST /update/spam|ham request. It updates dynamic samples both for spam and ham.
391
func (s *Server) updateSampleHandler(updFn func(msg string) error) func(w http.ResponseWriter, r *http.Request) {
13✔
392
        return func(w http.ResponseWriter, r *http.Request) {
18✔
393
                var req struct {
5✔
394
                        Msg string `json:"msg"`
5✔
395
                }
5✔
396

5✔
397
                isHtmxRequest := r.Header.Get("HX-Request") == "true"
5✔
398

5✔
399
                if isHtmxRequest {
5✔
400
                        req.Msg = r.FormValue("msg")
×
401
                } else {
5✔
402
                        if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
6✔
403
                                w.WriteHeader(http.StatusBadRequest)
1✔
404
                                rest.RenderJSON(w, rest.JSON{"error": "can't decode request", "details": err.Error()})
1✔
405
                                return
1✔
406
                        }
1✔
407
                }
408

409
                err := updFn(req.Msg)
4✔
410
                if err != nil {
5✔
411
                        w.WriteHeader(http.StatusInternalServerError)
1✔
412
                        rest.RenderJSON(w, rest.JSON{"error": "can't update samples", "details": err.Error()})
1✔
413
                        return
1✔
414
                }
1✔
415

416
                if isHtmxRequest {
3✔
417
                        s.renderSamples(w, "samples_list")
×
418
                } else {
3✔
419
                        rest.RenderJSON(w, rest.JSON{"updated": true, "msg": req.Msg})
3✔
420
                }
3✔
421
        }
422
}
423

424
// deleteSampleHandler handles DELETE /samples request. It deletes dynamic samples both for spam and ham.
425
func (s *Server) deleteSampleHandler(delFn func(msg string) error) func(w http.ResponseWriter, r *http.Request) {
13✔
426
        return func(w http.ResponseWriter, r *http.Request) {
18✔
427
                var req struct {
5✔
428
                        Msg string `json:"msg"`
5✔
429
                }
5✔
430
                isHtmxRequest := r.Header.Get("HX-Request") == "true"
5✔
431
                if isHtmxRequest {
6✔
432
                        req.Msg = r.FormValue("msg")
1✔
433
                } else {
5✔
434
                        if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
4✔
435
                                w.WriteHeader(http.StatusBadRequest)
×
436
                                rest.RenderJSON(w, rest.JSON{"error": "can't decode request", "details": err.Error()})
×
437
                                return
×
438
                        }
×
439
                }
440

441
                if err := delFn(req.Msg); err != nil {
6✔
442
                        w.WriteHeader(http.StatusInternalServerError)
1✔
443
                        rest.RenderJSON(w, rest.JSON{"error": "can't delete sample", "details": err.Error()})
1✔
444
                        return
1✔
445
                }
1✔
446

447
                if isHtmxRequest {
5✔
448
                        s.renderSamples(w, "samples_list")
1✔
449
                } else {
4✔
450
                        rest.RenderJSON(w, rest.JSON{"deleted": true, "msg": req.Msg, "count": 1})
3✔
451
                }
3✔
452
        }
453
}
454

455
// reloadDynamicSamplesHandler handles PUT /samples request. It reloads dynamic samples from db storage.
456
func (s *Server) reloadDynamicSamplesHandler(w http.ResponseWriter, _ *http.Request) {
2✔
457
        if err := s.SpamFilter.ReloadSamples(); err != nil {
3✔
458
                w.WriteHeader(http.StatusInternalServerError)
1✔
459
                rest.RenderJSON(w, rest.JSON{"error": "can't reload samples", "details": err.Error()})
1✔
460
                return
1✔
461
        }
1✔
462
        rest.RenderJSON(w, rest.JSON{"reloaded": true})
1✔
463
}
464

465
// updateApprovedUsersHandler handles POST /users/add and /users/delete requests, it adds or removes users from approved list.
466
func (s *Server) updateApprovedUsersHandler(updFn func(ui approved.UserInfo) error) func(w http.ResponseWriter, r *http.Request) {
14✔
467
        return func(w http.ResponseWriter, r *http.Request) {
23✔
468
                req := approved.UserInfo{}
9✔
469
                isHtmxRequest := r.Header.Get("HX-Request") == "true"
9✔
470
                if isHtmxRequest {
10✔
471
                        req.UserID = r.FormValue("user_id")
1✔
472
                        req.UserName = r.FormValue("user_name")
1✔
473
                } else {
9✔
474
                        if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
9✔
475
                                w.WriteHeader(http.StatusBadRequest)
1✔
476
                                rest.RenderJSON(w, rest.JSON{"error": "can't decode request", "details": err.Error()})
1✔
477
                                return
1✔
478
                        }
1✔
479
                }
480

481
                // try to get userID from request and fallback to userName lookup if it's empty
482
                if req.UserID == "" {
12✔
483
                        req.UserID = strconv.FormatInt(s.Locator.UserIDByName(r.Context(), req.UserName), 10)
4✔
484
                }
4✔
485

486
                if req.UserID == "" || req.UserID == "0" {
9✔
487
                        if isHtmxRequest {
1✔
488
                                w.Header().Set("HX-Retarget", "#error-message")
×
489
                                fmt.Fprintln(w, "<div class='alert alert-danger'>Either userid or valid username required.</div>")
×
490
                                return
×
491
                        }
×
492
                        w.WriteHeader(http.StatusBadRequest)
1✔
493
                        rest.RenderJSON(w, rest.JSON{"error": "user ID is required"})
1✔
494
                        return
1✔
495
                }
496

497
                // add or remove user from the approved list of detector
498
                if err := updFn(req); err != nil {
7✔
499
                        w.WriteHeader(http.StatusInternalServerError)
×
500
                        rest.RenderJSON(w, rest.JSON{"error": "can't update approved users", "details": err.Error()})
×
501
                        return
×
502
                }
×
503

504
                if isHtmxRequest {
8✔
505
                        users := s.Detector.ApprovedUsers()
1✔
506
                        tmplData := struct {
1✔
507
                                ApprovedUsers      []approved.UserInfo
1✔
508
                                TotalApprovedUsers int
1✔
509
                        }{
1✔
510
                                ApprovedUsers:      users,
1✔
511
                                TotalApprovedUsers: len(users),
1✔
512
                        }
1✔
513

1✔
514
                        if err := tmpl.ExecuteTemplate(w, "users_list", tmplData); err != nil {
1✔
515
                                http.Error(w, "Error executing template", http.StatusInternalServerError)
×
516
                                return
×
517
                        }
×
518

519
                } else {
6✔
520
                        rest.RenderJSON(w, rest.JSON{"updated": true, "user_id": req.UserID, "user_name": req.UserName})
6✔
521
                }
6✔
522
        }
523
}
524

525
// removeApprovedUser is adopter for updateApprovedUsersHandler updFn
526
func (s *Server) removeApprovedUser(req approved.UserInfo) error {
2✔
527
        return s.Detector.RemoveApprovedUser(req.UserID)
2✔
528
}
2✔
529

530
// getApprovedUsersHandler handles GET /users request. It returns list of approved users.
531
func (s *Server) getApprovedUsersHandler(w http.ResponseWriter, _ *http.Request) {
1✔
532
        rest.RenderJSON(w, rest.JSON{"user_ids": s.Detector.ApprovedUsers()})
1✔
533
}
1✔
534

535
// htmlSpamCheckHandler handles GET / request.
536
// It returns rendered spam_check.html template with all the components.
537
func (s *Server) htmlSpamCheckHandler(w http.ResponseWriter, _ *http.Request) {
1✔
538
        tmplData := struct {
1✔
539
                Version string
1✔
540
        }{
1✔
541
                Version: s.Version,
1✔
542
        }
1✔
543

1✔
544
        if err := tmpl.ExecuteTemplate(w, "spam_check.html", tmplData); err != nil {
1✔
545
                log.Printf("[WARN] can't execute template: %v", err)
×
546
                http.Error(w, "Error executing template", http.StatusInternalServerError)
×
547
                return
×
548
        }
×
549
}
550

551
// htmlManageSamplesHandler handles GET /manage_samples request.
552
// It returns rendered manage_samples.html template with all the components.
553
func (s *Server) htmlManageSamplesHandler(w http.ResponseWriter, _ *http.Request) {
1✔
554
        s.renderSamples(w, "manage_samples.html")
1✔
555
}
1✔
556

557
func (s *Server) htmlManageUsersHandler(w http.ResponseWriter, _ *http.Request) {
1✔
558
        users := s.Detector.ApprovedUsers()
1✔
559
        tmplData := struct {
1✔
560
                ApprovedUsers      []approved.UserInfo
1✔
561
                TotalApprovedUsers int
1✔
562
        }{
1✔
563
                ApprovedUsers:      users,
1✔
564
                TotalApprovedUsers: len(users),
1✔
565
        }
1✔
566
        tmplData.TotalApprovedUsers = len(tmplData.ApprovedUsers)
1✔
567

1✔
568
        if err := tmpl.ExecuteTemplate(w, "manage_users.html", tmplData); err != nil {
1✔
569
                log.Printf("[WARN] can't execute template: %v", err)
×
570
                http.Error(w, "Error executing template", http.StatusInternalServerError)
×
571
                return
×
572
        }
×
573
}
574

575
func (s *Server) htmlDetectedSpamHandler(w http.ResponseWriter, r *http.Request) {
2✔
576
        ds, err := s.DetectedSpam.Read(r.Context())
2✔
577
        if err != nil {
3✔
578
                log.Printf("[ERROR] Failed to fetch detected spam: %v", err)
1✔
579
                http.Error(w, "Internal Server Error", http.StatusInternalServerError)
1✔
580
                return
1✔
581
        }
1✔
582

583
        // clean up detected spam entries
584
        for i, d := range ds {
3✔
585
                d.Text = strings.ReplaceAll(d.Text, "'", " ")
2✔
586
                d.Text = strings.ReplaceAll(d.Text, "\n", " ")
2✔
587
                d.Text = strings.ReplaceAll(d.Text, "\r", " ")
2✔
588
                d.Text = strings.ReplaceAll(d.Text, "\t", " ")
2✔
589
                d.Text = strings.ReplaceAll(d.Text, "\"", " ")
2✔
590
                d.Text = strings.ReplaceAll(d.Text, "\\", " ")
2✔
591
                ds[i] = d
2✔
592
        }
2✔
593

594
        tmplData := struct {
1✔
595
                DetectedSpamEntries []storage.DetectedSpamInfo
1✔
596
                TotalDetectedSpam   int
1✔
597
        }{
1✔
598
                DetectedSpamEntries: ds,
1✔
599
                TotalDetectedSpam:   len(ds),
1✔
600
        }
1✔
601

1✔
602
        if err := tmpl.ExecuteTemplate(w, "detected_spam.html", tmplData); err != nil {
1✔
603
                log.Printf("[WARN] can't execute template: %v", err)
×
604
                http.Error(w, "Error executing template", http.StatusInternalServerError)
×
605
                return
×
606
        }
×
607
}
608

609
func (s *Server) htmlAddDetectedSpamHandler(w http.ResponseWriter, r *http.Request) {
1✔
610
        reportErr := func(err error, _ int) {
1✔
611
                w.Header().Set("HX-Retarget", "#error-message")
×
612
                fmt.Fprintf(w, "<div class='alert alert-danger'>%s</div>", err)
×
613
        }
×
614
        msg := r.FormValue("msg")
1✔
615

1✔
616
        id, err := strconv.ParseInt(r.FormValue("id"), 10, 64)
1✔
617
        if err != nil || msg == "" {
1✔
618
                log.Printf("[WARN] bad request: %v", err)
×
619
                reportErr(fmt.Errorf("bad request: %v", err), http.StatusBadRequest)
×
620
                return
×
621
        }
×
622

623
        if err := s.SpamFilter.UpdateSpam(msg); err != nil {
1✔
624
                log.Printf("[WARN] failed to update spam samples: %v", err)
×
625
                reportErr(fmt.Errorf("can't update spam samples: %v", err), http.StatusInternalServerError)
×
626
                return
×
627

×
628
        }
×
629
        if err := s.DetectedSpam.SetAddedToSamplesFlag(r.Context(), id); err != nil {
1✔
630
                log.Printf("[WARN] failed to update detected spam: %v", err)
×
631
                reportErr(fmt.Errorf("can't update detected spam: %v", err), http.StatusInternalServerError)
×
632
                return
×
633
        }
×
634
        w.WriteHeader(http.StatusOK)
1✔
635
}
636

637
func (s *Server) htmlSettingsHandler(w http.ResponseWriter, _ *http.Request) {
1✔
638
        // get database information if StorageEngine is available
1✔
639
        var dbInfo struct {
1✔
640
                DatabaseType   string `json:"database_type"`
1✔
641
                GID            string `json:"gid"`
1✔
642
                DatabaseStatus string `json:"database_status"`
1✔
643
        }
1✔
644

1✔
645
        if s.StorageEngine != nil {
1✔
NEW
646
                // try to cast to SQL engine to get type information
×
NEW
647
                if sqlEngine, ok := s.StorageEngine.(*engine.SQL); ok {
×
NEW
648
                        dbInfo.DatabaseType = string(sqlEngine.Type())
×
NEW
649
                        dbInfo.GID = sqlEngine.GID()
×
NEW
650
                        dbInfo.DatabaseStatus = "Connected"
×
NEW
651
                } else {
×
NEW
652
                        dbInfo.DatabaseType = "Unknown"
×
NEW
653
                        dbInfo.DatabaseStatus = "Connected (unknown type)"
×
NEW
654
                }
×
655
        } else {
1✔
656
                dbInfo.DatabaseStatus = "Not connected"
1✔
657
        }
1✔
658

659
        // get backup information
660
        backupURL := "/download/backup"
1✔
661
        backupFilename := fmt.Sprintf("tg-spam-backup-%s-%s.sql.gz", dbInfo.DatabaseType, time.Now().Format("20060102-150405"))
1✔
662

1✔
663
        // get system info - uptime since server start
1✔
664
        uptime := time.Since(startTime)
1✔
665

1✔
666
        data := struct {
1✔
667
                Settings
1✔
668
                Version  string
1✔
669
                Database struct {
1✔
670
                        Type   string
1✔
671
                        GID    string
1✔
672
                        Status string
1✔
673
                }
1✔
674
                Backup struct {
1✔
675
                        URL      string
1✔
676
                        Filename string
1✔
677
                }
1✔
678
                System struct {
1✔
679
                        Uptime string
1✔
680
                }
1✔
681
        }{
1✔
682
                Settings: s.Settings,
1✔
683
                Version:  s.Version,
1✔
684
                Database: struct {
1✔
685
                        Type   string
1✔
686
                        GID    string
1✔
687
                        Status string
1✔
688
                }{
1✔
689
                        Type:   dbInfo.DatabaseType,
1✔
690
                        GID:    dbInfo.GID,
1✔
691
                        Status: dbInfo.DatabaseStatus,
1✔
692
                },
1✔
693
                Backup: struct {
1✔
694
                        URL      string
1✔
695
                        Filename string
1✔
696
                }{
1✔
697
                        URL:      backupURL,
1✔
698
                        Filename: backupFilename,
1✔
699
                },
1✔
700
                System: struct {
1✔
701
                        Uptime string
1✔
702
                }{
1✔
703
                        Uptime: formatDuration(uptime),
1✔
704
                },
1✔
705
        }
1✔
706

1✔
707
        if err := tmpl.ExecuteTemplate(w, "settings.html", data); err != nil {
1✔
708
                log.Printf("[WARN] can't execute template: %v", err)
×
709
                http.Error(w, "Error executing template", http.StatusInternalServerError)
×
710
                return
×
711
        }
×
712
}
713

714
// formatDuration formats a duration in a human-readable way
715
func formatDuration(d time.Duration) string {
1✔
716
        days := int(d.Hours() / 24)
1✔
717
        hours := int(d.Hours()) % 24
1✔
718
        minutes := int(d.Minutes()) % 60
1✔
719

1✔
720
        if days > 0 {
1✔
NEW
721
                return fmt.Sprintf("%dd %dh %dm", days, hours, minutes)
×
NEW
722
        }
×
723

724
        if hours > 0 {
1✔
NEW
725
                return fmt.Sprintf("%dh %dm", hours, minutes)
×
NEW
726
        }
×
727

728
        return fmt.Sprintf("%dm", minutes)
1✔
729
}
730

731
func (s *Server) downloadDetectedSpamHandler(w http.ResponseWriter, r *http.Request) {
3✔
732
        ctx := r.Context()
3✔
733
        spam, err := s.DetectedSpam.Read(ctx)
3✔
734
        if err != nil {
4✔
735
                w.WriteHeader(http.StatusInternalServerError)
1✔
736
                rest.RenderJSON(w, rest.JSON{"error": "can't get detected spam", "details": err.Error()})
1✔
737
                return
1✔
738
        }
1✔
739

740
        type jsonSpamInfo struct {
2✔
741
                ID        int64                `json:"id"`
2✔
742
                GID       string               `json:"gid"`
2✔
743
                Text      string               `json:"text"`
2✔
744
                UserID    int64                `json:"user_id"`
2✔
745
                UserName  string               `json:"user_name"`
2✔
746
                Timestamp time.Time            `json:"timestamp"`
2✔
747
                Added     bool                 `json:"added"`
2✔
748
                Checks    []spamcheck.Response `json:"checks"`
2✔
749
        }
2✔
750

2✔
751
        // convert entries to jsonl format with lowercase fields
2✔
752
        lines := make([]string, 0, len(spam))
2✔
753
        for _, entry := range spam {
5✔
754
                data, err := json.Marshal(jsonSpamInfo{
3✔
755
                        ID:        entry.ID,
3✔
756
                        GID:       entry.GID,
3✔
757
                        Text:      entry.Text,
3✔
758
                        UserID:    entry.UserID,
3✔
759
                        UserName:  entry.UserName,
3✔
760
                        Timestamp: entry.Timestamp,
3✔
761
                        Added:     entry.Added,
3✔
762
                        Checks:    entry.Checks,
3✔
763
                })
3✔
764
                if err != nil {
3✔
765
                        w.WriteHeader(http.StatusInternalServerError)
×
766
                        rest.RenderJSON(w, rest.JSON{"error": "can't marshal entry", "details": err.Error()})
×
767
                        return
×
768
                }
×
769
                lines = append(lines, string(data))
3✔
770
        }
771

772
        body := strings.Join(lines, "\n")
2✔
773
        w.Header().Set("Content-Type", "application/x-jsonlines")
2✔
774
        w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", "detected_spam.jsonl"))
2✔
775
        w.Header().Set("Content-Length", strconv.Itoa(len(body)))
2✔
776
        w.WriteHeader(http.StatusOK)
2✔
777
        _, _ = w.Write([]byte(body))
2✔
778
}
779

780
func (s *Server) renderSamples(w http.ResponseWriter, tmplName string) {
3✔
781
        spam, ham, err := s.SpamFilter.DynamicSamples()
3✔
782
        if err != nil {
3✔
783
                w.WriteHeader(http.StatusInternalServerError)
×
784
                rest.RenderJSON(w, rest.JSON{"error": "can't fetch samples", "details": err.Error()})
×
785
                return
×
786
        }
×
787

788
        spam, ham = s.reverseSamples(spam, ham)
3✔
789

3✔
790
        type smpleWithID struct {
3✔
791
                ID     string
3✔
792
                Sample string
3✔
793
        }
3✔
794

3✔
795
        makeID := func(s string) string {
15✔
796
                hash := sha1.New() //nolint
12✔
797
                if _, err := hash.Write([]byte(s)); err != nil {
12✔
798
                        return fmt.Sprintf("%x", s)
×
799
                }
×
800
                return fmt.Sprintf("%x", hash.Sum(nil))
12✔
801
        }
802

803
        tmplData := struct {
3✔
804
                SpamSamples      []smpleWithID
3✔
805
                HamSamples       []smpleWithID
3✔
806
                TotalHamSamples  int
3✔
807
                TotalSpamSamples int
3✔
808
        }{
3✔
809
                TotalHamSamples:  len(ham),
3✔
810
                TotalSpamSamples: len(spam),
3✔
811
        }
3✔
812
        for _, s := range spam {
9✔
813
                tmplData.SpamSamples = append(tmplData.SpamSamples, smpleWithID{ID: makeID(s), Sample: s})
6✔
814
        }
6✔
815
        for _, h := range ham {
9✔
816
                tmplData.HamSamples = append(tmplData.HamSamples, smpleWithID{ID: makeID(h), Sample: h})
6✔
817
        }
6✔
818

819
        if err := tmpl.ExecuteTemplate(w, tmplName, tmplData); err != nil {
3✔
820
                w.WriteHeader(http.StatusInternalServerError)
×
821
                rest.RenderJSON(w, rest.JSON{"error": "can't execute template", "details": err.Error()})
×
822
                return
×
823
        }
×
824
}
825

826
func (s *Server) authMiddleware(mw func(next http.Handler) http.Handler) func(next http.Handler) http.Handler {
10✔
827
        if s.AuthPasswd == "" {
16✔
828
                return func(next http.Handler) http.Handler {
102✔
829
                        return next
96✔
830
                }
96✔
831
        }
832
        return func(next http.Handler) http.Handler {
68✔
833
                return mw(next)
64✔
834
        }
64✔
835
}
836

837
// reverseSamples returns reversed lists of spam and ham samples
838
func (s *Server) reverseSamples(spam, ham []string) (revSpam, revHam []string) {
6✔
839
        revSpam = make([]string, len(spam))
6✔
840
        revHam = make([]string, len(ham))
6✔
841

6✔
842
        for i, j := 0, len(spam)-1; i < len(spam); i, j = i+1, j-1 {
16✔
843
                revSpam[i] = spam[j]
10✔
844
        }
10✔
845
        for i, j := 0, len(ham)-1; i < len(ham); i, j = i+1, j-1 {
16✔
846
                revHam[i] = ham[j]
10✔
847
        }
10✔
848
        return revSpam, revHam
6✔
849
}
850

851
// staticFS is a filtered filesystem that only exposes specific static files
852
type staticFS struct {
853
        fs        fs.FS
854
        urlToPath map[string]string
855
}
856

857
// staticFileMapping defines a mapping between URL path and filesystem path
858
type staticFileMapping struct {
859
        urlPath     string
860
        filesysPath string
861
}
862

863
func newStaticFS(fsys fs.FS, files ...staticFileMapping) *staticFS {
5✔
864
        urlToPath := make(map[string]string)
5✔
865
        for _, f := range files {
20✔
866
                urlToPath[f.urlPath] = f.filesysPath
15✔
867
        }
15✔
868

869
        return &staticFS{
5✔
870
                fs:        fsys,
5✔
871
                urlToPath: urlToPath,
5✔
872
        }
5✔
873
}
874

875
func (sfs *staticFS) Open(name string) (fs.File, error) {
5✔
876
        name = path.Clean("/" + name)[1:]
5✔
877
        if fsPath, ok := sfs.urlToPath[name]; ok {
8✔
878
                return sfs.fs.Open(fsPath)
3✔
879
        }
3✔
880
        return nil, fs.ErrNotExist
2✔
881
}
882

883
// GenerateRandomPassword generates a random password of a given length
884
func GenerateRandomPassword(length int) (string, error) {
2✔
885
        const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+"
2✔
886

2✔
887
        var password strings.Builder
2✔
888
        charsetSize := big.NewInt(int64(len(charset)))
2✔
889

2✔
890
        for i := 0; i < length; i++ {
66✔
891
                randomNumber, err := rand.Int(rand.Reader, charsetSize)
64✔
892
                if err != nil {
64✔
893
                        return "", err
×
894
                }
×
895

896
                password.WriteByte(charset[randomNumber.Int64()])
64✔
897
        }
898

899
        return password.String(), nil
2✔
900
}
901

902
// downloadBackupHandler streams a database backup as an SQL file with gzip compression
903
// Files are always compressed and always have .gz extension to ensure consistency
904
func (s *Server) downloadBackupHandler(w http.ResponseWriter, r *http.Request) {
2✔
905
        if s.StorageEngine == nil {
3✔
906
                w.WriteHeader(http.StatusInternalServerError)
1✔
907
                rest.RenderJSON(w, rest.JSON{"error": "storage engine not available"})
1✔
908
                return
1✔
909
        }
1✔
910

911
        // set filename based on database type and timestamp
912
        dbType := "db"
1✔
913
        sqlEng, ok := s.StorageEngine.(*engine.SQL)
1✔
914
        if ok {
1✔
915
                dbType = string(sqlEng.Type())
×
916
        }
×
917
        timestamp := time.Now().Format("20060102-150405")
1✔
918

1✔
919
        // always use a .gz extension as the content is always compressed
1✔
920
        filename := fmt.Sprintf("tg-spam-backup-%s-%s.sql.gz", dbType, timestamp)
1✔
921

1✔
922
        // set headers for file download - note we're using application/octet-stream
1✔
923
        // instead of application/sql to prevent browsers from trying to interpret the file
1✔
924
        w.Header().Set("Content-Type", "application/octet-stream")
1✔
925
        w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
1✔
926
        w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
1✔
927
        w.Header().Set("Pragma", "no-cache")
1✔
928
        w.Header().Set("Expires", "0")
1✔
929

1✔
930
        // create a gzip writer that streams to response
1✔
931
        gzipWriter := gzip.NewWriter(w)
1✔
932
        defer func() {
2✔
933
                if err := gzipWriter.Close(); err != nil {
1✔
934
                        log.Printf("[ERROR] failed to close gzip writer: %v", err)
×
935
                }
×
936
        }()
937

938
        // stream backup directly to response through gzip
939
        if err := s.StorageEngine.Backup(r.Context(), gzipWriter); err != nil {
1✔
940
                log.Printf("[ERROR] failed to create backup: %v", err)
×
941
                // we've already started writing the response, so we can't send a proper error response
×
942
                return
×
943
        }
×
944

945
        // flush the gzip writer to ensure all data is written
946
        if err := gzipWriter.Flush(); err != nil {
1✔
947
                log.Printf("[ERROR] failed to flush gzip writer: %v", err)
×
948
        }
×
949
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc