Skip to content

Commit 1421ad1

Browse files
authored
fix: code adaptability issue fixes. (#54)
* fix: code adaptability issue fixes. golangci-lint config has been refactored to not include things checked by SonarLint so as to not have dual functionality. * fix: fixed issue we'd read a file of arbitrary size when processing an RPC call body. We now have a configurable limit defaulting to 20 megs * fix: fixed several code adaptability issues * fix: fixed remaining linting issues * fix: refactored switch statement
1 parent a1ed308 commit 1421ad1

File tree

17 files changed

+213
-200
lines changed

17 files changed

+213
-200
lines changed

.golangci.yaml

+11-34
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ output:
88
path: build/report.xml
99
- format: colored-line-number
1010
linters:
11+
disable-all: true
1112
enable:
1213
- errcheck
1314
- gosimple
@@ -16,43 +17,19 @@ linters:
1617
- staticcheck
1718
- unused
1819
- goimports
19-
- goheader
2020
- gosec
2121
- forbidigo
22-
- goconst
2322
- godot
24-
issues:
25-
exclude-rules:
26-
- linters:
27-
- goheader
28-
path: cache.go # This file already has a header with another license
23+
- errname
24+
- errorlint
25+
- asasalint
26+
- asciicheck
27+
- bidichk
28+
- errchkjson
29+
- gochecknoinits
30+
# - wrapcheck
31+
- sloglint
32+
- tenv
2933
linters-settings:
3034
goimports:
3135
local-prefixes: github.com/madsrc/sophrosyne
32-
gofmt:
33-
simplify: true
34-
rewrite-rules:
35-
- pattern: 'interface{}'
36-
replacement: 'any'
37-
- pattern: 'a[b:len(a)]'
38-
replacement: 'a[b:]'
39-
goheader:
40-
values:
41-
const:
42-
AUTHOR: 'Mads R. Havmand'
43-
template: |-
44-
Sophrosyne
45-
Copyright (C) {{ YEAR }} {{ AUTHOR }}
46-
47-
This program is free software: you can redistribute it and/or modify
48-
it under the terms of the GNU Affero General Public License as published by
49-
the Free Software Foundation, either version 3 of the License, or
50-
(at your option) any later version.
51-
52-
This program is distributed in the hope that it will be useful,
53-
but WITHOUT ANY WARRANTY; without even the implied warranty of
54-
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
55-
GNU Affero General Public License for more details.
56-
57-
You should have received a copy of the GNU Affero General Public License
58-
along with this program. If not, see <http://www.gnu.org/licenses/>.

.idea/sonarlint.xml

+6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.mise/tasks/dev/lint

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/bin/sh
2-
# mise sources=["go.mod", "go.sum", "internal/**/*", "cmd/**/*", "*.go"]
2+
# mise sources=["go.mod", "go.sum", "internal/**/*", "cmd/**/*", "*.go", ".golangci.yaml]
33
# mise outputs=["build/report.xml"]
44

55
nofail=1

cmd/sophrosyne/main.go

+6-3
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,9 @@ func main() {
9292
validate := validator.NewValidator()
9393

9494
config, err := getConfig(c.String("config"), nil, c.StringSlice("secretfiles"), validate)
95+
if err != nil {
96+
return err
97+
}
9598
migrationService, err := migrate.NewMigrationService(config)
9699
if err != nil {
97100
return err
@@ -102,7 +105,7 @@ func main() {
102105
if !errors.Is(err, migrate.ErrNoChange) {
103106
return err
104107
} else {
105-
_, _ = fmt.Fprintf(c.App.Writer, "No migrations to apply")
108+
_, _ = fmt.Fprint(c.App.Writer, "No migrations to apply")
106109
return nil
107110
}
108111
}
@@ -116,7 +119,7 @@ func main() {
116119
} else {
117120
msg = fmt.Sprintf("%s\n", msg)
118121
}
119-
_, _ = fmt.Fprintf(c.App.Writer, msg)
122+
_, _ = fmt.Fprint(c.App.Writer, msg)
120123
return nil
121124
},
122125
},
@@ -345,7 +348,7 @@ func run(c *cli.Context) error {
345348
config,
346349
userService,
347350
logger,
348-
http.RPCHandler(logger, rpcServer),
351+
http.RPCHandler(logger, rpcServer, config),
349352
),
350353
),
351354
),

config.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,11 @@ var DefaultConfig = map[string]interface{}{
7777
"services.profiles.cacheTTL": 100,
7878
"services.checks.pageSize": 2,
7979
"services.checks.cacheTTL": 100,
80+
"server.maxBodySize": 20 * megabyte,
8081
}
8182

