forked from mtusi2026/mtusi2026lab7
feat: secure service connections and login
This commit is contained in:
@@ -6,6 +6,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -18,7 +20,8 @@ import (
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/security/tlsconfig"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("object not found")
|
||||
@@ -30,6 +33,7 @@ type Config struct {
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
UseTLS bool
|
||||
CAPath string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
@@ -47,11 +51,27 @@ func New(config Config) (*Store, error) {
|
||||
if strings.TrimSpace(config.Bucket) == "" || config.Timeout <= 0 {
|
||||
return nil, errors.New("invalid object store configuration")
|
||||
}
|
||||
client, err := minio.New(endpoint, &minio.Options{
|
||||
options := &minio.Options{
|
||||
Creds: credentials.NewStaticV4(config.AccessKey, config.SecretKey, ""),
|
||||
Secure: config.UseTLS,
|
||||
Region: config.Region,
|
||||
})
|
||||
}
|
||||
if config.UseTLS {
|
||||
host, _, err := net.SplitHostPort(endpoint)
|
||||
if err != nil {
|
||||
return nil, errors.New("S3 endpoint must include a port")
|
||||
}
|
||||
tlsConfiguration, err := tlsconfig.LoadClient(tlsconfig.ClientConfig{
|
||||
CAPath: config.CAPath, ServerName: host,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load S3 TLS configuration: %w", err)
|
||||
}
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.TLSClientConfig = tlsConfiguration
|
||||
options.Transport = transport
|
||||
}
|
||||
client, err := minio.New(endpoint, options)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create S3 client: %w", err)
|
||||
}
|
||||
@@ -79,12 +99,8 @@ func endpointHost(value string, useTLS bool) (string, error) {
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
exists, err := s.client.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check S3 bucket: %w", err)
|
||||
}
|
||||
if !exists {
|
||||
return errors.New("S3 bucket does not exist")
|
||||
if _, err := s.client.GetBucketLocation(ctx, s.bucket); err != nil {
|
||||
return fmt.Errorf("check S3 bucket location: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user