PHASE-8: Instrumenting #9

Merged
krendelhoff merged 10 commits from phase-8-instrumenting into master 2025-08-23 13:54:08 +03:00
6 changed files with 276 additions and 146 deletions
Showing only changes of commit 0bf84576a8 - Show all commits

22
config.yaml Normal file
View file

@ -0,0 +1,22 @@
server:
address: ":8080"
timeouts:
read: 5s
write: 5s
connection: 15s
pow:
difficulty: 25
max_difficulty: 30
ttl: 5m
hmac_secret: "development-secret-change-in-production"
quotes:
timeout: 10s
metrics:
address: ":8081"
logging:
level: "info"
format: "text"

72
internal/config/config.go Normal file
View file

@ -0,0 +1,72 @@
package config
import (
"time"
"github.com/ilyakaznacheev/cleanenv"
)
type Config struct {
Server ServerConfig `yaml:"server"`
PoW PoWConfig `yaml:"pow"`
Quotes QuotesConfig `yaml:"quotes"`
Metrics MetricsConfig `yaml:"metrics"`
Logging LoggingConfig `yaml:"logging"`
}
type ServerConfig struct {
Address string `yaml:"address" env:"SERVER_ADDRESS" env-default:":8080"`
Timeouts TimeoutConfig `yaml:"timeouts"`
}
type TimeoutConfig struct {
Read time.Duration `yaml:"read" env:"SERVER_READ_TIMEOUT" env-default:"5s"`
Write time.Duration `yaml:"write" env:"SERVER_WRITE_TIMEOUT" env-default:"5s"`
Connection time.Duration `yaml:"connection" env:"SERVER_CONNECTION_TIMEOUT" env-default:"15s"`
}
type PoWConfig struct {
Difficulty int `yaml:"difficulty" env:"POW_DIFFICULTY" env-default:"4"`
MaxDifficulty int `yaml:"max_difficulty" env:"POW_MAX_DIFFICULTY" env-default:"10"`
TTL time.Duration `yaml:"ttl" env:"POW_TTL" env-default:"5m"`
HMACSecret string `yaml:"hmac_secret" env:"POW_HMAC_SECRET" env-default:"development-secret-change-in-production"`
}
type QuotesConfig struct {
Timeout time.Duration `yaml:"timeout" env:"QUOTES_TIMEOUT" env-default:"10s"`
}
type MetricsConfig struct {
Address string `yaml:"address" env:"METRICS_ADDRESS" env-default:":8081"`
}
type LoggingConfig struct {
Level string `yaml:"level" env:"LOG_LEVEL" env-default:"info"`
Format string `yaml:"format" env:"LOG_FORMAT" env-default:"text"`
}
func Load(configPath string) (*Config, error) {
cfg := &Config{}
if configPath != "" {
err := cleanenv.ReadConfig(configPath, cfg)
if err != nil {
return nil, err
}
} else {
err := cleanenv.ReadEnv(cfg)
if err != nil {
return nil, err
}
}
return cfg, nil
}
func (c *Config) ToServerConfig() *ServerConfig {
return &c.Server
}
func (c *Config) ToPoWConfig() *PoWConfig {
return &c.PoW
}

View file

@ -17,15 +17,3 @@ type TimeoutConfig struct {
// Connection timeout is the maximum total connection lifetime
Connection time.Duration
}
// DefaultConfig returns default server configuration
func DefaultConfig() *Config {
return &Config{
Address: ":8080",
Timeouts: TimeoutConfig{
Read: 5 * time.Second,
Write: 5 * time.Second,
Connection: 15 * time.Second,
},
}
}

View file

@ -29,12 +29,6 @@ type TCPServer struct {
// Option is a functional option for configuring TCPServer
type option func(*TCPServer)
// WithConfig sets a custom configuration
func WithConfig(config *Config) option {
return func(s *TCPServer) {
s.config = config
}
}
// WithLogger sets a custom logger
func WithLogger(logger *slog.Logger) option {
@ -43,10 +37,10 @@ func WithLogger(logger *slog.Logger) option {
}
}
// NewTCPServer creates a new TCP server with optional configuration
func NewTCPServer(wisdomService *service.WisdomService, opts ...option) *TCPServer {
// NewTCPServer creates a new TCP server with required configuration
func NewTCPServer(wisdomService *service.WisdomService, config *Config, opts ...option) *TCPServer {
server := &TCPServer{
config: DefaultConfig(),
config: config,
wisdomApplication: application.NewWisdomApplication(wisdomService),
decoder: protocol.NewMessageDecoder(),
logger: slog.Default(),

View file

@ -14,13 +14,16 @@ import (
func TestSlowlorisProtection_SlowReader(t *testing.T) {
// Setup server with very short read timeout for testing
config := server.DefaultConfig()
config.Address = ":0"
config.Timeouts.Read = 100 * time.Millisecond
config.Timeouts.Write = 5 * time.Second
config.Timeouts.Connection = 15 * time.Second
serverConfig := &server.Config{
Address: ":0",
Timeouts: server.TimeoutConfig{
Read: 100 * time.Millisecond,
Write: 5 * time.Second,
Connection: 15 * time.Second,
},
}
srv := setupTestServerWithConfig(t, config)
srv := setupTestServerWithConfig(t, serverConfig)
defer srv.Stop()
// Connect to server
@ -47,13 +50,16 @@ func TestSlowlorisProtection_SlowReader(t *testing.T) {
func TestSlowlorisProtection_SlowWriter(t *testing.T) {
// Setup server with very short write timeout for testing
config := server.DefaultConfig()
config.Address = ":0"
config.Timeouts.Read = 5 * time.Second
config.Timeouts.Write = 100 * time.Millisecond
config.Timeouts.Connection = 15 * time.Second
serverConfig := &server.Config{
Address: ":0",
Timeouts: server.TimeoutConfig{
Read: 5 * time.Second,
Write: 100 * time.Millisecond,
Connection: 15 * time.Second,
},
}
srv := setupTestServerWithConfig(t, config)
srv := setupTestServerWithConfig(t, serverConfig)
defer srv.Stop()
// Connect to server but don't read responses (simulate slow writer client)
@ -66,133 +72,164 @@ func TestSlowlorisProtection_SlowWriter(t *testing.T) {
err = challengeReq.Encode(conn)
require.NoError(t, err)
// Don't read the response to simulate slow writer
// Server should timeout when trying to write response
// Don't read the response - this should trigger write timeout
time.Sleep(200 * time.Millisecond)
// Try to send another request - connection should be closed
err = challengeReq.Encode(conn)
// Try to write again - connection should be timed out
_, err = conn.Write([]byte{0x01})
// Verify connection is closed
buffer := make([]byte, 1024)
conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
_, err = conn.Read(buffer)
assert.Error(t, err, "Connection should be closed due to slow writing")
}
func TestSlowlorisProtection_ConnectionTimeout(t *testing.T) {
// Setup server with very short connection timeout
config := server.DefaultConfig()
config.Address = ":0"
config.Timeouts.Read = 5 * time.Second
config.Timeouts.Write = 5 * time.Second
config.Timeouts.Connection = 100 * time.Millisecond
func TestSlowlorisProtection_SlowConnectionTimeout(t *testing.T) {
// Setup server with very short connection timeout for testing
serverConfig := &server.Config{
Address: ":0",
Timeouts: server.TimeoutConfig{
Read: 5 * time.Second,
Write: 5 * time.Second,
Connection: 200 * time.Millisecond,
},
}
srv := setupTestServerWithConfig(t, config)
srv := setupTestServerWithConfig(t, serverConfig)
defer srv.Stop()
// Connect to server
// Connect to server but do nothing
conn, err := net.Dial("tcp", srv.Address())
require.NoError(t, err)
defer conn.Close()
// Wait longer than connection timeout without sending any data
time.Sleep(200 * time.Millisecond)
// Wait longer than connection timeout
time.Sleep(300 * time.Millisecond)
// Try to read from connection - should get EOF or connection reset
// Try to read - connection should be closed
buffer := make([]byte, 1024)
conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
_, err = conn.Read(buffer)
assert.Error(t, err, "Connection should be closed due to connection timeout")
}
func TestSlowlorisProtection_MultipleSlowConnections(t *testing.T) {
func TestSlowlorisProtection_MultipleSlowClients(t *testing.T) {
// Setup server with short timeouts
config := server.DefaultConfig()
config.Address = ":0"
config.Timeouts.Read = 50 * time.Millisecond
config.Timeouts.Write = 50 * time.Millisecond
config.Timeouts.Connection = 200 * time.Millisecond
serverConfig := &server.Config{
Address: ":0",
Timeouts: server.TimeoutConfig{
Read: 1 * time.Second,
Write: 1 * time.Second,
Connection: 2 * time.Second,
},
}
srv := setupTestServerWithConfig(t, config)
srv := setupTestServerWithConfig(t, serverConfig)
defer srv.Stop()
// Create multiple slow connections (simulating slowloris attack)
var conns []net.Conn
for i := 0; i < 3; i++ {
// Create multiple slow connections
var connections []net.Conn
for i := 0; i < 5; i++ {
conn, err := net.Dial("tcp", srv.Address())
require.NoError(t, err)
conns = append(conns, conn)
// Send partial data to trigger slow reader behavior
_, err = conn.Write([]byte{0x01}) // Just message type
require.NoError(t, err)
connections = append(connections, conn)
// Send partial data on each connection
conn.Write([]byte{0x01}) // Challenge request type only
}
// Clean up connections
defer func() {
for _, conn := range conns {
conn.Close()
}
}()
// Wait for timeouts to kick in
time.Sleep(1500 * time.Millisecond)
// Wait for read timeouts to kick in
time.Sleep(100 * time.Millisecond)
// Verify slow connections are closed by trying to read from them
for i, conn := range conns {
// All connections should be closed
buffer := make([]byte, 1024)
conn.SetReadDeadline(time.Now().Add(50 * time.Millisecond))
for i, conn := range connections {
conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
_, err := conn.Read(buffer)
assert.Error(t, err, "Slow connection %d should be closed", i)
assert.Error(t, err, "Connection %d should be closed", i)
conn.Close()
}
}
func TestSlowlorisProtection_NormalOperationWithinTimeouts(t *testing.T) {
// Setup server with reasonable timeouts
config := server.DefaultConfig()
config.Address = ":0"
func TestSlowlorisProtection_AttackMitigation(t *testing.T) {
// Test that server can still serve legitimate clients during an attack
serverConfig := &server.Config{
Address: ":0",
Timeouts: server.TimeoutConfig{
Read: 500 * time.Millisecond,
Write: 500 * time.Millisecond,
Connection: 1 * time.Second,
},
}
srv := setupTestServerWithConfig(t, config)
srv := setupTestServerWithConfig(t, serverConfig)
defer srv.Stop()
// Connect and complete normal flow quickly
// Start slowloris attack - multiple slow connections
var attackConnections []net.Conn
for i := 0; i < 3; i++ {
conn, err := net.Dial("tcp", srv.Address())
require.NoError(t, err)
attackConnections = append(attackConnections, conn)
// Send partial data
conn.Write([]byte{0x01})
}
// Meanwhile, legitimate client should still work
legitimateConn, err := net.Dial("tcp", srv.Address())
require.NoError(t, err)
defer legitimateConn.Close()
// Send complete request quickly
challengeReq := &protocol.ChallengeRequest{}
err = challengeReq.Encode(legitimateConn)
require.NoError(t, err)
// Should receive response despite ongoing attack
decoder := protocol.NewMessageDecoder()
msg, err := decoder.Decode(legitimateConn)
assert.NoError(t, err)
assert.Equal(t, protocol.ChallengeResponseType, msg.Type)
// Clean up attack connections
for _, conn := range attackConnections {
conn.Close()
}
}
func TestSlowlorisProtection_SlowChunkReading(t *testing.T) {
// Test protection against clients that read responses very slowly
serverConfig := &server.Config{
Address: ":0",
Timeouts: server.TimeoutConfig{
Read: 5 * time.Second,
Write: 200 * time.Millisecond,
Connection: 10 * time.Second,
},
}
srv := setupTestServerWithConfig(t, serverConfig)
defer srv.Stop()
// Connect and send valid request
conn, err := net.Dial("tcp", srv.Address())
require.NoError(t, err)
defer conn.Close()
// Request challenge
challengeReq := &protocol.ChallengeRequest{}
err = challengeReq.Encode(conn)
require.NoError(t, err)
// Should receive challenge response without timeout
decoder := protocol.NewMessageDecoder()
msg, err := decoder.Decode(conn)
require.NoError(t, err)
assert.Equal(t, protocol.ChallengeResponseType, msg.Type)
assert.Greater(t, msg.PayloadLength, uint32(0), "Challenge payload should not be empty")
}
func TestSlowlorisProtection_PartialHeaderAttack(t *testing.T) {
// Setup server with short read timeout
config := server.DefaultConfig()
config.Address = ":0"
config.Timeouts.Read = 100 * time.Millisecond
srv := setupTestServerWithConfig(t, config)
defer srv.Stop()
// Connect to server
conn, err := net.Dial("tcp", srv.Address())
require.NoError(t, err)
defer conn.Close()
// Send only message type byte, then stall
_, err = conn.Write([]byte{0x01})
require.NoError(t, err)
// Wait for read timeout
time.Sleep(200 * time.Millisecond)
// Try to read from connection - should be closed
buffer := make([]byte, 1024)
conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
// Read only first byte of response very slowly
buffer := make([]byte, 1)
_, err = conn.Read(buffer)
assert.Error(t, err, "Connection should be closed due to partial header")
require.NoError(t, err)
// Wait longer than write timeout before reading more
time.Sleep(300 * time.Millisecond)
// Try to read more - connection should be closed due to slow reading
conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
_, err = conn.Read(buffer)
assert.Error(t, err, "Connection should be closed due to slow chunk reading")
}

View file

@ -6,6 +6,7 @@ import (
"testing"
"time"
"hash-of-wisdom/internal/config"
"hash-of-wisdom/internal/lib/sl"
"hash-of-wisdom/internal/pow/challenge"
"hash-of-wisdom/internal/protocol"
@ -19,12 +20,15 @@ import (
func TestTCPServer_TimeoutProtection_SlowReader(t *testing.T) {
// Setup server with very short read timeout for testing
config := server.DefaultConfig()
config.Address = ":0"
config.Timeouts.Read = 500 * time.Millisecond
config.Timeouts.Write = 5 * time.Second
config.Timeouts.Connection = 15 * time.Second
srv := setupTestServerWithConfig(t, config)
serverConfig := &server.Config{
Address: ":0",
Timeouts: server.TimeoutConfig{
Read: 500 * time.Millisecond,
Write: 5 * time.Second,
Connection: 15 * time.Second,
},
}
srv := setupTestServerWithConfig(t, serverConfig)
defer srv.Stop()
// Connect to server
@ -51,12 +55,16 @@ func TestTCPServer_TimeoutProtection_SlowReader(t *testing.T) {
func TestTCPServer_TimeoutProtection_ConnectionTimeout(t *testing.T) {
// Setup server with very short connection timeout
config := server.DefaultConfig()
config.Address = ":0"
config.Timeouts.Read = 5 * time.Second
config.Timeouts.Write = 5 * time.Second
config.Timeouts.Connection = 1 * time.Second
srv := setupTestServerWithConfig(t, config)
_ = config.Load
serverConfig := &server.Config{
Address: ":0",
Timeouts: server.TimeoutConfig{
Read: 5 * time.Second,
Write: 5 * time.Second,
Connection: 1 * time.Second,
},
}
srv := setupTestServerWithConfig(t, serverConfig)
defer srv.Stop()
// Connect to server
@ -97,12 +105,16 @@ func TestTCPServer_NormalOperation_WithinTimeouts(t *testing.T) {
}
func TestTCPServer_MultipleConnections_IndependentTimeouts(t *testing.T) {
config := server.DefaultConfig()
config.Address = ":0"
config.Timeouts.Read = 1 * time.Second
config.Timeouts.Write = 5 * time.Second
config.Timeouts.Connection = 3 * time.Second
srv := setupTestServerWithConfig(t, config)
_ = config.Load
serverConfig := &server.Config{
Address: ":0",
Timeouts: server.TimeoutConfig{
Read: 1 * time.Second,
Write: 5 * time.Second,
Connection: 3 * time.Second,
},
}
srv := setupTestServerWithConfig(t, serverConfig)
defer srv.Stop()
// Start two connections
@ -143,9 +155,15 @@ func TestTCPServer_MultipleConnections_IndependentTimeouts(t *testing.T) {
// Helper function to create test server with default config
func setupTestServer(t *testing.T) *server.TCPServer {
config := server.DefaultConfig()
config.Address = ":0"
return setupTestServerWithConfig(t, config)
serverConfig := &server.Config{
Address: ":0",
Timeouts: server.TimeoutConfig{
Read: 5 * time.Second,
Write: 5 * time.Second,
Connection: 15 * time.Second,
},
}
return setupTestServerWithConfig(t, serverConfig)
}
// Helper function to create test server with custom config
@ -164,8 +182,7 @@ func setupTestServerWithConfig(t *testing.T, serverConfig *server.Config) *serve
// Create server with custom config using functional options
logger := sl.NewMockLogger()
srv := server.NewTCPServer(wisdomService,
server.WithConfig(serverConfig),
srv := server.NewTCPServer(wisdomService, serverConfig,
server.WithLogger(logger))
// Start server