fix: code correctness, security, and simplicity improvements
This commit is contained in:
24
internal/cache/store.go
vendored
24
internal/cache/store.go
vendored
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
@@ -90,16 +91,31 @@ func (r *redisClient) Decrement(ctx context.Context, key *CacheKey) (int64, erro
|
||||
}
|
||||
|
||||
// keyString converts a CacheKey to a Redis string key.
|
||||
// Sanitizes key components to prevent key corruption via special characters.
|
||||
func sanitizeKeyComponent(s string) string {
|
||||
// Replace characters that could corrupt Redis key format
|
||||
s = strings.ReplaceAll(s, ":", "_colon_")
|
||||
s = strings.ReplaceAll(s, "/", "_slash_")
|
||||
s = strings.ReplaceAll(s, " ", "_")
|
||||
s = strings.ReplaceAll(s, "\t", "_tab_")
|
||||
s = strings.ReplaceAll(s, "\n", "_newline_")
|
||||
s = strings.ReplaceAll(s, "\r", "_cr_")
|
||||
return s
|
||||
}
|
||||
|
||||
func keyString(k *CacheKey) string {
|
||||
switch k.Kind {
|
||||
case "city":
|
||||
return fmt.Sprintf("cities:%s", k.Code)
|
||||
return fmt.Sprintf("cities:%s", sanitizeKeyComponent(k.Code))
|
||||
case "station":
|
||||
return fmt.Sprintf("stations:%s", k.Code)
|
||||
return fmt.Sprintf("stations:%s", sanitizeKeyComponent(k.Code))
|
||||
case "search":
|
||||
return fmt.Sprintf("search:%s:%s:%s", k.From, k.To, k.Date)
|
||||
return fmt.Sprintf("search:%s:%s:%s",
|
||||
sanitizeKeyComponent(k.From),
|
||||
sanitizeKeyComponent(k.To),
|
||||
sanitizeKeyComponent(k.Date))
|
||||
default:
|
||||
return fmt.Sprintf("unknown:%s", k.Kind)
|
||||
return fmt.Sprintf("unknown:%s", sanitizeKeyComponent(k.Kind))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user