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

umputun / tg-spam / 13687371261

05 Mar 2025 11:09PM UTC coverage: 81.677% (-0.2%) from 81.876%
13687371261

push

github

umputun
Add detailed documentation to SQLite to PostgreSQL converter

4355 of 5332 relevant lines covered (81.68%)

62.94 hits per line

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

88.37
/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
        Type() engine.Type
145
        BackupSqliteAsPostgres(ctx context.Context, w io.Writer) error
146
}
147

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

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

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

174
        router = s.routes(router) // setup routes
3✔
175

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

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

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

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

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

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

224
                authApi.HandleFunc("GET /samples", s.getDynamicSamplesHandler)    // get dynamic samples
5✔
225
                authApi.HandleFunc("PUT /samples", s.reloadDynamicSamplesHandler) // reload samples
5✔
226

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

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

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

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

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

266
        return router
5✔
267
}
268

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

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

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

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

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

308
        // render result for HTMX request
309
        resultDisplay := CheckResultDisplay{
1✔
310
                Spam:   spam,
1✔
311
                Checks: cr,
1✔
312
        }
1✔
313

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5✔
619
        id, err := strconv.ParseInt(r.FormValue("id"), 10, 64)
5✔
620
        if err != nil || msg == "" {
7✔
621
                log.Printf("[WARN] bad request: %v", err)
2✔
622
                reportErr(fmt.Errorf("bad request: %v", err), http.StatusBadRequest)
2✔
623
                return
2✔
624
        }
2✔
625

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

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

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

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

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

4✔
666
        // get system info - uptime since server start
4✔
667
        uptime := time.Since(startTime)
4✔
668

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

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

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

12✔
723
        if days > 0 {
15✔
724
                return fmt.Sprintf("%dd %dh %dm", days, hours, minutes)
3✔
725
        }
3✔
726

727
        if hours > 0 {
11✔
728
                return fmt.Sprintf("%dh %dm", hours, minutes)
2✔
729
        }
2✔
730

731
        return fmt.Sprintf("%dm", minutes)
7✔
732
}
733

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

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

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

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

783
// downloadBackupHandler streams a database backup as an SQL file with gzip compression
784
// Files are always compressed and always have .gz extension to ensure consistency
785
func (s *Server) downloadBackupHandler(w http.ResponseWriter, r *http.Request) {
2✔
786
        if s.StorageEngine == nil {
3✔
787
                w.WriteHeader(http.StatusInternalServerError)
1✔
788
                rest.RenderJSON(w, rest.JSON{"error": "storage engine not available"})
1✔
789
                return
1✔
790
        }
1✔
791

792
        // set filename based on database type and timestamp
793
        dbType := "db"
1✔
794
        sqlEng, ok := s.StorageEngine.(*engine.SQL)
1✔
795
        if ok {
1✔
796
                dbType = string(sqlEng.Type())
×
797
        }
×
798
        timestamp := time.Now().Format("20060102-150405")
1✔
799

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

1✔
803
        // set headers for file download - note we're using application/octet-stream
1✔
804
        // instead of application/sql to prevent browsers from trying to interpret the file
1✔
805
        w.Header().Set("Content-Type", "application/octet-stream")
1✔
806
        w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
1✔
807
        w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
1✔
808
        w.Header().Set("Pragma", "no-cache")
1✔
809
        w.Header().Set("Expires", "0")
1✔
810

1✔
811
        // create a gzip writer that streams to response
1✔
812
        gzipWriter := gzip.NewWriter(w)
1✔
813
        defer func() {
2✔
814
                if err := gzipWriter.Close(); err != nil {
1✔
815
                        log.Printf("[ERROR] failed to close gzip writer: %v", err)
×
816
                }
×
817
        }()
818

819
        // stream backup directly to response through gzip
820
        if err := s.StorageEngine.Backup(r.Context(), gzipWriter); err != nil {
1✔
821
                log.Printf("[ERROR] failed to create backup: %v", err)
×
822
                // we've already started writing the response, so we can't send a proper error response
×
823
                return
×
824
        }
×
825

826
        // flush the gzip writer to ensure all data is written
827
        if err := gzipWriter.Flush(); err != nil {
1✔
828
                log.Printf("[ERROR] failed to flush gzip writer: %v", err)
×
829
        }
×
830
}
831

832
// downloadExportToPostgresHandler streams a PostgreSQL-compatible export from a SQLite database
833
func (s *Server) downloadExportToPostgresHandler(w http.ResponseWriter, r *http.Request) {
3✔
834
        if s.StorageEngine == nil {
4✔
835
                w.WriteHeader(http.StatusInternalServerError)
1✔
836
                rest.RenderJSON(w, rest.JSON{"error": "storage engine not available"})
1✔
837
                return
1✔
838
        }
1✔
839

840
        // check if the database is SQLite
841
        if s.StorageEngine.Type() != engine.Sqlite {
3✔
842
                w.WriteHeader(http.StatusBadRequest)
1✔
843
                rest.RenderJSON(w, rest.JSON{"error": "source database must be SQLite"})
1✔
844
                return
1✔
845
        }
1✔
846

847
        // set filename based on timestamp
848
        timestamp := time.Now().Format("20060102-150405")
1✔
849
        filename := fmt.Sprintf("tg-spam-sqlite-to-postgres-%s.sql.gz", timestamp)
1✔
850

1✔
851
        // set headers for file download
1✔
852
        w.Header().Set("Content-Type", "application/octet-stream")
1✔
853
        w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
1✔
854
        w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
1✔
855
        w.Header().Set("Pragma", "no-cache")
1✔
856
        w.Header().Set("Expires", "0")
1✔
857

1✔
858
        // create a gzip writer that streams to response
1✔
859
        gzipWriter := gzip.NewWriter(w)
1✔
860
        defer func() {
2✔
861
                if err := gzipWriter.Close(); err != nil {
1✔
862
                        log.Printf("[ERROR] failed to close gzip writer: %v", err)
×
863
                }
×
864
        }()
865

866
        // stream export directly to response through gzip
867
        if err := s.StorageEngine.BackupSqliteAsPostgres(r.Context(), gzipWriter); err != nil {
1✔
868
                log.Printf("[ERROR] failed to create export: %v", err)
×
869
                // we've already started writing the response, so we can't send a proper error response
×
870
                return
×
871
        }
×
872

873
        // flush the gzip writer to ensure all data is written
874
        if err := gzipWriter.Flush(); err != nil {
1✔
875
                log.Printf("[ERROR] failed to flush gzip writer: %v", err)
×
876
        }
×
877
}
878

879
func (s *Server) renderSamples(w http.ResponseWriter, tmplName string) {
6✔
880
        spam, ham, err := s.SpamFilter.DynamicSamples()
6✔
881
        if err != nil {
7✔
882
                w.WriteHeader(http.StatusInternalServerError)
1✔
883
                rest.RenderJSON(w, rest.JSON{"error": "can't fetch samples", "details": err.Error()})
1✔
884
                return
1✔
885
        }
1✔
886

887
        spam, ham = s.reverseSamples(spam, ham)
5✔
888

5✔
889
        type smpleWithID struct {
5✔
890
                ID     string
5✔
891
                Sample string
5✔
892
        }
5✔
893

5✔
894
        makeID := func(s string) string {
19✔
895
                hash := sha1.New() //nolint
14✔
896
                if _, err := hash.Write([]byte(s)); err != nil {
14✔
897
                        return fmt.Sprintf("%x", s)
×
898
                }
×
899
                return fmt.Sprintf("%x", hash.Sum(nil))
14✔
900
        }
901

902
        tmplData := struct {
5✔
903
                SpamSamples      []smpleWithID
5✔
904
                HamSamples       []smpleWithID
5✔
905
                TotalHamSamples  int
5✔
906
                TotalSpamSamples int
5✔
907
        }{
5✔
908
                TotalHamSamples:  len(ham),
5✔
909
                TotalSpamSamples: len(spam),
5✔
910
        }
5✔
911
        for _, s := range spam {
12✔
912
                tmplData.SpamSamples = append(tmplData.SpamSamples, smpleWithID{ID: makeID(s), Sample: s})
7✔
913
        }
7✔
914
        for _, h := range ham {
12✔
915
                tmplData.HamSamples = append(tmplData.HamSamples, smpleWithID{ID: makeID(h), Sample: h})
7✔
916
        }
7✔
917

918
        if err := tmpl.ExecuteTemplate(w, tmplName, tmplData); err != nil {
6✔
919
                w.WriteHeader(http.StatusInternalServerError)
1✔
920
                rest.RenderJSON(w, rest.JSON{"error": "can't execute template", "details": err.Error()})
1✔
921
                return
1✔
922
        }
1✔
923
}
924