83+
const megabyte int64 = 1048576
84+
8285
// The Config struct is used to store the configuration of the application.
8386
//
8487
// The ConfigProvider interface is used to retrieve the configuration of the
@@ -103,7 +106,8 @@ type Config struct {
103106
Name string `key:"name" validate:"required"`
104107
} `key:"database"`
105108
Server struct {
106-
Port int `key:"port" validate:"required,min=1,max=65535"`
109+
Port int `key:"port" validate:"required,min=1,max=65535"`
110+
MaxBodySize int64 `key:"maxBodySize" validate:"required,min=1"` // in bytes
107111
} `key:"server"`
108112
Logging struct {
109113
Enabled bool `key:"enabled"`

internal/configProvider/config.go

+7-7
Original file line numberDiff line numberDiff line change
@@ -49,22 +49,22 @@ func envExtractor(s string, v string) (string, interface{}) {
4949
}
5050

5151
func loadConfig(k *koanf.Koanf, defaultConfig map[string]interface{}, yamlFile koanf.Provider, overwrites map[string]interface{}, secretFiles []string) error {
52-
k.Load(confmap.Provider(defaultConfig, sophrosyne.ConfigDelimiter), nil)
52+
_ = k.Load(confmap.Provider(defaultConfig, sophrosyne.ConfigDelimiter), nil)
5353

5454
if err := loadYamlConfig(k, yamlFile); err != nil {
5555
return err
5656
}
5757

58-
k.Load(env.ProviderWithValue(sophrosyne.ConfigEnvironmentPrefix, sophrosyne.ConfigDelimiter, envExtractor), nil)
58+
_ = k.Load(env.ProviderWithValue(sophrosyne.ConfigEnvironmentPrefix, sophrosyne.ConfigDelimiter, envExtractor), nil)
5959

60-
k.Load(confmap.Provider(overwrites, sophrosyne.ConfigDelimiter), nil)
60+
_ = k.Load(confmap.Provider(overwrites, sophrosyne.ConfigDelimiter), nil)
6161

6262
for _, secretFile := range secretFiles {
6363
secret, err := secretFromFile(secretFile)
6464
if err != nil {
6565
return err
6666
}
67-
k.Load(confmap.Provider(secret, sophrosyne.ConfigDelimiter), nil)
67+
_ = k.Load(confmap.Provider(secret, sophrosyne.ConfigDelimiter), nil)
6868
}
6969

7070
return nil
@@ -97,7 +97,7 @@ func NewConfigProvider(yamlFilePath string, overwrites map[string]interface{}, s
9797
return nil, err
9898
}
9999

100-
yamlFile.Watch(func(event interface{}, err error) {
100+
_ = yamlFile.Watch(func(event interface{}, err error) {
101101
if err != nil {
102102
// Error occurred when watching the file.
103103
return
@@ -111,7 +111,7 @@ func NewConfigProvider(yamlFilePath string, overwrites map[string]interface{}, s
111111
return
112112
}
113113
newConf := &sophrosyne.Config{}
114-
cfgProv.k.UnmarshalWithConf("", newConf, koanf.UnmarshalConf{Tag: "key"})
114+
_ = cfgProv.k.UnmarshalWithConf("", newConf, koanf.UnmarshalConf{Tag: "key"})
115115
err = cfgProv.validate.Validate(newConf)
116116
if err != nil {
117117
// Error occurred when validating the config.
@@ -124,7 +124,7 @@ func NewConfigProvider(yamlFilePath string, overwrites map[string]interface{}, s
124124
*cfgProv.config = *newConf
125125
})
126126

127-
cfgProv.k.UnmarshalWithConf("", cfgProv.config, koanf.UnmarshalConf{Tag: "key"})
127+
_ = cfgProv.k.UnmarshalWithConf("", cfgProv.config, koanf.UnmarshalConf{Tag: "key"})
128128

129129
err := cfgProv.validate.Validate(cfgProv.config)
130130
if err != nil {

internal/http/http.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -84,10 +84,10 @@ func (s *Server) Handle(path string, handler http.Handler) {
8484
const JSONContentType = "application/json"
8585
const PlainTextContentType = "text/plain"
8686

87-
func RPCHandler(logger *slog.Logger, rpcService sophrosyne.RPCServer) http.Handler {
87+
func RPCHandler(logger *slog.Logger, rpcService sophrosyne.RPCServer, config *sophrosyne.Config) http.Handler {
8888
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
8989

90-
body, err := io.ReadAll(r.Body) // Find a way to implement a limit on the body size
90+
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, config.Server.MaxBodySize))
9191
if err != nil {
9292
logger.ErrorContext(r.Context(), "failed to read request body", "error", err)
9393
WriteInternalServerError(r.Context(), w, logger)

internal/pgx/checks.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ func (p *CheckService) GetChecks(ctx context.Context, cursor *sophrosyne.Databas
132132
cursor = &sophrosyne.DatabaseCursor{}
133133
}
134134
p.logger.DebugContext(ctx, "getting checks", "cursor", cursor)
135-
rows, err := p.pool.Query(ctx, `SELECT * FROM checks WHERE id > $1 AND deleted_at IS NULL ORDER BY id ASC LIMIT $2`, cursor.Position, p.config.Services.Checks.PageSize+1)
135+
rows, _ := p.pool.Query(ctx, `SELECT * FROM checks WHERE id > $1 AND deleted_at IS NULL ORDER BY id ASC LIMIT $2`, cursor.Position, p.config.Services.Checks.PageSize+1)
136136
checks, err := pgx.CollectRows(rows, pgx.RowToStructByNameLax[sophrosyne.Check])
137137
if err != nil {
138138
return []sophrosyne.Check{}, err
@@ -154,7 +154,9 @@ func (p *CheckService) CreateCheck(ctx context.Context, check sophrosyne.CreateC
154154
if err != nil {
155155
return sophrosyne.Check{}, err
156156
}
157-
defer tx.Rollback(ctx)
157+
defer func() {
158+
_ = tx.Rollback(ctx)
159+
}()
158160

159161
rows, _ := tx.Query(ctx, `INSERT INTO checks (name, upstream_services) VALUES ($1, $2) RETURNING *`, check.Name, check.UpstreamServices)
160162
retP, err := pgx.CollectOneRow(rows, pgx.RowToAddrOfStructByNameLax[checkDbEntry])
@@ -220,7 +222,9 @@ func (p *CheckService) UpdateCheck(ctx context.Context, check sophrosyne.UpdateC
220222
if err != nil {
221223
return sophrosyne.Check{}, err
222224
}
223-
defer tx.Rollback(ctx)
225+
defer func() {
226+
_ = tx.Rollback(ctx)
227+
}()
224228

225229
rows, _ := tx.Query(ctx, `SELECT id FROM checks WHERE name = $1 AND deleted_at IS NULL`, check.Name)
226230
pp, err := pgx.CollectOneRow(rows, pgx.RowToStructByNameLax[sophrosyne.Check])

internal/pgx/pgx.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ func (s *UserService) createRootUser(ctx context.Context) error {
253253
}
254254
defer func() {
255255
s.logger.DebugContext(ctx, "rolling back transaction")
256-
tx.Rollback(ctx)
256+
_ = tx.Rollback(ctx)
257257
}()
258258
// Check if root user exists and exit early if it does
259259
var exists bool

internal/pgx/profiles.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ func (p *ProfileService) GetProfiles(ctx context.Context, cursor *sophrosyne.Dat
127127
cursor = &sophrosyne.DatabaseCursor{}
128128
}
129129
p.logger.DebugContext(ctx, "getting profiles", "cursor", cursor)
130-
rows, err := p.pool.Query(ctx, `SELECT * FROM profiles WHERE id > $1 AND deleted_at IS NULL ORDER BY id ASC LIMIT $2`, cursor.Position, p.config.Services.Profiles.PageSize+1)
130+
rows, _ := p.pool.Query(ctx, `SELECT * FROM profiles WHERE id > $1 AND deleted_at IS NULL ORDER BY id ASC LIMIT $2`, cursor.Position, p.config.Services.Profiles.PageSize+1)
131131
profiles, err := pgx.CollectRows(rows, pgx.RowToStructByNameLax[sophrosyne.Profile])
132132
if err != nil {
133133
return []sophrosyne.Profile{}, err
@@ -149,7 +149,9 @@ func (p *ProfileService) CreateProfile(ctx context.Context, profile sophrosyne.C
149149
if err != nil {
150150
return sophrosyne.Profile{}, err
151151
}
152-
defer tx.Rollback(ctx)
152+
defer func() {
153+
_ = tx.Rollback(ctx)
154+
}()
153155

154156
rows, _ := tx.Query(ctx, `INSERT INTO profiles (name) VALUES ($1) RETURNING *`, profile.Name)
155157
retP, err := pgx.CollectOneRow(rows, pgx.RowToAddrOfStructByNameLax[sophrosyne.Profile])
@@ -190,7 +192,9 @@ func (p *ProfileService) UpdateProfile(ctx context.Context, profile sophrosyne.U
190192
if err != nil {
191193
return sophrosyne.Profile{}, err
192194
}
193-
defer tx.Rollback(ctx)
195+
defer func() {
196+
_ = tx.Rollback(ctx)
197+
}()
194198

195199
rows, _ := tx.Query(ctx, `SELECT id FROM profiles WHERE name = $1 AND deleted_at IS NULL`, profile.Name)
196200
pp, err := pgx.CollectOneRow(rows, pgx.RowToStructByNameLax[sophrosyne.Profile])

0 commit comments

Comments
 (0)