Skip to content

πŸ“š The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.

5.7 KB
Raw Blame
package app

import (
	"alexandrie/pkg/logger"
	"alexandrie/utils"
	"context"
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"strings"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"github.com/minio/minio-go/v7/pkg/lifecycle"
)

func MinioConnection() (*minio.Client, *minio.Client, error) {
	ctx := context.Background()

	internalEndpoint := os.Getenv("MINIO_ENDPOINT")
	publicEndpoint := os.Getenv("MINIO_PUBLIC_URL")

	accessKeyID := os.Getenv("MINIO_ACCESSKEY")
	secretAccessKey := os.Getenv("MINIO_SECRETKEY")

	if internalEndpoint == "" || accessKeyID == "" || secretAccessKey == "" {
		return nil, nil, fmt.Errorf("MINIO NOT CONFIGURED")
	}

	// TLS configuration
	rootCAs, err := x509.SystemCertPool()
	if err != nil {
		rootCAs = x509.NewCertPool()
	}

	if caPath := os.Getenv("MINIO_CA_PATH"); caPath != "" {
		caCert, err := os.ReadFile(caPath)
		if err != nil {
			logger.Error("s3", "Failed to read CA certificate: "+err.Error())
		} else if !rootCAs.AppendCertsFromPEM(caCert) {
			logger.Error("s3", "Provided CA certificate could not be parsed")
		} else {
			logger.Success("s3", "Custom S3 CA certificate loaded")
		}
	}

	insecureTLS := os.Getenv("MINIO_INSECURE_TLS") == "true"

	internalTLSConfig := &tls.Config{
		RootCAs:            rootCAs,
		InsecureSkipVerify: insecureTLS,
	}

	publicTLSConfig := &tls.Config{
		RootCAs:            rootCAs,
		InsecureSkipVerify: insecureTLS,
	}

	internalTransport := &http.Transport{
		TLSClientConfig: internalTLSConfig,
	}

	publicTransport := &http.Transport{
		TLSClientConfig: publicTLSConfig,
	}

	// Internal MinIO client
	isSecure := true
	if os.Getenv("MINIO_SECURE") != "" && os.Getenv("MINIO_SECURE") != "true" {
		isSecure = false
	} else if strings.HasPrefix(internalEndpoint, "localhost") || strings.HasPrefix(internalEndpoint, "127.") {
		isSecure = false
	}

	minioClient, err := minio.New(internalEndpoint, &minio.Options{
		Creds:     credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure:    isSecure,
		Transport: internalTransport,
	})
	if err != nil {
		logger.Error("s3", fmt.Sprintf("Failed to initialize MinIO client: %v", err))
		os.Exit(1)
	}

	// Signer client (public URLs / CDN)
	publicURL, err := url.Parse(publicEndpoint)
	if err != nil {
		logger.Error("s3", "CONFIG: MINIO_PUBLIC_URL is not a valid URL")
		os.Exit(1)
	}

	isPublicSecure := publicURL.Scheme == "https"

	signerClient, err := minio.New(publicURL.Host, &minio.Options{
		Creds:        credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure:       isPublicSecure,
		BucketLookup: minio.BucketLookupPath,
		Transport:    publicTransport,
	})
	if err != nil {
		logger.Error("s3", fmt.Sprintf("Failed to create signer client: %v", err))
		logger.Error("s3", "Please check your MINIO_PUBLIC_URL is set correctly.")
		os.Exit(1)
	}

	// Buckets setup
	bucketName := os.Getenv("MINIO_BUCKET")
	setupPublicBucket(ctx, minioClient, bucketName)

	backupBucket := utils.GetBackupBucketName()
	setupPrivateBackupBucket(ctx, minioClient, backupBucket)

	return minioClient, signerClient, nil
}

func setupPublicBucket(ctx context.Context, minioClient *minio.Client, bucketName string) {
	err := minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{})
	if err != nil {
		exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
		if errBucketExists == nil && exists {
			logger.Info("s3", fmt.Sprintf("We already own %s", bucketName))
		} else {
			logger.Error("s3", fmt.Sprintf("Failed to create bucket %s: %v", bucketName, err))
			os.Exit(1)
		}
	} else {
		logger.Success("s3", "Successfully created "+bucketName)
	}

	// Set public read policy for user files
	policy := fmt.Sprintf(`{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "AWS": ["*"] },
      "Action": ["s3:GetObject"],
      "Resource": ["arn:aws:s3:::%s/*"]
    }
  ]
}`, bucketName)

	// Some S3-compatible providers (e.g. Garage) do not implement PutBucketPolicy.
	// Public read access can be configured on the provider side instead, so this
	// is not fatal: warn and keep the backend running.
	err = minioClient.SetBucketPolicy(ctx, bucketName, policy)
	if err != nil {
		logger.Warn("s3", fmt.Sprintf("Failed to set public bucket policy for %s: %v", bucketName, err))
		logger.Warn("s3", "Make sure objects in this bucket are publicly readable (configure it in your S3 provider), otherwise uploaded files will not be accessible.")
		return
	}
	logger.Success("s3", "Successfully set public bucket policy for "+bucketName)
}

func setupPrivateBackupBucket(ctx context.Context, minioClient *minio.Client, bucketName string) {
	err := minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{})
	if err != nil {
		exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
		if errBucketExists == nil && exists {
			logger.Info("s3", fmt.Sprintf("We already own %s", bucketName))
		} else {
			logger.Error("s3", fmt.Sprintf("Failed to create private backup bucket %s: %v", bucketName, err))
			os.Exit(1)
		}
	} else {
		logger.Success("s3", "Successfully created private backup bucket: "+bucketName)
	}

	// Configure lifecycle rule to auto-delete backup files after 1 day
	lifecycleConfig := lifecycle.NewConfiguration()
	lifecycleConfig.Rules = []lifecycle.Rule{
		{
			ID:     "auto-delete-backups",
			Status: "Enabled",
			RuleFilter: lifecycle.Filter{
				Prefix: "",
			},
			Expiration: lifecycle.Expiration{
				Days: 1,
			},
		},
	}

	err = minioClient.SetBucketLifecycle(ctx, bucketName, lifecycleConfig)
	if err != nil {
		logger.Warn("s3", fmt.Sprintf("Failed to set lifecycle policy for backups: %v", err))
	} else {
		logger.Success("s3", "Successfully set lifecycle policy for backups (auto-delete after 24h)")
	}
}