mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-07-14 05:06:14 +00:00
e39d6a0f0d
Multi-agent audit + fix pass covering bugs, security, dead config wiring,
and missing features. All quality gates green: build/vet/test -race/govulncheck/
golangci-lint. Frontend tests 47/47.
SECURITY & CORRECTNESS
- Scanner pipeline fail-closed: cache.go scan timeout now 503 (was goto servePkg);
scanner.go all-scanners-fail saves ScanStatusError; CheckVulnerabilities blocks
on missing/error result instead of allowing.
- Scanner argv corrections: govulncheck source-mode + go.mod discovery;
npm-audit generates lockfile via npm install --package-lock-only --ignore-scripts;
pip-audit per-extension dispatch (wheel direct / sdist extract+pyproject).
- GHSA version-range filtering implemented (was always-include); url.QueryEscape
on package name.
- pypi SSRF closed via host allowlist on original_url; url.QueryEscape on
rewriteURL output.
- Path traversal: cache temp file uses os.CreateTemp; smb keyToPath sanitized;
filesystem keyToPath returns error + filepath.Abs prefix-verify.
- Goroutine leaks plugged: cache.cleanupWorker stop channel; auth.ValidationCache
Stop() with sync.Once; ws.unregister buffered with non-blocking send.
- WebSocket double-close panic fixed via sync.Once Client.closeSend().
- Race conditions: gormstore.registryCache sync.RWMutex (was concurrent map
panic); auth.LastUsedAt no longer mutated under RLock; analytics strict
lock-ordering invariant (statsMu before downloadsMu).
- Auth validator fails CLOSED on transport/unknown-status errors (was returning
true,err 'allow cache fallback').
- Credential cache hash full SHA256 (was 8-byte truncate; eliminates 2^32
collision risk).
- filesystem.fs.used incremented after successful rename (no quota inflation
race).
- gormstore aggregation events deleted in same tx as insert (no double-counting).
- gormstore.SavePackage uses Updates(map) so zero-value security flags
(RequiresAuth=false) can be cleared.
- partition_manager validates partition name regex before DROP TABLE.
- vcs/git: version regex validation rejects --option-injection; checkout uses
--detach -- separator; removed TrimPrefix(repo,'v') that corrupted vault/
vitess/vim-go.
- WebSocket CheckOrigin allowlist (was return true; CSWSH closed); same-origin
default + ServerConfig.AllowedOrigins.
- fiber CVE GO-2026-4543 patched (v2.52.10 -> v2.52.12).
FUNCTIONAL FEATURES
- API key DB persistence: APIKeyModel + migration 202604280002, full CRUD,
async LastUsedAt updates with WaitGroup-tracked goroutines drained on Close.
- Admin bootstrap via GOHOARDER_BOOTSTRAP_ADMIN_KEY env var; idempotent
(skipped when non-revoked admin already exists).
- Auth middleware factory in pkg/app: RequireAuth, RequireRole, RequirePermission,
OptionalAuth. Mounted on proxy + read APIs when Auth.Enabled=true.
DELETE /api/packages/* requires admin role. /health public for k8s probes.
- NFS storage backend: pkg/storage/nfs wraps filesystem with /proc/mounts
detection (Linux), post-write fsync, read-after-write health probe.
- WebSocket real-time pipeline: pkg/events Broadcaster interface; cache + scanner
managers emit EventPackageCached / EventPackageDownloaded / EventScanComplete;
app.go runs 30s EventStatsUpdate ticker. Frontend has full WS client (reconnect
with exponential backoff 1s->30s, 25s heartbeat, subscriber pattern), Pinia
realtime store, Dashboard live indicator + activity feed + reactive stats
override.
- TLS termination: fiber.ListenTLS when Server.TLS.Enabled.
- Pre-warming: Prewarming.Enabled flag wired (was hardcoded false); Interval,
MaxConcurrent, TopPackages plumbed.
- NetworkConfig wired (timeouts, retry, rate-limit, circuit-breaker).
- AuthConfig.BcryptCost wired.
- Security.Scanners.Static.MaxPackageSize plumbed to cache.io.LimitReader.
- Handlers.{Go,NPM,PyPI}.Enabled gates route mounting.
- Graceful shutdown: authManager.Close drains async writes.
LINT/HYGIENE
- 80 golangci-lint issues resolved: errcheck (Close/Write/RemoveAll wrapped),
gofmt, gosec G104/G306, govet shadow renames + fieldalignment reorders,
staticcheck ST1000 pkg comments + QF1003 tagged switches + QF1008 embedded
field selectors + QF1001 De Morgan's law.
BEHAVIOR CHANGES
- Scanner now fail-closed: deployments without scanner binaries
(trivy/govulncheck/npm-audit/pip-audit/grype) BLOCK packages instead of
serving unscanned. Add binaries or plan a future allow-on-scan-error flag.
- WS origin defaults to same-origin; cross-origin dashboards must set
server.allowed_origins.
- Validator no longer fails open; private packages won't serve from cache when
validation can't be performed.
- download_events retention dropped from 24h to ~5min (deleted in agg tx).
Migration 202604280001 purges pre-upgrade events.
- DELETE /api/packages/* requires admin role when auth enabled.
NEW PACKAGES
- pkg/events - Broadcaster interface
- pkg/storage/nfs - NFS-aware filesystem wrapper
DEFERRED (out of scope this pass)
- Static scanner implementation (config defines AllowedLicenses/MaxPackageSize/
BlockSuspicious but pkg/scanner/static/ does not exist).
- AuthConfig.AuditLog wiring (no audit log infra yet).
- CacheConfig.TTLOverrides passthrough (would touch cache.Config beyond
integrator scope).
391 lines
9.3 KiB
Go
391 lines
9.3 KiB
Go
// Package s3 implements the S3-compatible Storage backend (AWS S3,
|
|
// MinIO, etc.).
|
|
package s3
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
stderrors "errors"
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
|
|
"github.com/aws/aws-sdk-go-v2/aws"
|
|
"github.com/aws/aws-sdk-go-v2/config"
|
|
"github.com/aws/aws-sdk-go-v2/credentials"
|
|
"github.com/aws/aws-sdk-go-v2/service/s3"
|
|
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
|
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
|
"github.com/lukaszraczylo/gohoarder/pkg/storage"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
// Config holds S3 storage configuration
|
|
type Config struct {
|
|
Region string
|
|
Bucket string
|
|
Prefix string
|
|
AccessKeyID string
|
|
SecretAccessKey string
|
|
Endpoint string // Optional: for S3-compatible services like MinIO
|
|
ForcePathStyle bool // Optional: for S3-compatible services
|
|
MaxSizeBytes int64
|
|
}
|
|
|
|
// S3Storage implements storage.StorageBackend using AWS S3
|
|
type S3Storage struct {
|
|
client *s3.Client
|
|
bucket string
|
|
prefix string
|
|
maxSizeBytes int64
|
|
}
|
|
|
|
// New creates a new S3 storage backend
|
|
func New(cfg Config) (*S3Storage, error) {
|
|
if cfg.Bucket == "" {
|
|
return nil, fmt.Errorf("S3 bucket is required")
|
|
}
|
|
|
|
if cfg.Region == "" {
|
|
cfg.Region = "us-east-1" // Default region
|
|
}
|
|
|
|
// Build AWS config
|
|
var awsConfig aws.Config
|
|
var err error
|
|
|
|
// Build config options
|
|
configOpts := []func(*config.LoadOptions) error{
|
|
config.WithRegion(cfg.Region),
|
|
}
|
|
|
|
// Add credentials if provided
|
|
if cfg.AccessKeyID != "" && cfg.SecretAccessKey != "" {
|
|
configOpts = append(configOpts, config.WithCredentialsProvider(
|
|
credentials.NewStaticCredentialsProvider(
|
|
cfg.AccessKeyID,
|
|
cfg.SecretAccessKey,
|
|
"",
|
|
),
|
|
))
|
|
}
|
|
|
|
awsConfig, err = config.LoadDefaultConfig(context.Background(), configOpts...)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to load AWS config: %w", err)
|
|
}
|
|
|
|
// Create S3 client with service-specific options
|
|
client := s3.NewFromConfig(awsConfig, func(o *s3.Options) {
|
|
// Use custom endpoint if provided (for MinIO, S3-compatible services, etc.)
|
|
if cfg.Endpoint != "" {
|
|
o.BaseEndpoint = aws.String(cfg.Endpoint)
|
|
}
|
|
if cfg.ForcePathStyle {
|
|
o.UsePathStyle = true
|
|
}
|
|
})
|
|
|
|
storage := &S3Storage{
|
|
client: client,
|
|
bucket: cfg.Bucket,
|
|
prefix: strings.TrimSuffix(cfg.Prefix, "/"),
|
|
maxSizeBytes: cfg.MaxSizeBytes,
|
|
}
|
|
|
|
log.Info().
|
|
Str("bucket", cfg.Bucket).
|
|
Str("region", cfg.Region).
|
|
Str("prefix", cfg.Prefix).
|
|
Msg("S3 storage initialized")
|
|
|
|
return storage, nil
|
|
}
|
|
|
|
// Get retrieves data from S3
|
|
func (s *S3Storage) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
|
fullKey := s.buildKey(key)
|
|
|
|
log.Debug().Str("key", fullKey).Msg("Getting object from S3")
|
|
|
|
result, err := s.client.GetObject(ctx, &s3.GetObjectInput{
|
|
Bucket: aws.String(s.bucket),
|
|
Key: aws.String(fullKey),
|
|
})
|
|
|
|
if err != nil {
|
|
if isNotFoundError(err) {
|
|
return nil, errors.NotFound(fmt.Sprintf("S3 object not found: %s", key))
|
|
}
|
|
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to get object from S3")
|
|
}
|
|
|
|
return result.Body, nil
|
|
}
|
|
|
|
// Put stores data in S3
|
|
func (s *S3Storage) Put(ctx context.Context, key string, data io.Reader, opts *storage.PutOptions) error {
|
|
fullKey := s.buildKey(key)
|
|
|
|
// Read data into buffer to get size
|
|
buf := new(bytes.Buffer)
|
|
size, err := io.Copy(buf, data)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to read data: %w", err)
|
|
}
|
|
|
|
log.Debug().
|
|
Str("key", fullKey).
|
|
Int64("size", size).
|
|
Msg("Putting object to S3")
|
|
|
|
// Check quota if set
|
|
if s.maxSizeBytes > 0 {
|
|
currentUsage, usageErr := s.calculateUsage(ctx)
|
|
if usageErr != nil {
|
|
log.Warn().Err(usageErr).Msg("Failed to calculate current usage, skipping quota check")
|
|
} else if currentUsage+size > s.maxSizeBytes {
|
|
return errors.QuotaExceeded(s.maxSizeBytes)
|
|
}
|
|
}
|
|
|
|
// Convert metadata to S3 metadata format
|
|
s3Metadata := make(map[string]string)
|
|
if opts != nil && opts.Metadata != nil {
|
|
for k, v := range opts.Metadata {
|
|
s3Metadata[k] = v
|
|
}
|
|
}
|
|
|
|
// Upload to S3
|
|
_, err = s.client.PutObject(ctx, &s3.PutObjectInput{
|
|
Bucket: aws.String(s.bucket),
|
|
Key: aws.String(fullKey),
|
|
Body: bytes.NewReader(buf.Bytes()),
|
|
Metadata: s3Metadata,
|
|
})
|
|
|
|
if err != nil {
|
|
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to put object to S3")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Delete removes data from S3
|
|
func (s *S3Storage) Delete(ctx context.Context, key string) error {
|
|
fullKey := s.buildKey(key)
|
|
|
|
log.Debug().Str("key", fullKey).Msg("Deleting object from S3")
|
|
|
|
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
|
Bucket: aws.String(s.bucket),
|
|
Key: aws.String(fullKey),
|
|
})
|
|
|
|
if err != nil {
|
|
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to delete object from S3")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Exists checks if data exists in S3
|
|
func (s *S3Storage) Exists(ctx context.Context, key string) (bool, error) {
|
|
fullKey := s.buildKey(key)
|
|
|
|
_, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{
|
|
Bucket: aws.String(s.bucket),
|
|
Key: aws.String(fullKey),
|
|
})
|
|
|
|
if err != nil {
|
|
if isNotFoundError(err) {
|
|
return false, nil
|
|
}
|
|
return false, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to check object existence in S3")
|
|
}
|
|
|
|
return true, nil
|
|
}
|
|
|
|
// List returns a list of objects with the given prefix
|
|
func (s *S3Storage) List(ctx context.Context, prefix string, opts *storage.ListOptions) ([]storage.StorageObject, error) {
|
|
fullPrefix := s.buildKey(prefix)
|
|
|
|
log.Debug().Str("prefix", fullPrefix).Msg("Listing objects in S3")
|
|
|
|
var objects []storage.StorageObject
|
|
paginator := s3.NewListObjectsV2Paginator(s.client, &s3.ListObjectsV2Input{
|
|
Bucket: aws.String(s.bucket),
|
|
Prefix: aws.String(fullPrefix),
|
|
})
|
|
|
|
for paginator.HasMorePages() {
|
|
page, err := paginator.NextPage(ctx)
|
|
if err != nil {
|
|
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to list objects in S3")
|
|
}
|
|
|
|
for _, obj := range page.Contents {
|
|
if obj.Key != nil {
|
|
// Strip prefix from key
|
|
key := s.stripPrefix(*obj.Key)
|
|
|
|
object := storage.StorageObject{
|
|
Key: key,
|
|
Size: aws.ToInt64(obj.Size),
|
|
}
|
|
|
|
if obj.LastModified != nil {
|
|
object.Modified = *obj.LastModified
|
|
}
|
|
|
|
if obj.ETag != nil {
|
|
object.ETag = *obj.ETag
|
|
}
|
|
|
|
objects = append(objects, object)
|
|
}
|
|
}
|
|
}
|
|
|
|
return objects, nil
|
|
}
|
|
|
|
// Stat returns metadata about stored data
|
|
func (s *S3Storage) Stat(ctx context.Context, key string) (*storage.StorageInfo, error) {
|
|
fullKey := s.buildKey(key)
|
|
|
|
result, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{
|
|
Bucket: aws.String(s.bucket),
|
|
Key: aws.String(fullKey),
|
|
})
|
|
|
|
if err != nil {
|
|
if isNotFoundError(err) {
|
|
return nil, errors.NotFound(fmt.Sprintf("S3 object not found: %s", key))
|
|
}
|
|
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to stat object in S3")
|
|
}
|
|
|
|
info := &storage.StorageInfo{
|
|
Key: key,
|
|
Size: aws.ToInt64(result.ContentLength),
|
|
}
|
|
|
|
if result.LastModified != nil {
|
|
info.Modified = *result.LastModified
|
|
}
|
|
|
|
if result.ETag != nil {
|
|
info.ETag = *result.ETag
|
|
}
|
|
|
|
if result.ContentType != nil {
|
|
info.ContentType = *result.ContentType
|
|
}
|
|
|
|
return info, nil
|
|
}
|
|
|
|
// GetQuota returns current usage and quota information
|
|
func (s *S3Storage) GetQuota(ctx context.Context) (*storage.QuotaInfo, error) {
|
|
usage, err := s.calculateUsage(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &storage.QuotaInfo{
|
|
Used: usage,
|
|
Limit: s.maxSizeBytes,
|
|
}, nil
|
|
}
|
|
|
|
// Health checks if the S3 backend is healthy
|
|
func (s *S3Storage) Health(ctx context.Context) error {
|
|
// Try to list objects (lightweight operation)
|
|
_, err := s.client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
|
|
Bucket: aws.String(s.bucket),
|
|
MaxKeys: aws.Int32(1),
|
|
})
|
|
|
|
if err != nil {
|
|
return errors.Wrap(err, errors.ErrCodeStorageFailure, "S3 health check failed")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Close closes the S3 storage backend
|
|
func (s *S3Storage) Close() error {
|
|
log.Info().Msg("S3 storage closed")
|
|
return nil
|
|
}
|
|
|
|
// buildKey constructs the full S3 key with prefix
|
|
func (s *S3Storage) buildKey(key string) string {
|
|
if s.prefix == "" {
|
|
return key
|
|
}
|
|
return s.prefix + "/" + key
|
|
}
|
|
|
|
// stripPrefix removes the prefix from an S3 key
|
|
func (s *S3Storage) stripPrefix(key string) string {
|
|
if s.prefix == "" {
|
|
return key
|
|
}
|
|
return strings.TrimPrefix(key, s.prefix+"/")
|
|
}
|
|
|
|
// calculateUsage calculates total storage usage
|
|
func (s *S3Storage) calculateUsage(ctx context.Context) (int64, error) {
|
|
var totalSize int64
|
|
|
|
paginator := s3.NewListObjectsV2Paginator(s.client, &s3.ListObjectsV2Input{
|
|
Bucket: aws.String(s.bucket),
|
|
Prefix: aws.String(s.prefix),
|
|
})
|
|
|
|
for paginator.HasMorePages() {
|
|
page, err := paginator.NextPage(ctx)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("failed to calculate usage: %w", err)
|
|
}
|
|
|
|
for _, obj := range page.Contents {
|
|
if obj.Size != nil {
|
|
totalSize += aws.ToInt64(obj.Size)
|
|
}
|
|
}
|
|
}
|
|
|
|
return totalSize, nil
|
|
}
|
|
|
|
// isNotFoundError checks if an error is a "not found" error
|
|
func isNotFoundError(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
|
|
// Check for specific S3 error types
|
|
var notFound *types.NotFound
|
|
var noSuchKey *types.NoSuchKey
|
|
|
|
// Use errors.As to check for wrapped errors
|
|
if ok := stderrors.As(err, ¬Found); ok {
|
|
return true
|
|
}
|
|
if ok := stderrors.As(err, &noSuchKey); ok {
|
|
return true
|
|
}
|
|
|
|
// Check error message as fallback
|
|
errMsg := err.Error()
|
|
return strings.Contains(errMsg, "NoSuchKey") ||
|
|
strings.Contains(errMsg, "NotFound") ||
|
|
strings.Contains(errMsg, "404")
|
|
}
|