Выполнение lab4 на 4
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
// Package objectstore stores original bytes; chat authorization belongs to the service.
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"github.com/minio/minio-go/v7/pkg/s3utils"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrConfig = errors.New("invalid S3 configuration")
|
||||
ErrInput = errors.New("invalid object input")
|
||||
ErrNotFound = errors.New("S3 object not found")
|
||||
ErrUnavailable = errors.New("S3 unavailable")
|
||||
)
|
||||
|
||||
const operationTimeout = 30 * time.Second
|
||||
|
||||
type Config struct {
|
||||
Endpoint, Region, Bucket string
|
||||
AccessKeyFile, SecretKeyFile string
|
||||
}
|
||||
|
||||
type S3 struct {
|
||||
core *minio.Core
|
||||
bucket string
|
||||
transport *http.Transport
|
||||
}
|
||||
|
||||
func New(config Config) (*S3, error) {
|
||||
u, err := url.Parse(config.Endpoint)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" || config.Region == "" {
|
||||
return nil, ErrConfig
|
||||
}
|
||||
if err := s3utils.CheckValidBucketNameStrict(config.Bucket); err != nil {
|
||||
return nil, ErrConfig
|
||||
}
|
||||
access, err := readSecret(config.AccessKeyFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
secret, err := readSecret(config.SecretKeyFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
transport := &http.Transport{
|
||||
DialContext: (&net.Dialer{Timeout: 5 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
|
||||
TLSHandshakeTimeout: 5 * time.Second, ResponseHeaderTimeout: 5 * time.Second,
|
||||
IdleConnTimeout: 60 * time.Second, MaxIdleConns: 10, MaxIdleConnsPerHost: 10,
|
||||
}
|
||||
core, err := minio.NewCore(u.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(access, secret, ""), Secure: u.Scheme == "https",
|
||||
Region: config.Region, BucketLookup: minio.BucketLookupPath,
|
||||
Transport: transport, MaxRetries: 1,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, ErrConfig
|
||||
}
|
||||
return &S3{core: core, bucket: config.Bucket, transport: transport}, nil
|
||||
}
|
||||
|
||||
func readSecret(path string) (string, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", ErrConfig
|
||||
}
|
||||
value := strings.TrimRight(string(data), "\r\n")
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return "", ErrConfig
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (s *S3) Close() { s.transport.CloseIdleConnections() }
|
||||
|
||||
func (s *S3) Check(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 1500*time.Millisecond)
|
||||
defer cancel()
|
||||
exists, err := s.core.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return storageError(ctx, err)
|
||||
}
|
||||
if !exists {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ObjectKey(id string) (string, error) {
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil || parsed.String() != id {
|
||||
return "", ErrInput
|
||||
}
|
||||
return "attachments/" + id, nil
|
||||
}
|
||||
|
||||
func (s *S3) Put(ctx context.Context, id string, source io.Reader, size int64, contentType, sha256 string) error {
|
||||
key, err := ObjectKey(id)
|
||||
checksum, checksumErr := hex.DecodeString(sha256)
|
||||
if err != nil || source == nil || size < 1 || size > 10485760 || (contentType != "image/png" && contentType != "image/jpeg") || checksumErr != nil || len(checksum) != 32 || strings.ToLower(sha256) != sha256 {
|
||||
return ErrInput
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
|
||||
defer cancel()
|
||||
_, err = s.core.PutObject(ctx, s.bucket, key, source, size, "", sha256, minio.PutObjectOptions{ContentType: contentType})
|
||||
return storageError(ctx, err)
|
||||
}
|
||||
|
||||
type Original struct {
|
||||
Body io.ReadCloser
|
||||
SizeBytes int64
|
||||
ContentType string
|
||||
}
|
||||
|
||||
func (s *S3) Open(ctx context.Context, id string) (Original, error) {
|
||||
key, err := ObjectKey(id)
|
||||
if err != nil {
|
||||
return Original{}, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
|
||||
body, info, _, err := s.core.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
mapped := storageError(ctx, err)
|
||||
cancel()
|
||||
return Original{}, mapped
|
||||
}
|
||||
return Original{Body: &originalBody{ReadCloser: body, cancel: cancel}, SizeBytes: info.Size, ContentType: info.ContentType}, nil
|
||||
}
|
||||
|
||||
func (s *S3) Delete(ctx context.Context, id string) error {
|
||||
key, err := ObjectKey(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
|
||||
defer cancel()
|
||||
return storageError(ctx, s.core.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}))
|
||||
}
|
||||
|
||||
func storageError(ctx context.Context, err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
switch minio.ToErrorResponse(err).Code {
|
||||
case "NoSuchKey", "NoSuchObject":
|
||||
return ErrNotFound
|
||||
default:
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
type originalBody struct {
|
||||
io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
once sync.Once
|
||||
err error
|
||||
}
|
||||
|
||||
func (b *originalBody) Close() error {
|
||||
b.once.Do(func() { b.err = b.ReadCloser.Close(); b.cancel() })
|
||||
return b.err
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/upload"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestObjectKey(t *testing.T) {
|
||||
for _, bad := range []string{"", "../x", "photo.png", "550E8400-E29B-41D4-A716-446655440000"} {
|
||||
if _, err := ObjectKey(bad); !errors.Is(err, ErrInput) {
|
||||
t.Fatalf("accepted key %q", bad)
|
||||
}
|
||||
}
|
||||
id := uuid.NewString()
|
||||
if key, err := ObjectKey(id); err != nil || key != "attachments/"+id {
|
||||
t.Fatal("invalid generated key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidConfig(t *testing.T) {
|
||||
for _, endpoint := range []string{"", "ftp://s3:9000", "http://user:password@s3:9000", "http://s3:9000/path", "http://s3:9000?secret=hidden"} {
|
||||
_, err := New(Config{Endpoint: endpoint, Region: "us-east-1", Bucket: "messenger-attachments"})
|
||||
if !errors.Is(err, ErrConfig) {
|
||||
t.Fatal("invalid config accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3Integration(t *testing.T) {
|
||||
if os.Getenv("S3_INTEGRATION") != "1" {
|
||||
t.Skip("explicit S3 integration mode required")
|
||||
}
|
||||
config := Config{
|
||||
Endpoint: os.Getenv("S3_ENDPOINT"), Region: os.Getenv("S3_REGION"), Bucket: os.Getenv("S3_BUCKET"),
|
||||
AccessKeyFile: os.Getenv("S3_ACCESS_KEY_ID_FILE"), SecretKeyFile: os.Getenv("S3_SECRET_ACCESS_KEY_FILE"),
|
||||
}
|
||||
client, err := New(config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
ctx := context.Background()
|
||||
id := uuid.NewString()
|
||||
defer func() {
|
||||
if err := client.Delete(context.Background(), id); err != nil {
|
||||
t.Errorf("fixture cleanup: %v", err)
|
||||
}
|
||||
}()
|
||||
var encoded bytes.Buffer
|
||||
if err := png.Encode(&encoded, image.NewNRGBA(image.Rect(0, 0, 3, 2))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := upload.NewValidator(t.TempDir()).Prepare(ctx, bytes.NewReader(encoded.Bytes()), "image/png", "original.png")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer p.Close()
|
||||
if err := client.Put(ctx, id, p.File, p.SizeBytes, p.ContentType, p.SHA256); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log("PASS: validated original uploaded with API credentials")
|
||||
original, err := client.Open(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, readErr := io.ReadAll(original.Body)
|
||||
closeErr := original.Body.Close()
|
||||
if readErr != nil || closeErr != nil {
|
||||
t.Fatalf("download: %v %v", readErr, closeErr)
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
if !bytes.Equal(data, encoded.Bytes()) || original.SizeBytes != p.SizeBytes || original.ContentType != "image/png" || hex.EncodeToString(sum[:]) != p.SHA256 {
|
||||
t.Fatal("original or metadata mismatch")
|
||||
}
|
||||
t.Log("PASS: downloaded original bytes, MIME, size and SHA-256 match")
|
||||
if err := client.Delete(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := client.Open(ctx, id); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("missing object: %v", err)
|
||||
}
|
||||
if err := client.Delete(ctx, id); err != nil {
|
||||
t.Fatal("repeat delete failed")
|
||||
}
|
||||
t.Log("PASS: deleted object is not found; repeat delete succeeds")
|
||||
cancelled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if _, err := client.Open(cancelled, id); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancellation: %v", err)
|
||||
}
|
||||
t.Log("PASS: caller cancellation propagated")
|
||||
badSecret := filepath.Join(t.TempDir(), "secret")
|
||||
if err := os.WriteFile(badSecret, []byte("deliberately-invalid-secret"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wrongConfig := config
|
||||
wrongConfig.SecretKeyFile = badSecret
|
||||
wrongClient, err := New(wrongConfig)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer wrongClient.Close()
|
||||
if _, err := wrongClient.Open(ctx, id); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("credential failure: %v", err)
|
||||
}
|
||||
t.Log("PASS: incorrect credentials yield sanitized unavailable error")
|
||||
unavailableConfig := config
|
||||
unavailableConfig.Endpoint = "http://127.0.0.1:1"
|
||||
unavailableClient, err := New(unavailableConfig)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer unavailableClient.Close()
|
||||
if _, err := unavailableClient.Open(ctx, id); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("unreachable endpoint: %v", err)
|
||||
}
|
||||
t.Log("PASS: unreachable endpoint yields sanitized unavailable error")
|
||||
}
|
||||
Reference in New Issue
Block a user