925
func (s *Server) authMiddleware(mw func(next http.Handler) http.Handler) func(next http.Handler) http.Handler {
10✔
926
        if s.AuthPasswd == "" {
16✔
927
                return func(next http.Handler) http.Handler {
105✔
928
                        return next
99✔
929
                }
99✔
930
        }
931
        return func(next http.Handler) http.Handler {
70✔
932
                return mw(next)
66✔
933
        }
66✔
934
}
935

936
// reverseSamples returns reversed lists of spam and ham samples
937
func (s *Server) reverseSamples(spam, ham []string) (revSpam, revHam []string) {
8✔
938
        revSpam = make([]string, len(spam))
8✔
939
        revHam = make([]string, len(ham))
8✔
940

8✔
941
        for i, j := 0, len(spam)-1; i < len(spam); i, j = i+1, j-1 {
19✔
942
                revSpam[i] = spam[j]
11✔
943
        }
11✔
944
        for i, j := 0, len(ham)-1; i < len(ham); i, j = i+1, j-1 {
19✔
945
                revHam[i] = ham[j]
11✔
946
        }
11✔
947
        return revSpam, revHam
8✔
948
}
949

950
// staticFS is a filtered filesystem that only exposes specific static files
951
type staticFS struct {
952
        fs        fs.FS
953
        urlToPath map[string]string
954
}
955

956
// staticFileMapping defines a mapping between URL path and filesystem path
957
type staticFileMapping struct {
958
        urlPath     string
959
        filesysPath string
960
}
961

962
func newStaticFS(fsys fs.FS, files ...staticFileMapping) *staticFS {
5✔
963
        urlToPath := make(map[string]string)
5✔
964
        for _, f := range files {
20✔
965
                urlToPath[f.urlPath] = f.filesysPath
15✔
966
        }
15✔
967

968
        return &staticFS{
5✔
969
                fs:        fsys,
5✔
970
                urlToPath: urlToPath,
5✔
971
        }
5✔
972
}
973

974
func (sfs *staticFS) Open(name string) (fs.File, error) {
5✔
975
        name = path.Clean("/" + name)[1:]
5✔
976
        if fsPath, ok := sfs.urlToPath[name]; ok {
8✔
977
                return sfs.fs.Open(fsPath)
3✔
978
        }
3✔
979
        return nil, fs.ErrNotExist
2✔
980
}
981

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

2✔
986
        var password strings.Builder
2✔
987
        charsetSize := big.NewInt(int64(len(charset)))
2✔
988

2✔
989
        for i := 0; i < length; i++ {
66✔
990
                randomNumber, err := rand.Int(rand.Reader, charsetSize)
64✔
991
                if err != nil {
64✔
992
                        return "", err
×
993
                }
×
994

995
                password.WriteByte(charset[randomNumber.Int64()])
64✔
996
        }
997

998
        return password.String(), nil
2✔
999
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc