Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 48 additions & 2 deletions cmd/poster/parsing.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ package main
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"path/filepath"

"github.com/adcondev/poster/internal/load"
"github.com/adcondev/poster/pkg/constants"
"github.com/adcondev/poster/pkg/document/schema"
)

Expand All @@ -26,11 +28,34 @@ func loadJSON(filePath string) ([]byte, error) {
return nil, fmt.Errorf("security check failed: %w", err)
}

// Read file
data, err := os.ReadFile(securePath) //nolint:gosec
// Read file securely
file, err := os.Open(securePath) //nolint:gosec
if err != nil {
return nil, err
}
defer func() {
_ = file.Close()
}()

// Check file size
fi, err := file.Stat()
if err != nil {
return nil, fmt.Errorf("failed to stat file: %w", err)
}
if fi.Size() > int64(constants.MaxJSONSize) {
return nil, fmt.Errorf("file too large: %d bytes (max %d bytes)", fi.Size(), constants.MaxJSONSize)
}

// Read with limit reader to prevent TOCTOU issues if file grows
reader := io.LimitReader(file, int64(constants.MaxJSONSize)+1)
data, err := io.ReadAll(reader)
if err != nil {
return nil, err
}

if len(data) > constants.MaxJSONSize {
return nil, fmt.Errorf("file too large (exceeded %d bytes during read)", constants.MaxJSONSize)
}

// Validate JSON
var temp interface{}
Expand All @@ -41,7 +66,28 @@ func loadJSON(filePath string) ([]byte, error) {
return data, nil
}

func validateJSON(filePath string) error {
data, err := loadJSON(filePath)
if err != nil {
return err
}

var doc schema.Document
if err := json.Unmarshal(data, &doc); err != nil {
return fmt.Errorf("invalid JSON: %w", err)
}

if err := doc.Validate(); err != nil {
return fmt.Errorf("invalid document: %w", err)
}

return validateDocument(&doc)
}

func validateDocument(doc *schema.Document) error {
if err := doc.Validate(); err != nil {
return fmt.Errorf("invalid document: %w", err)
}
fmt.Println("=== Document Validation ===")
fmt.Printf("Version: %s\n", doc.Version)
fmt.Printf("Profile: %s (%dmm)\n", doc.Profile.Model, doc.Profile.PaperWidth)
Expand Down
192 changes: 192 additions & 0 deletions cmd/poster/parsing_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
package main

import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"

"github.com/adcondev/poster/pkg/constants"
"github.com/adcondev/poster/pkg/document/schema"
)

const validDocContent = `{
"version": "1.0",
"profile": {
"model": "POS-80"
},
"commands": [
{
"type": "text",
"data": {"text": "data"}
}
]
}`

func TestLoadJSON_SizeLimit(t *testing.T) {
tempDir, err := os.MkdirTemp("", "poster_test")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
t.Cleanup(func() {
_ = os.RemoveAll(tempDir)
})

// Case 1: File within limit
smallFile := filepath.Join(tempDir, "small.json")
if err := os.WriteFile(smallFile, []byte(validDocContent), 0600); err != nil {
t.Fatalf("Failed to write small file: %v", err)
}

_, err = loadJSON(smallFile)
if err != nil {
t.Errorf("Expected no error for small file, got: %v", err)
}

// Case 2: File exceeding limit
largeFile := filepath.Join(tempDir, "large.json")
f, err := os.Create(filepath.Clean(largeFile))
if err != nil {
t.Fatalf("Failed to create large file: %v", err)
}

// Write slightly more than MaxJSONSize (11MB)
chunk := make([]byte, 1024*1024)
for i := range chunk {
chunk[i] = ' '
}

for i := 0; i < 11; i++ {
if _, err := f.Write(chunk); err != nil {
_ = f.Close()
t.Fatalf("Failed to write to large file: %v", err)
}
}
if _, err := f.Write([]byte(validDocContent)); err != nil {
_ = f.Close()
t.Fatalf("Failed to write end of large file: %v", err)
}
_ = f.Close()

_, err = loadJSON(largeFile)
if err == nil {
t.Error("Expected error for large file, got nil")
} else if !strings.Contains(err.Error(), "file too large") {
t.Errorf("Expected 'file too large' error, got: %v", err)
}
}

func TestLoadJSON_ExactLimit(t *testing.T) {
tempDir, err := os.MkdirTemp("", "poster_test_exact")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
t.Cleanup(func() {
_ = os.RemoveAll(tempDir)
})

exactFile := filepath.Join(tempDir, "exact.json")
f, err := os.Create(filepath.Clean(exactFile))
if err != nil {
t.Fatalf("Failed to create exact file: %v", err)
}

targetSize := constants.MaxJSONSize
validBytes := []byte(validDocContent)
if _, err := f.Write(validBytes); err != nil {
_ = f.Close()
t.Fatalf("Failed to write valid doc prefix: %v", err)
}

chunkSize := 1024 * 1024
chunk := make([]byte, chunkSize)
for i := range chunk {
chunk[i] = ' '
}

remaining := targetSize - len(validBytes)
for remaining > 0 {
toWrite := remaining
if toWrite > chunkSize {
toWrite = chunkSize
}
if _, err := f.Write(chunk[:toWrite]); err != nil {
_ = f.Close()
t.Fatalf("Failed to write exact file padding: %v", err)
}
remaining -= toWrite
}
_ = f.Close()

info, err := os.Stat(exactFile)
if err != nil {
t.Fatalf("Failed to stat exact file: %v", err)
}
if info.Size() != int64(constants.MaxJSONSize) {
t.Fatalf("Created file size %d, expected %d", info.Size(), constants.MaxJSONSize)
}

data, err := loadJSON(exactFile)
if err != nil {
t.Fatalf("Expected no error for exact size file, got: %v", err)
}

var doc schema.Document
if err := json.Unmarshal(data, &doc); err != nil {
t.Fatalf("Failed to unmarshal exact size file JSON: %v", err)
}
if err := doc.Validate(); err != nil {
t.Errorf("Document in exact size file failed doc.Validate(): %v", err)
}
}

func TestValidateJSON(t *testing.T) {
tempDir, err := os.MkdirTemp("", "poster_validate_test")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
t.Cleanup(func() {
_ = os.RemoveAll(tempDir)
})

t.Run("Valid document passes validation", func(t *testing.T) {
filePath := filepath.Join(tempDir, "valid.json")
if err := os.WriteFile(filePath, []byte(validDocContent), 0600); err != nil {
t.Fatalf("Failed to write test file: %v", err)
}

if err := validateJSON(filePath); err != nil {
t.Errorf("Expected valid document to pass validateJSON, got: %v", err)
}
})

t.Run("Invalid document schema fails validation", func(t *testing.T) {
invalidDoc := `{"commands": [{"type": "text", "data": {"text": "hello"}}]}`
filePath := filepath.Join(tempDir, "invalid_schema.json")
if err := os.WriteFile(filePath, []byte(invalidDoc), 0600); err != nil {
t.Fatalf("Failed to write test file: %v", err)
}

err := validateJSON(filePath)
if err == nil {
t.Error("Expected error for invalid document schema, got nil")
} else if !strings.Contains(err.Error(), "invalid document") {
t.Errorf("Expected 'invalid document' error, got: %v", err)
}
})

t.Run("Invalid JSON syntax fails validation", func(t *testing.T) {
filePath := filepath.Join(tempDir, "invalid_syntax.json")
if err := os.WriteFile(filePath, []byte(`{not valid json}`), 0600); err != nil {
t.Fatalf("Failed to write test file: %v", err)
}

err := validateJSON(filePath)
if err == nil {
t.Error("Expected error for invalid syntax, got nil")
} else if !strings.Contains(err.Error(), "invalid JSON") {
t.Errorf("Expected 'invalid JSON' error, got: %v", err)
}
})
}
6 changes: 6 additions & 0 deletions internal/testutils/byte_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ func RepeatByte(length int, value byte) []byte {
return result
}

// GenerateString creates a string of specified length filled with value
func GenerateString(length int, value byte) string {
return string(RepeatByte(length, value))
}


// ============================================================================
// Command Builders
// ============================================================================
Expand Down
9 changes: 3 additions & 6 deletions pkg/commands/print/print_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"testing"

"github.com/adcondev/poster/internal/testutils"
"github.com/adcondev/poster/pkg/commands/print"
"github.com/adcondev/poster/pkg/commands/shared"
)
Expand Down Expand Up @@ -106,12 +107,8 @@ func TestCommands_Text(t *testing.T) {
wantErr: true,
},
{
name: "buffer overflow",
// FIXME: change anonymous func to utils helpers
text: func() string {
overflow := make([]byte, shared.MaxBuf+1)
return string(overflow)
}(),
name: "buffer overflow",
text: testutils.GenerateString(shared.MaxBuf+1, 0),
want: nil,
wantErr: true,
},
Expand Down
10 changes: 10 additions & 0 deletions pkg/constants/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,3 +425,13 @@ const (
// TopMarginMultiplier is used to calculate initial top margin
TopMarginMultiplier = 2
)

// ============================================================================
// File Size Constants
// ============================================================================

const (
// MaxJSONSize is the maximum size in bytes for a JSON document (10MB)
MaxJSONSize = 10 * 1024 * 1024
)

7 changes: 7 additions & 0 deletions pkg/document/executor/image_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ func (e *Executor) handleImage(printer service.PrinterActions, data json.RawMess
opts.PixelWidth = constants.DefaultImagePixelWidth
}

if prof := printer.GetProfile(); prof != nil && prof.DotsPerLine > 0 {
opts.MaxWidth = prof.DotsPerLine
if opts.PixelWidth > opts.MaxWidth {
opts.PixelWidth = opts.MaxWidth
}
}

if opts.Threshold == 0 {
opts.Threshold = constants.DefaultImageThreshold
}
Expand Down
Loading
Loading