lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
// Package objectstore defines the S3-compatible port used by attachments.
|
||||
// Metadata never belongs here: PostgreSQL is the source of truth, this package
|
||||
// only moves bytes and exposes object timestamps for the orphan sweeper.
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Object is the provider-neutral view of one stored object.
|
||||
type Object struct {
|
||||
Key string
|
||||
Size int64
|
||||
ContentType string
|
||||
LastModified time.Time
|
||||
Metadata map[string]string
|
||||
}
|
||||
|
||||
// Store is implemented by S3-compatible backends. Put requires a seekable body
|
||||
// because AWS SigV4 may need to rewind the payload; the proxy upload path always
|
||||
// passes an *os.File.
|
||||
type Store interface {
|
||||
// Ping verifies that the bucket is reachable and the credentials are valid.
|
||||
Ping(ctx context.Context) error
|
||||
Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string, metadata map[string]string) error
|
||||
Open(ctx context.Context, key string) (io.ReadCloser, Object, error)
|
||||
Head(ctx context.Context, key string) (Object, error)
|
||||
Copy(ctx context.Context, src, dst, contentType string, metadata map[string]string) error
|
||||
Delete(ctx context.Context, key string) error
|
||||
List(ctx context.Context, prefix string) ([]Object, error)
|
||||
PresignPut(ctx context.Context, key string, size int64, ttl time.Duration) (string, time.Time, error)
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"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/aws/smithy-go"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
// Config is the S3 connection subset. Limits belong to the attachment service.
|
||||
type Config struct {
|
||||
Endpoint string
|
||||
PublicEndpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
UsePathStyle bool
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// S3 is an object store backed by an S3-compatible server (SeaweedFS in the
|
||||
// lab stand, MinIO/AWS in other deployments).
|
||||
type S3 struct {
|
||||
bucket string
|
||||
internal *s3.Client
|
||||
public *s3.Client
|
||||
timeout time.Duration
|
||||
transport *http.Transport
|
||||
}
|
||||
|
||||
var _ Store = (*S3)(nil)
|
||||
|
||||
func New(cfg Config) (*S3, error) {
|
||||
if cfg.Endpoint == "" || cfg.Region == "" || cfg.Bucket == "" {
|
||||
return nil, errors.New("object store: endpoint, region and bucket are required")
|
||||
}
|
||||
|
||||
if cfg.AccessKeyID == "" || cfg.SecretAccessKey == "" {
|
||||
return nil, errors.New("object store: access key id and secret access key are required")
|
||||
}
|
||||
|
||||
if cfg.PublicEndpoint == "" {
|
||||
cfg.PublicEndpoint = cfg.Endpoint
|
||||
}
|
||||
|
||||
for _, endpoint := range []string{cfg.Endpoint, cfg.PublicEndpoint} {
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil {
|
||||
return nil, errors.New("object store: endpoints must be https urls without credentials")
|
||||
}
|
||||
if u.RawQuery != "" || u.Fragment != "" {
|
||||
return nil, errors.New("object store: endpoints must not contain a query or fragment")
|
||||
}
|
||||
}
|
||||
clientTLS, err := tlsconfig.NewClientFromEnv("")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure object store tls: %w", err)
|
||||
}
|
||||
transport := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 3 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
TLSClientConfig: clientTLS,
|
||||
TLSHandshakeTimeout: 3 * time.Second,
|
||||
ResponseHeaderTimeout: 15 * time.Second,
|
||||
MaxIdleConnsPerHost: 16,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
}
|
||||
httpClient := &http.Client{
|
||||
Transport: transport,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return errors.New("object store: redirects are not permitted")
|
||||
},
|
||||
// Downloads stream through the response body; an overall timeout
|
||||
// would abort them.
|
||||
}
|
||||
|
||||
newClient := func(endpoint string) *s3.Client {
|
||||
return s3.New(s3.Options{
|
||||
Region: cfg.Region,
|
||||
BaseEndpoint: aws.String(endpoint),
|
||||
UsePathStyle: cfg.UsePathStyle,
|
||||
Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKeyID, cfg.SecretAccessKey, ""),
|
||||
HTTPClient: httpClient,
|
||||
})
|
||||
}
|
||||
|
||||
st := &S3{
|
||||
bucket: cfg.Bucket,
|
||||
internal: newClient(cfg.Endpoint),
|
||||
public: newClient(cfg.PublicEndpoint),
|
||||
timeout: cfg.Timeout,
|
||||
transport: transport,
|
||||
}
|
||||
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// Close releases idle connections owned by the S3 clients.
|
||||
func (s *S3) Close() { s.transport.CloseIdleConnections() }
|
||||
|
||||
func (s *S3) Ping(ctx context.Context) error {
|
||||
// HeadBucket needs bucket-level permissions that the application identity
|
||||
// intentionally does not have. A HeadObject on a sentinel staging key is
|
||||
// enough to prove connectivity and the object-level credentials; a missing
|
||||
// sentinel is the expected healthy result.
|
||||
_, err := s.Head(ctx, "staging/.health/ping")
|
||||
if err == nil || errors.Is(err, domain.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *S3) Put(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
body io.ReadSeeker,
|
||||
size int64,
|
||||
contentType string,
|
||||
metadata map[string]string,
|
||||
) error {
|
||||
ctx, cancel := s.operationContext(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.internal.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
Body: body,
|
||||
ContentLength: aws.Int64(size),
|
||||
ContentType: aws.String(contentType),
|
||||
Metadata: metadata,
|
||||
})
|
||||
if err != nil {
|
||||
return mapObjectError("put object", key, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Open(ctx context.Context, key string) (io.ReadCloser, Object, error) {
|
||||
output, err := s.internal.GetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, Object{}, mapObjectError("open object", key, err)
|
||||
}
|
||||
|
||||
object := Object{
|
||||
Key: key,
|
||||
Size: aws.ToInt64(output.ContentLength),
|
||||
ContentType: aws.ToString(output.ContentType),
|
||||
LastModified: aws.ToTime(output.LastModified),
|
||||
Metadata: output.Metadata,
|
||||
}
|
||||
|
||||
return output.Body, object, nil
|
||||
}
|
||||
|
||||
func (s *S3) Head(ctx context.Context, key string) (Object, error) {
|
||||
output, err := s.internal.HeadObject(ctx, &s3.HeadObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return Object{}, mapObjectError("head object", key, err)
|
||||
}
|
||||
|
||||
return Object{
|
||||
Key: key,
|
||||
Size: aws.ToInt64(output.ContentLength),
|
||||
ContentType: aws.ToString(output.ContentType),
|
||||
LastModified: aws.ToTime(output.LastModified),
|
||||
Metadata: output.Metadata,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *S3) Copy(ctx context.Context, src, dst, contentType string, metadata map[string]string) error {
|
||||
ctx, cancel := s.operationContext(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.internal.CopyObject(ctx, &s3.CopyObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(dst),
|
||||
CopySource: aws.String(s.bucket + "/" + src),
|
||||
MetadataDirective: types.MetadataDirectiveReplace,
|
||||
ContentType: aws.String(contentType),
|
||||
Metadata: metadata,
|
||||
})
|
||||
if err != nil {
|
||||
return mapObjectError("copy object", src+" -> "+dst, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Delete(ctx context.Context, key string) error {
|
||||
ctx, cancel := s.operationContext(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.internal.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return mapObjectError("delete object", key, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) List(ctx context.Context, prefix string) ([]Object, error) {
|
||||
ctx, cancel := s.operationContext(ctx)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
objects []Object
|
||||
token *string
|
||||
)
|
||||
|
||||
for {
|
||||
output, err := s.internal.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Prefix: aws.String(prefix),
|
||||
ContinuationToken: token,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, mapObjectError("list objects", prefix, err)
|
||||
}
|
||||
|
||||
for _, item := range output.Contents {
|
||||
objects = append(objects, Object{
|
||||
Key: aws.ToString(item.Key),
|
||||
Size: aws.ToInt64(item.Size),
|
||||
LastModified: aws.ToTime(item.LastModified),
|
||||
})
|
||||
}
|
||||
|
||||
if !aws.ToBool(output.IsTruncated) {
|
||||
break
|
||||
}
|
||||
|
||||
token = output.NextContinuationToken
|
||||
if token == nil || *token == "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return objects, nil
|
||||
}
|
||||
|
||||
// PresignPut signs the bucket, key, host and exact Content-Length. The size is
|
||||
// therefore enforced by S3 at write time: a client that uploads a different
|
||||
// number of bytes gets 403 SignatureDoesNotMatch. Content-Type and checksums
|
||||
// are not signed (SeaweedFS does not validate checksums); completion verifies
|
||||
// the actual bytes and their structure.
|
||||
func (s *S3) PresignPut(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
size int64,
|
||||
ttl time.Duration,
|
||||
) (string, time.Time, error) {
|
||||
expiresAt := time.Now().UTC().Add(ttl)
|
||||
|
||||
presigned, err := s3.NewPresignClient(s.public).PresignPutObject(
|
||||
ctx,
|
||||
&s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
ContentLength: aws.Int64(size),
|
||||
},
|
||||
func(options *s3.PresignOptions) {
|
||||
options.Expires = ttl
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return "", time.Time{}, mapObjectError("presign put", key, err)
|
||||
}
|
||||
|
||||
return presigned.URL, expiresAt, nil
|
||||
}
|
||||
|
||||
func (s *S3) operationContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
if s.timeout <= 0 {
|
||||
return context.WithCancel(ctx)
|
||||
}
|
||||
|
||||
return context.WithTimeout(ctx, s.timeout)
|
||||
}
|
||||
|
||||
func mapObjectError(operation, subject string, err error) error {
|
||||
var apiErr smithy.APIError
|
||||
|
||||
if errors.As(err, &apiErr) {
|
||||
switch apiErr.ErrorCode() {
|
||||
case "NoSuchBucket":
|
||||
return fmt.Errorf("%w: %s %q: %w", domain.ErrUnavailable, operation, subject, err)
|
||||
case "NotFound", "NoSuchKey":
|
||||
return fmt.Errorf("%s %q: %w", operation, subject, domain.ErrNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return fmt.Errorf("%s %q: %w", operation, subject, err)
|
||||
}
|
||||
|
||||
if strings.Contains(strings.ToLower(err.Error()), "no such key") {
|
||||
return fmt.Errorf("%s %q: %w", operation, subject, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %s %q: %w", domain.ErrUnavailable, operation, subject, err)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/aws/smithy-go"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
func TestMapObjectErrorBucketIsUnavailable(t *testing.T) {
|
||||
err := mapObjectError("put object", "key", &smithy.GenericAPIError{
|
||||
Code: "NoSuchBucket",
|
||||
Message: "bucket is missing",
|
||||
})
|
||||
require.ErrorIs(t, err, domain.ErrUnavailable)
|
||||
}
|
||||
|
||||
func TestMapObjectErrorMissingKeyIsNotFound(t *testing.T) {
|
||||
err := mapObjectError("open object", "key", &smithy.GenericAPIError{
|
||||
Code: "NoSuchKey",
|
||||
Message: "object is missing",
|
||||
})
|
||||
require.ErrorIs(t, err, domain.ErrNotFound)
|
||||
}
|
||||
Reference in New Issue
Block a user