ЛР7 на 4: HTTPS, mTLS, OpenBao AppRole и ротация leaf.
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Smoke/security/grade4/persistence/failover пройдены; REPORT и DEFENSE.
This commit is contained in:
@@ -0,0 +1,362 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gavrilenko-sxdees/lab7/internal/db"
|
||||
"gavrilenko-sxdees/lab7/internal/model"
|
||||
"gavrilenko-sxdees/lab7/internal/postgres"
|
||||
s3store "gavrilenko-sxdees/lab7/internal/s3"
|
||||
"gavrilenko-sxdees/lab7/internal/telemetry"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAttachmentNotFound = errors.New("attachment not found")
|
||||
ErrAttachmentNotReady = errors.New("attachment not ready")
|
||||
ErrInvalidImage = errors.New("invalid image")
|
||||
ErrInvalidSize = errors.New("invalid size")
|
||||
ErrUploadReadTimeout = errors.New("upload body read timed out")
|
||||
)
|
||||
|
||||
type attachmentQueries interface {
|
||||
CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error)
|
||||
CreateOutboxEntry(ctx context.Context, arg db.CreateOutboxEntryParams) (db.Outbox, error)
|
||||
GetAttachmentByID(ctx context.Context, id uuid.UUID) (db.Attachment, error)
|
||||
ListAttachmentVariants(ctx context.Context, arg db.ListAttachmentVariantsParams) ([]db.AttachmentVariant, error)
|
||||
IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error)
|
||||
}
|
||||
|
||||
type AttachmentService struct {
|
||||
pool txBeginner
|
||||
q attachmentQueries
|
||||
withTx func(pgx.Tx) attachmentQueries
|
||||
s3 *s3store.Client
|
||||
maxBytes int
|
||||
maxPixels int
|
||||
decodeSlot chan struct{}
|
||||
}
|
||||
|
||||
func NewAttachmentService(
|
||||
pool *pgxpool.Pool,
|
||||
q *db.Queries,
|
||||
s3 *s3store.Client,
|
||||
maxBytes, maxPixels int,
|
||||
) *AttachmentService {
|
||||
return &AttachmentService{
|
||||
pool: pool,
|
||||
q: q,
|
||||
withTx: func(tx pgx.Tx) attachmentQueries {
|
||||
return q.WithTx(tx)
|
||||
},
|
||||
s3: s3,
|
||||
maxBytes: maxBytes,
|
||||
maxPixels: maxPixels,
|
||||
decodeSlot: make(chan struct{}, 1),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Upload(
|
||||
ctx context.Context,
|
||||
userID, chatID uuid.UUID,
|
||||
filename string,
|
||||
body io.Reader,
|
||||
contentType string,
|
||||
) (model.Attachment, error) {
|
||||
if err := s.ensureMember(ctx, userID, chatID); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
tmp, err := os.CreateTemp("", "upload-*.tmp")
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
defer func() {
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(tmp.Name())
|
||||
}()
|
||||
|
||||
hasher := sha256.New()
|
||||
size, err := io.Copy(io.MultiWriter(tmp, hasher), body)
|
||||
if err != nil {
|
||||
var maxBytesErr *http.MaxBytesError
|
||||
if errors.As(err, &maxBytesErr) {
|
||||
return model.Attachment{}, ErrInvalidSize
|
||||
}
|
||||
var networkErr net.Error
|
||||
if errors.As(err, &networkErr) && networkErr.Timeout() {
|
||||
return model.Attachment{}, ErrUploadReadTimeout
|
||||
}
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
if size > int64(s.maxBytes) {
|
||||
return model.Attachment{}, ErrInvalidSize
|
||||
}
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
detectedType, width, height, err := s.checkImage(ctx, tmp, contentType)
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
jobID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
hash := hex.EncodeToString(hasher.Sum(nil))
|
||||
key := "chats/" + chatID.String() + "/attachments/" + id.String()
|
||||
stagingKey := "staging/" + id.String()
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
if err := s.s3.Put(ctx, stagingKey, tmp, size, string(detectedType)); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
q := s.withTx(tx)
|
||||
|
||||
row, err := q.CreateAttachment(ctx, db.CreateAttachmentParams{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
OwnerID: userID,
|
||||
S3Key: key,
|
||||
StagingKey: stagingKey,
|
||||
JobID: jobID,
|
||||
Filename: filename,
|
||||
ContentType: db.AttachmentContentType(detectedType),
|
||||
SizeBytes: int(size),
|
||||
Sha256: hash,
|
||||
Width: width,
|
||||
Height: height,
|
||||
ErrorCode: "",
|
||||
})
|
||||
if postgres.IsNotFound(err) {
|
||||
return model.Attachment{}, ErrAttachmentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
traceparent, tracestate := telemetry.Inject(ctx)
|
||||
if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||
AttachmentID: id,
|
||||
Attempt: 1,
|
||||
AvailableAt: row.CreatedAt,
|
||||
Traceparent: traceparent,
|
||||
Tracestate: tracestate,
|
||||
}); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
return model.Attachment{
|
||||
ID: row.ID,
|
||||
ChatID: row.ChatID,
|
||||
OwnerID: row.OwnerID,
|
||||
Filename: row.Filename,
|
||||
ContentType: model.ContentType(row.ContentType),
|
||||
SizeBytes: row.SizeBytes,
|
||||
Sha256: row.Sha256,
|
||||
Status: model.AttachmentStatus(row.Status),
|
||||
Width: row.Width,
|
||||
Height: row.Height,
|
||||
ErrorCode: row.ErrorCode,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Get(
|
||||
ctx context.Context,
|
||||
userID, attachmentID uuid.UUID,
|
||||
) (model.Attachment, error) {
|
||||
row, err := s.q.GetAttachmentByID(ctx, attachmentID)
|
||||
if postgres.IsNotFound(err) {
|
||||
return model.Attachment{}, ErrAttachmentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
if err := s.ensureMember(ctx, userID, row.ChatID); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
rows, err := s.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{AttachmentID: row.ID, PipelineVersion: row.PipelineVersion})
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
variants := make([]model.AttachmentVariant, 0, len(rows))
|
||||
for _, v := range rows {
|
||||
variants = append(variants, model.AttachmentVariant{
|
||||
Name: model.AttachmentVariantName(v.Variant),
|
||||
ContentType: model.ContentType(v.ContentType),
|
||||
SizeBytes: v.SizeBytes,
|
||||
Width: v.Width,
|
||||
Height: v.Height,
|
||||
Sha256: v.Sha256,
|
||||
})
|
||||
}
|
||||
|
||||
return model.Attachment{
|
||||
Variants: variants,
|
||||
ID: row.ID,
|
||||
ChatID: row.ChatID,
|
||||
OwnerID: row.OwnerID,
|
||||
Filename: row.Filename,
|
||||
ContentType: model.ContentType(row.ContentType),
|
||||
SizeBytes: row.SizeBytes,
|
||||
Sha256: row.Sha256,
|
||||
Status: model.AttachmentStatus(row.Status),
|
||||
Width: row.Width,
|
||||
Height: row.Height,
|
||||
ErrorCode: row.ErrorCode,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) GetContent(
|
||||
ctx context.Context,
|
||||
userID, attachmentID uuid.UUID,
|
||||
variant string,
|
||||
) ([]byte, model.ContentType, error) {
|
||||
row, err := s.q.GetAttachmentByID(ctx, attachmentID)
|
||||
if postgres.IsNotFound(err) {
|
||||
return nil, "", ErrAttachmentNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if err := s.ensureMember(ctx, userID, row.ChatID); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
if model.AttachmentStatus(row.Status) != model.AttachmentStatusReady {
|
||||
return nil, "", ErrAttachmentNotReady
|
||||
}
|
||||
|
||||
key, contentType := row.S3Key, model.ContentType(row.ContentType)
|
||||
if variant != "" && variant != model.AttachmentContentOriginal {
|
||||
rows, err := s.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{AttachmentID: row.ID, PipelineVersion: row.PipelineVersion})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
found := false
|
||||
for _, v := range rows {
|
||||
if string(v.Variant) == variant {
|
||||
key, contentType, found = v.S3Key, model.ContentType(v.ContentType), true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, "", ErrAttachmentNotFound
|
||||
}
|
||||
}
|
||||
out, err := s.s3.Get(ctx, key)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer out.Body.Close()
|
||||
|
||||
data, err := io.ReadAll(out.Body)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return data, contentType, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) checkImage(ctx context.Context, r io.ReadSeeker, contentType string) (model.ContentType, int, int, error) {
|
||||
cfg, format, err := image.DecodeConfig(r)
|
||||
if err != nil {
|
||||
return "", 0, 0, ErrInvalidImage
|
||||
}
|
||||
|
||||
if cfg.Width <= 0 || cfg.Height <= 0 {
|
||||
return "", 0, 0, ErrInvalidImage
|
||||
}
|
||||
if cfg.Width > s.maxPixels/cfg.Height {
|
||||
return "", 0, 0, ErrInvalidSize
|
||||
}
|
||||
|
||||
var detectedType model.ContentType
|
||||
switch format {
|
||||
case "png":
|
||||
if contentType != string(model.ContentTypePNG) {
|
||||
return "", 0, 0, ErrInvalidImage
|
||||
}
|
||||
detectedType = model.ContentTypePNG
|
||||
case "jpeg":
|
||||
if contentType != string(model.ContentTypeJPEG) {
|
||||
return "", 0, 0, ErrInvalidImage
|
||||
}
|
||||
detectedType = model.ContentTypeJPEG
|
||||
default:
|
||||
return "", 0, 0, ErrInvalidImage
|
||||
}
|
||||
|
||||
select {
|
||||
case s.decodeSlot <- struct{}{}:
|
||||
defer func() { <-s.decodeSlot }()
|
||||
case <-ctx.Done():
|
||||
return "", 0, 0, ctx.Err()
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", 0, 0, err
|
||||
}
|
||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||
return "", 0, 0, err
|
||||
}
|
||||
if _, _, err := image.Decode(r); err != nil {
|
||||
return "", 0, 0, ErrInvalidImage
|
||||
}
|
||||
|
||||
return detectedType, cfg.Width, cfg.Height, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID uuid.UUID) error {
|
||||
member, err := s.q.IsChatMember(ctx, db.IsChatMemberParams{
|
||||
ChatID: chatID,
|
||||
UserID: userID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !member {
|
||||
return ErrAttachmentNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user