Compare commits
4 commits
phase-9-do
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dfbf23a27c | ||
|
|
89b5fb9cf1 | ||
|
|
c9fb9f91c1 | ||
|
|
78beb401fe |
59
README.md
59
README.md
|
|
@ -11,17 +11,41 @@ The Hash of Wisdom server requires clients to solve computational puzzles (proof
|
|||
### Prerequisites
|
||||
- Go 1.24.3+
|
||||
- Docker (optional)
|
||||
- [Task](https://taskfile.dev/) (optional, but recommended)
|
||||
|
||||
### Building
|
||||
```bash
|
||||
# Build server
|
||||
go build -o hash-of-wisdom ./cmd/server
|
||||
|
||||
# Build client
|
||||
# Build client
|
||||
go build -o client ./cmd/client
|
||||
```
|
||||
|
||||
### Running
|
||||
|
||||
#### Using Task (Recommended)
|
||||
```bash
|
||||
# Most useful command - run all checks
|
||||
task check
|
||||
|
||||
# Start server
|
||||
task server -- -config config.yaml
|
||||
|
||||
# Connect client
|
||||
task client -- --addr=localhost:8080
|
||||
|
||||
# Run tests
|
||||
task test
|
||||
|
||||
# See coverage
|
||||
task test-coverage
|
||||
|
||||
# See all available commands
|
||||
task --list
|
||||
```
|
||||
|
||||
#### Manual Commands
|
||||
```bash
|
||||
# Start server (uses config.yaml by default)
|
||||
./hash-of-wisdom
|
||||
|
|
@ -31,6 +55,9 @@ go build -o client ./cmd/client
|
|||
|
||||
# Connect with client
|
||||
./client -addr localhost:8080
|
||||
|
||||
# Run tests
|
||||
go test ./...
|
||||
```
|
||||
|
||||
### Using Docker
|
||||
|
|
@ -50,38 +77,10 @@ docker run -p 8080:8080 -p 8081:8081 hash-of-wisdom
|
|||
|
||||
### Protocol & Implementation
|
||||
- [Protocol Specification](docs/PROTOCOL.md) - Binary protocol definition
|
||||
- [PoW Algorithm Analysis](docs/POW_ANALYSIS.md) - Algorithm selection rationale and comparison
|
||||
- [Implementation Plan](docs/IMPLEMENTATION.md) - Development phases and progress
|
||||
- [Package Structure](docs/PACKAGES.md) - Code organization and package responsibilities
|
||||
- [Architecture Choices](docs/ARCHITECTURE.md) - Design decisions and patterns
|
||||
|
||||
### Production Readiness
|
||||
- [Production Readiness Guide](docs/PRODUCTION_READINESS.md) - Requirements for production deployment
|
||||
|
||||
## Algorithm Choice
|
||||
|
||||
The server uses **SHA-256 based proof-of-work** with leading zero bits difficulty:
|
||||
- **Why SHA-256**: Cryptographically secure, well-tested, hardware-optimized
|
||||
- **Leading Zero Bits**: Simple difficulty scaling, easy verification
|
||||
- **HMAC Authentication**: Prevents challenge tampering and replay attacks
|
||||
- **Configurable Difficulty**: Adaptive to different threat levels (4-30 bits)
|
||||
|
||||
This approach provides strong DDoS protection while remaining computationally reasonable for legitimate clients.
|
||||
|
||||
## Current Status
|
||||
|
||||
✅ **Complete**: Core functionality, TCP server, client, metrics, containerization
|
||||
🔄 **In Progress**: Documentation (Phase 9)
|
||||
📋 **Planned**: See [Production Readiness Guide](docs/PRODUCTION_READINESS.md) for production deployment requirements
|
||||
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
go test ./...
|
||||
|
||||
# Run integration tests
|
||||
go test ./test/integration/...
|
||||
|
||||
# Benchmarks
|
||||
go test -bench=. ./internal/pow/...
|
||||
```
|
||||
|
|
|
|||
38
Taskfile.yml
38
Taskfile.yml
|
|
@ -93,3 +93,41 @@ tasks:
|
|||
desc: Alias for cpu-burner
|
||||
cmds:
|
||||
- task: cpu-burner
|
||||
|
||||
server:
|
||||
desc: Build and run the server
|
||||
cmds:
|
||||
- go build -o hash-of-wisdom ./cmd/server
|
||||
- ./hash-of-wisdom {{.CLI_ARGS}}
|
||||
|
||||
server-config:
|
||||
desc: Build and run the server with custom config
|
||||
cmds:
|
||||
- go build -o hash-of-wisdom ./cmd/server
|
||||
- ./hash-of-wisdom -config {{.CONFIG | default "config.yaml"}}
|
||||
|
||||
client:
|
||||
desc: Build and run the client
|
||||
cmds:
|
||||
- go build -o client ./cmd/client
|
||||
- ./client {{.CLI_ARGS | default "-addr localhost:8080"}}
|
||||
|
||||
docker-build:
|
||||
desc: Build Docker image
|
||||
cmds:
|
||||
- docker build -t hash-of-wisdom .
|
||||
|
||||
docker-run:
|
||||
desc: Run Docker container
|
||||
cmds:
|
||||
- docker run -p 8080:8080 -p 8081:8081 hash-of-wisdom
|
||||
|
||||
metrics:
|
||||
desc: Check metrics endpoint
|
||||
cmds:
|
||||
- curl -s http://localhost:8081/metrics
|
||||
|
||||
integration:
|
||||
desc: Run integration tests only
|
||||
cmds:
|
||||
- go test -v ./test/integration/...
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ func main() {
|
|||
|
||||
// Create server configuration
|
||||
serverConfig := &server.Config{
|
||||
Address: cfg.Server.Address,
|
||||
Address: cfg.Server.Address,
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: cfg.Server.Timeouts.Read,
|
||||
Write: cfg.Server.Timeouts.Write,
|
||||
|
|
|
|||
|
|
@ -32,9 +32,9 @@ func TestWisdomApplication_HandleMessage_UnsupportedType(t *testing.T) {
|
|||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.MessageType(0xFF), // Invalid type
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
Type: protocol.MessageType(0xFF), // Invalid type
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
|
|
@ -64,9 +64,9 @@ func TestWisdomApplication_HandleChallengeRequest_Success(t *testing.T) {
|
|||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.ChallengeRequestType,
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
Type: protocol.ChallengeRequestType,
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
|
|
@ -89,9 +89,9 @@ func TestWisdomApplication_HandleChallengeRequest_ServiceError(t *testing.T) {
|
|||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.ChallengeRequestType,
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
Type: protocol.ChallengeRequestType,
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
|
|
@ -138,9 +138,9 @@ func TestWisdomApplication_HandleSolutionRequest_Success(t *testing.T) {
|
|||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(payloadJSON)),
|
||||
PayloadStream: bytes.NewReader(payloadJSON),
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(payloadJSON)),
|
||||
PayloadStream: bytes.NewReader(payloadJSON),
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
|
|
@ -161,9 +161,9 @@ func TestWisdomApplication_HandleSolutionRequest_InvalidJSON(t *testing.T) {
|
|||
invalidJSON := []byte("invalid json")
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(invalidJSON)),
|
||||
PayloadStream: bytes.NewReader(invalidJSON),
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(invalidJSON)),
|
||||
PayloadStream: bytes.NewReader(invalidJSON),
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
|
|
@ -205,9 +205,9 @@ func TestWisdomApplication_HandleSolutionRequest_VerificationFailed(t *testing.T
|
|||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(payloadJSON)),
|
||||
PayloadStream: bytes.NewReader(payloadJSON),
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(payloadJSON)),
|
||||
PayloadStream: bytes.NewReader(payloadJSON),
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
|
|
@ -250,9 +250,9 @@ func TestWisdomApplication_HandleSolutionRequest_QuoteServiceError(t *testing.T)
|
|||
|
||||
ctx := context.Background()
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(payloadJSON)),
|
||||
PayloadStream: bytes.NewReader(payloadJSON),
|
||||
Type: protocol.SolutionRequestType,
|
||||
PayloadLength: uint32(len(payloadJSON)),
|
||||
PayloadStream: bytes.NewReader(payloadJSON),
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
|
|
@ -279,9 +279,9 @@ func TestWisdomApplication_HandleMessage_ContextCancellation(t *testing.T) {
|
|||
mockService.On("GenerateChallenge", mock.Anything, "quotes").Return(nil, context.Canceled)
|
||||
|
||||
msg := &protocol.Message{
|
||||
Type: protocol.ChallengeRequestType,
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
Type: protocol.ChallengeRequestType,
|
||||
PayloadLength: 0,
|
||||
PayloadStream: nil,
|
||||
}
|
||||
|
||||
response, err := app.HandleMessage(ctx, msg)
|
||||
|
|
|
|||
|
|
@ -7,16 +7,16 @@ import (
|
|||
)
|
||||
|
||||
type Config struct {
|
||||
Server ServerConfig `yaml:"server"`
|
||||
PoW PoWConfig `yaml:"pow"`
|
||||
Quotes QuotesConfig `yaml:"quotes"`
|
||||
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"`
|
||||
Address string `yaml:"address" env:"SERVER_ADDRESS" env-default:":8080"`
|
||||
Timeouts TimeoutConfig `yaml:"timeouts"`
|
||||
}
|
||||
|
||||
type TimeoutConfig struct {
|
||||
|
|
@ -26,10 +26,10 @@ type TimeoutConfig struct {
|
|||
}
|
||||
|
||||
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"`
|
||||
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"`
|
||||
HMACSecret string `yaml:"hmac_secret" env:"POW_HMAC_SECRET" env-default:"development-secret-change-in-production"`
|
||||
}
|
||||
|
||||
type QuotesConfig struct {
|
||||
|
|
|
|||
|
|
@ -68,8 +68,8 @@ func (c *Challenge) VerifySolution(nonce uint64) bool {
|
|||
|
||||
// hasLeadingZeroBits checks if hash has the required number of leading zero bits
|
||||
func hasLeadingZeroBits(hash []byte, difficulty int) bool {
|
||||
full := difficulty >> 3 // number of whole zero bytes
|
||||
rem := uint(difficulty & 7) // remaining leading zero bits
|
||||
full := difficulty >> 3 // number of whole zero bytes
|
||||
rem := uint(difficulty & 7) // remaining leading zero bits
|
||||
|
||||
for i := range full {
|
||||
if hash[i] != 0 {
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ package protocol
|
|||
type MessageType byte
|
||||
|
||||
const (
|
||||
ChallengeRequestType MessageType = 0x01
|
||||
SolutionRequestType MessageType = 0x03
|
||||
ChallengeRequestType MessageType = 0x01
|
||||
SolutionRequestType MessageType = 0x03
|
||||
// Response types (for responses.go)
|
||||
ChallengeResponseType MessageType = 0x02
|
||||
QuoteResponseType MessageType = 0x04
|
||||
|
|
@ -14,14 +14,14 @@ const (
|
|||
|
||||
// Error codes as defined in protocol specification
|
||||
const (
|
||||
ErrMalformedMessage = "MALFORMED_MESSAGE"
|
||||
ErrInvalidChallenge = "INVALID_CHALLENGE"
|
||||
ErrInvalidSolution = "INVALID_SOLUTION"
|
||||
ErrExpiredChallenge = "EXPIRED_CHALLENGE"
|
||||
ErrRateLimited = "RATE_LIMITED"
|
||||
ErrServerError = "SERVER_ERROR"
|
||||
ErrTooManyConnections = "TOO_MANY_CONNECTIONS"
|
||||
ErrDifficultyTooHigh = "DIFFICULTY_TOO_HIGH"
|
||||
ErrMalformedMessage = "MALFORMED_MESSAGE"
|
||||
ErrInvalidChallenge = "INVALID_CHALLENGE"
|
||||
ErrInvalidSolution = "INVALID_SOLUTION"
|
||||
ErrExpiredChallenge = "EXPIRED_CHALLENGE"
|
||||
ErrRateLimited = "RATE_LIMITED"
|
||||
ErrServerError = "SERVER_ERROR"
|
||||
ErrTooManyConnections = "TOO_MANY_CONNECTIONS"
|
||||
ErrDifficultyTooHigh = "DIFFICULTY_TOO_HIGH"
|
||||
)
|
||||
|
||||
// Protocol constants
|
||||
|
|
|
|||
|
|
@ -43,8 +43,8 @@ func (d *MessageDecoder) Decode(r io.Reader) (*Message, error) {
|
|||
}
|
||||
|
||||
return &Message{
|
||||
Type: msgType,
|
||||
PayloadLength: payloadLength,
|
||||
PayloadStream: payloadStream,
|
||||
Type: msgType,
|
||||
PayloadLength: payloadLength,
|
||||
PayloadStream: payloadStream,
|
||||
}, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,11 +13,11 @@ func TestMessageDecoder_Decode_Header(t *testing.T) {
|
|||
decoder := NewMessageDecoder()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
data []byte
|
||||
wantType MessageType
|
||||
wantLength uint32
|
||||
wantErr string
|
||||
name string
|
||||
data []byte
|
||||
wantType MessageType
|
||||
wantLength uint32
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "challenge request with empty payload",
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import (
|
|||
"hash-of-wisdom/internal/pow/challenge"
|
||||
)
|
||||
|
||||
|
||||
// ChallengeRequest is empty (no payload for challenge requests)
|
||||
type ChallengeRequest struct{}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import (
|
|||
"hash-of-wisdom/internal/quotes"
|
||||
)
|
||||
|
||||
|
||||
// ChallengeResponse represents a challenge response
|
||||
type ChallengeResponse struct {
|
||||
Challenge *challenge.Challenge
|
||||
|
|
|
|||
|
|
@ -113,7 +113,6 @@ func TestChallengeRequest_EmptyPayload(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
|
||||
func TestPayloadStream_LimitedRead(t *testing.T) {
|
||||
decoder := NewMessageDecoder()
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import "io"
|
|||
|
||||
// Message represents a protocol message with type and payload stream
|
||||
type Message struct {
|
||||
Type MessageType
|
||||
PayloadLength uint32
|
||||
PayloadStream io.Reader
|
||||
Type MessageType
|
||||
PayloadLength uint32
|
||||
PayloadStream io.Reader
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ type TCPServer struct {
|
|||
// Option is a functional option for configuring TCPServer
|
||||
type option func(*TCPServer)
|
||||
|
||||
|
||||
// WithLogger sets a custom logger
|
||||
func WithLogger(logger *slog.Logger) option {
|
||||
return func(s *TCPServer) {
|
||||
|
|
@ -54,7 +53,6 @@ func NewTCPServer(wisdomService *service.WisdomService, config *Config, opts ...
|
|||
return server
|
||||
}
|
||||
|
||||
|
||||
// Start starts the TCP server
|
||||
func (s *TCPServer) Start(ctx context.Context) error {
|
||||
listener, err := net.Listen("tcp", s.config.Address)
|
||||
|
|
|
|||
|
|
@ -9,11 +9,11 @@ import (
|
|||
)
|
||||
|
||||
var (
|
||||
ErrResourceRequired = errors.New("resource is required")
|
||||
ErrResourceRequired = errors.New("resource is required")
|
||||
ErrUnsupportedResource = errors.New("unsupported resource")
|
||||
ErrSolutionRequired = errors.New("solution is required")
|
||||
ErrInvalidChallenge = errors.New("invalid challenge")
|
||||
ErrInvalidSolution = errors.New("invalid proof of work solution")
|
||||
ErrSolutionRequired = errors.New("solution is required")
|
||||
ErrInvalidChallenge = errors.New("invalid challenge")
|
||||
ErrInvalidSolution = errors.New("invalid proof of work solution")
|
||||
)
|
||||
|
||||
type ChallengeGenerator interface {
|
||||
|
|
|
|||
|
|
@ -70,15 +70,15 @@ func TestWisdomService_GenerateChallenge(t *testing.T) {
|
|||
|
||||
func TestWisdomService_VerifySolution(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
solution *challenge.Solution
|
||||
wantErr error
|
||||
name string
|
||||
solution *challenge.Solution
|
||||
wantErr error
|
||||
setupMocks func(*mocks.MockChallengeVerifier)
|
||||
}{
|
||||
{
|
||||
name: "nil solution",
|
||||
solution: nil,
|
||||
wantErr: ErrSolutionRequired,
|
||||
name: "nil solution",
|
||||
solution: nil,
|
||||
wantErr: ErrSolutionRequired,
|
||||
setupMocks: func(mv *mocks.MockChallengeVerifier) {},
|
||||
},
|
||||
{
|
||||
|
|
@ -93,17 +93,17 @@ func TestWisdomService_VerifySolution(t *testing.T) {
|
|||
},
|
||||
},
|
||||
{
|
||||
name: "invalid solution",
|
||||
name: "invalid solution",
|
||||
solution: createInvalidSolution(t),
|
||||
wantErr: ErrInvalidSolution,
|
||||
wantErr: ErrInvalidSolution,
|
||||
setupMocks: func(mv *mocks.MockChallengeVerifier) {
|
||||
mv.EXPECT().VerifyChallenge(mock.Anything).Return(nil).Once()
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "valid solution",
|
||||
name: "valid solution",
|
||||
solution: createValidSolution(t),
|
||||
wantErr: nil,
|
||||
wantErr: nil,
|
||||
setupMocks: func(mv *mocks.MockChallengeVerifier) {
|
||||
mv.EXPECT().VerifyChallenge(mock.Anything).Return(nil).Once()
|
||||
},
|
||||
|
|
|
|||
|
|
@ -284,8 +284,8 @@ func TestWisdomService_InvalidSolutions(t *testing.T) {
|
|||
|
||||
func TestWisdomService_UnsuccessfulFlows(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
difficulty int
|
||||
name string
|
||||
difficulty int
|
||||
createSolution func(*challenge.Challenge, *challenge.Solution) *challenge.Solution
|
||||
}{
|
||||
{
|
||||
|
|
|
|||
56
test/integration/helpers_test.go
Normal file
56
test/integration/helpers_test.go
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hash-of-wisdom/internal/lib/sl"
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
"hash-of-wisdom/internal/server"
|
||||
"hash-of-wisdom/internal/service"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// testQuoteService provides static quotes for testing
|
||||
type testQuoteService struct{}
|
||||
|
||||
func (s *testQuoteService) GetRandomQuote(ctx context.Context) (*quotes.Quote, error) {
|
||||
return "es.Quote{
|
||||
Text: "Test quote for integration testing",
|
||||
Author: "Test Author",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func setupTestServerWithConfig(t *testing.T, serverConfig *server.Config) *server.TCPServer {
|
||||
// Create test components
|
||||
challengeConfig := challenge.TestConfig()
|
||||
generator := challenge.NewGenerator(challengeConfig)
|
||||
verifier := challenge.NewVerifier(challengeConfig)
|
||||
|
||||
// Create a simple test quote service
|
||||
quoteService := &testQuoteService{}
|
||||
|
||||
// Wire up service
|
||||
genAdapter := service.NewGeneratorAdapter(generator)
|
||||
wisdomService := service.NewWisdomService(genAdapter, verifier, quoteService)
|
||||
|
||||
// Create server with custom config using functional options
|
||||
logger := sl.NewMockLogger()
|
||||
srv := server.NewTCPServer(wisdomService, serverConfig,
|
||||
server.WithLogger(logger))
|
||||
|
||||
// Start server
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
|
||||
err := srv.Start(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Give server time to start
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
return srv
|
||||
}
|
||||
|
|
@ -5,7 +5,6 @@ import (
|
|||
"testing"
|
||||
"time"
|
||||
|
||||
"hash-of-wisdom/internal/protocol"
|
||||
"hash-of-wisdom/internal/server"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
|
@ -15,7 +14,7 @@ import (
|
|||
func TestSlowlorisProtection_SlowReader(t *testing.T) {
|
||||
// Setup server with very short read timeout for testing
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 100 * time.Millisecond,
|
||||
Write: 5 * time.Second,
|
||||
|
|
@ -48,47 +47,10 @@ func TestSlowlorisProtection_SlowReader(t *testing.T) {
|
|||
assert.Error(t, err, "Connection should be closed due to slow reading")
|
||||
}
|
||||
|
||||
func TestSlowlorisProtection_SlowWriter(t *testing.T) {
|
||||
// Setup server with very short write timeout for testing
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 5 * time.Second,
|
||||
Write: 100 * time.Millisecond,
|
||||
Connection: 15 * time.Second,
|
||||
},
|
||||
}
|
||||
|
||||
srv := setupTestServerWithConfig(t, serverConfig)
|
||||
defer srv.Stop()
|
||||
|
||||
// Connect to server but don't read responses (simulate slow writer client)
|
||||
conn, err := net.Dial("tcp", srv.Address())
|
||||
require.NoError(t, err)
|
||||
defer conn.Close()
|
||||
|
||||
// Send a complete challenge request
|
||||
challengeReq := &protocol.ChallengeRequest{}
|
||||
err = challengeReq.Encode(conn)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Don't read the response - this should trigger write timeout
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
// 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_SlowConnectionTimeout(t *testing.T) {
|
||||
// Setup server with very short connection timeout for testing
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 5 * time.Second,
|
||||
Write: 5 * time.Second,
|
||||
|
|
@ -117,7 +79,7 @@ func TestSlowlorisProtection_SlowConnectionTimeout(t *testing.T) {
|
|||
func TestSlowlorisProtection_MultipleSlowClients(t *testing.T) {
|
||||
// Setup server with short timeouts
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 1 * time.Second,
|
||||
Write: 1 * time.Second,
|
||||
|
|
@ -150,86 +112,3 @@ func TestSlowlorisProtection_MultipleSlowClients(t *testing.T) {
|
|||
conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
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, serverConfig)
|
||||
defer srv.Stop()
|
||||
|
||||
// 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()
|
||||
|
||||
challengeReq := &protocol.ChallengeRequest{}
|
||||
err = challengeReq.Encode(conn)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Read only first byte of response very slowly
|
||||
buffer := make([]byte, 1)
|
||||
_, err = conn.Read(buffer)
|
||||
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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,18 +1,12 @@
|
|||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hash-of-wisdom/internal/config"
|
||||
"hash-of-wisdom/internal/lib/sl"
|
||||
"hash-of-wisdom/internal/pow/challenge"
|
||||
"hash-of-wisdom/internal/protocol"
|
||||
"hash-of-wisdom/internal/quotes"
|
||||
"hash-of-wisdom/internal/server"
|
||||
"hash-of-wisdom/internal/service"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
|
@ -21,7 +15,7 @@ import (
|
|||
func TestTCPServer_TimeoutProtection_SlowReader(t *testing.T) {
|
||||
// Setup server with very short read timeout for testing
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 500 * time.Millisecond,
|
||||
Write: 5 * time.Second,
|
||||
|
|
@ -55,9 +49,8 @@ func TestTCPServer_TimeoutProtection_SlowReader(t *testing.T) {
|
|||
|
||||
func TestTCPServer_TimeoutProtection_ConnectionTimeout(t *testing.T) {
|
||||
// Setup server with very short connection timeout
|
||||
_ = config.Load
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 5 * time.Second,
|
||||
Write: 5 * time.Second,
|
||||
|
|
@ -105,9 +98,8 @@ func TestTCPServer_NormalOperation_WithinTimeouts(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestTCPServer_MultipleConnections_IndependentTimeouts(t *testing.T) {
|
||||
_ = config.Load
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 1 * time.Second,
|
||||
Write: 5 * time.Second,
|
||||
|
|
@ -156,7 +148,7 @@ func TestTCPServer_MultipleConnections_IndependentTimeouts(t *testing.T) {
|
|||
// Helper function to create test server with default config
|
||||
func setupTestServer(t *testing.T) *server.TCPServer {
|
||||
serverConfig := &server.Config{
|
||||
Address: ":0",
|
||||
Address: ":0",
|
||||
Timeouts: server.TimeoutConfig{
|
||||
Read: 5 * time.Second,
|
||||
Write: 5 * time.Second,
|
||||
|
|
@ -167,43 +159,3 @@ func setupTestServer(t *testing.T) *server.TCPServer {
|
|||
}
|
||||
|
||||
// Helper function to create test server with custom config
|
||||
func setupTestServerWithConfig(t *testing.T, serverConfig *server.Config) *server.TCPServer {
|
||||
// Create test components
|
||||
challengeConfig := challenge.TestConfig()
|
||||
generator := challenge.NewGenerator(challengeConfig)
|
||||
verifier := challenge.NewVerifier(challengeConfig)
|
||||
|
||||
// Create a simple test quote service
|
||||
quoteService := &testQuoteService{}
|
||||
|
||||
// Wire up service
|
||||
genAdapter := service.NewGeneratorAdapter(generator)
|
||||
wisdomService := service.NewWisdomService(genAdapter, verifier, quoteService)
|
||||
|
||||
// Create server with custom config using functional options
|
||||
logger := sl.NewMockLogger()
|
||||
srv := server.NewTCPServer(wisdomService, serverConfig,
|
||||
server.WithLogger(logger))
|
||||
|
||||
// Start server
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
defer cancel()
|
||||
|
||||
err := srv.Start(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Give server time to start
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
return srv
|
||||
}
|
||||
|
||||
// testQuoteService provides test quotes
|
||||
type testQuoteService struct{}
|
||||
|
||||
func (s *testQuoteService) GetRandomQuote(ctx context.Context) (*quotes.Quote, error) {
|
||||
return "es.Quote{
|
||||
Text: "Test quote for integration testing",
|
||||
Author: "Test Author",
|
||||
}, nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue