forked from mtusi2026/mtusi2026lab7
lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
+83
-109
@@ -1,35 +1,38 @@
|
||||
// Command s3init bootstraps the private attachment bucket. It is idempotent:
|
||||
// it runs before the API on every compose up, verifies the bucket and the
|
||||
// application identity, and exits successfully when everything is in place.
|
||||
// Command s3init idempotently creates the private attachment bucket using
|
||||
// operator-only file credentials over the shared TLS trust boundary.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"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/smithy-go"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/platform/secretfile"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
const bootstrapTimeout = 120 * time.Second
|
||||
|
||||
type settings struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AdminAccessKey string
|
||||
AdminSecretKey string
|
||||
AppAccessKey string
|
||||
AppSecretKey string
|
||||
Endpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -47,21 +50,16 @@ func run(log *slog.Logger) error {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), bootstrapTimeout)
|
||||
signalCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
ctx, cancel := context.WithTimeout(signalCtx, bootstrapTimeout)
|
||||
defer cancel()
|
||||
|
||||
admin := newClient(cfg, cfg.AdminAccessKey, cfg.AdminSecretKey)
|
||||
app := newClient(cfg, cfg.AppAccessKey, cfg.AppSecretKey)
|
||||
|
||||
if err := waitForBucket(ctx, admin, cfg.Bucket); err != nil {
|
||||
client, transport, err := newClient(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := probeAppIdentity(ctx, app, cfg.Bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := probeForbiddenPrefix(ctx, app, cfg.Bucket); err != nil {
|
||||
defer transport.CloseIdleConnections()
|
||||
if err := waitForBucket(ctx, client, cfg.Bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -75,38 +73,60 @@ func run(log *slog.Logger) error {
|
||||
|
||||
func loadSettings() (settings, error) {
|
||||
cfg := settings{
|
||||
Endpoint: strings.TrimSpace(os.Getenv("S3_ENDPOINT")),
|
||||
Region: strings.TrimSpace(os.Getenv("S3_REGION")),
|
||||
Bucket: strings.TrimSpace(os.Getenv("S3_BUCKET")),
|
||||
AdminAccessKey: strings.TrimSpace(os.Getenv("S3_ADMIN_ACCESS_KEY")),
|
||||
AdminSecretKey: strings.TrimSpace(os.Getenv("S3_ADMIN_SECRET_ACCESS_KEY")),
|
||||
AppAccessKey: strings.TrimSpace(os.Getenv("S3_ACCESS_KEY_ID")),
|
||||
AppSecretKey: strings.TrimSpace(os.Getenv("S3_SECRET_ACCESS_KEY")),
|
||||
Endpoint: strings.TrimSpace(os.Getenv("S3_ENDPOINT")),
|
||||
Region: strings.TrimSpace(os.Getenv("S3_REGION")),
|
||||
Bucket: strings.TrimSpace(os.Getenv("S3_BUCKET")),
|
||||
}
|
||||
|
||||
switch {
|
||||
case cfg.Endpoint == "":
|
||||
return settings{}, errors.New("S3_ENDPOINT is required")
|
||||
case cfg.Region == "":
|
||||
return settings{}, errors.New("S3_REGION is required")
|
||||
case cfg.Bucket == "":
|
||||
return settings{}, errors.New("S3_BUCKET is required")
|
||||
case cfg.AdminAccessKey == "" || cfg.AdminSecretKey == "":
|
||||
return settings{}, errors.New("S3_ADMIN_ACCESS_KEY and S3_ADMIN_SECRET_ACCESS_KEY are required")
|
||||
case cfg.AppAccessKey == "" || cfg.AppSecretKey == "":
|
||||
return settings{}, errors.New("S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY are required")
|
||||
endpoint, err := url.Parse(cfg.Endpoint)
|
||||
if err != nil || endpoint.Scheme != "https" || endpoint.Hostname() == "" || endpoint.User != nil {
|
||||
return settings{}, errors.New("s3 endpoint must be an https url without credentials")
|
||||
}
|
||||
if endpoint.RawQuery != "" || endpoint.Fragment != "" {
|
||||
return settings{}, errors.New("s3 endpoint must not contain a query or fragment")
|
||||
}
|
||||
if cfg.Region == "" || cfg.Bucket == "" {
|
||||
return settings{}, errors.New("s3 region and bucket are required")
|
||||
}
|
||||
cfg.AccessKey, err = operatorSecret("S3_ACCESS_KEY_ID_FILE")
|
||||
if err != nil {
|
||||
return settings{}, err
|
||||
}
|
||||
cfg.SecretKey, err = operatorSecret("S3_SECRET_ACCESS_KEY_FILE")
|
||||
if err != nil {
|
||||
return settings{}, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func newClient(cfg settings, accessKey, secretKey string) *s3.Client {
|
||||
return s3.New(s3.Options{
|
||||
func newClient(cfg settings) (*s3.Client, *http.Transport, error) {
|
||||
clientTLS, err := tlsconfig.NewClientFromEnv("")
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("configure object store tls: %w", err)
|
||||
}
|
||||
transport := &http.Transport{
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 3 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
TLSClientConfig: clientTLS,
|
||||
TLSHandshakeTimeout: 3 * time.Second,
|
||||
ResponseHeaderTimeout: 10 * time.Second,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
}
|
||||
client := s3.New(s3.Options{
|
||||
Region: cfg.Region,
|
||||
BaseEndpoint: aws.String(cfg.Endpoint),
|
||||
UsePathStyle: true,
|
||||
Credentials: credentials.NewStaticCredentialsProvider(accessKey, secretKey, ""),
|
||||
Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
HTTPClient: &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: 15 * time.Second,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return errors.New("object store redirects are not permitted")
|
||||
},
|
||||
},
|
||||
})
|
||||
return client, transport, nil
|
||||
}
|
||||
|
||||
func waitForBucket(ctx context.Context, client *s3.Client, bucket string) error {
|
||||
@@ -136,68 +156,6 @@ func waitForBucket(ctx context.Context, client *s3.Client, bucket string) error
|
||||
}
|
||||
}
|
||||
|
||||
func probeAppIdentity(ctx context.Context, client *s3.Client, bucket string) error {
|
||||
key := "staging/.bootstrap/" + uuid.NewString()
|
||||
|
||||
if _, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader([]byte("ok")),
|
||||
ContentLength: aws.Int64(2),
|
||||
ContentType: aws.String("text/plain"),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("application identity cannot write: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_, _ = client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
}()
|
||||
|
||||
if _, err := client.HeadObject(ctx, &s3.HeadObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("application identity cannot read: %w", err)
|
||||
}
|
||||
|
||||
if _, err := client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(bucket),
|
||||
Prefix: aws.String("staging/"),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("application identity cannot list: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func probeForbiddenPrefix(ctx context.Context, client *s3.Client, bucket string) error {
|
||||
key := "forbidden/" + uuid.NewString()
|
||||
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader([]byte("must not be stored")),
|
||||
})
|
||||
if err == nil {
|
||||
_, _ = client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
|
||||
return errors.New("application identity can write outside the allowed prefixes; check infra/s3/s3.json")
|
||||
}
|
||||
|
||||
var apiErr smithy.APIError
|
||||
if !errors.As(err, &apiErr) || apiErr.ErrorCode() != "AccessDenied" {
|
||||
return fmt.Errorf("forbidden-prefix probe returned an unexpected error: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isNotFound(err error) bool {
|
||||
var apiErr smithy.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
@@ -221,3 +179,19 @@ func isBucketExists(err error) bool {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func operatorSecret(env string) (string, error) {
|
||||
path := strings.TrimSpace(os.Getenv(env))
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("%s is required", env)
|
||||
}
|
||||
value, err := secretfile.Read(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", env, err)
|
||||
}
|
||||
secret := strings.TrimSpace(string(value))
|
||||
if secret == "" {
|
||||
return "", fmt.Errorf("%s is empty", env)
|
||||
}
|
||||
return secret, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user