forked from mtusi2026/mtusi2026lab7
69 lines
2.2 KiB
Go
69 lines
2.2 KiB
Go
package config
|
|
|
|
import (
|
|
"fmt"
|
|
"gitea.privcloud.tech/mtusi2026/internal/pkg/transportsecurity"
|
|
"net/url"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type Attachment struct {
|
|
Endpoint, Region, Bucket, AccessKey, SecretKey string
|
|
MaxBytes, MaxPixels int64
|
|
Timeout, Grace time.Duration
|
|
Uploads, Decoders int
|
|
}
|
|
|
|
func LoadAttachment() (*Attachment, error) {
|
|
defaultEndpoint := "http://s3:9000"
|
|
if transportsecurity.Enabled() {
|
|
defaultEndpoint = "https://s3:9443"
|
|
}
|
|
c := &Attachment{Endpoint: env("S3_ENDPOINT", defaultEndpoint), Region: env("S3_REGION", "us-east-1"), Bucket: env("S3_BUCKET", "messenger-attachments"), MaxBytes: 10485760, MaxPixels: 40000000, Timeout: 120 * time.Second, Grace: time.Hour, Uploads: 4, Decoders: 1}
|
|
endpoint, err := url.Parse(c.Endpoint)
|
|
if err != nil || endpoint.Host == "" || (transportsecurity.Enabled() && endpoint.Scheme != "https") {
|
|
return nil, fmt.Errorf("invalid S3 endpoint: verified HTTPS required in TLS mode")
|
|
}
|
|
|
|
for key, dst := range map[string]*string{"S3_ACCESS_KEY_ID_FILE": &c.AccessKey, "S3_SECRET_ACCESS_KEY_FILE": &c.SecretKey} {
|
|
b, e := os.ReadFile(os.Getenv(key))
|
|
if e != nil {
|
|
return nil, fmt.Errorf("read %s: %w", key, e)
|
|
}
|
|
*dst = strings.TrimSpace(string(b))
|
|
if *dst == "" {
|
|
return nil, fmt.Errorf("empty %s", key)
|
|
}
|
|
}
|
|
for key, dst := range map[string]*int64{"MAX_UPLOAD_BYTES": &c.MaxBytes, "MAX_IMAGE_PIXELS": &c.MaxPixels} {
|
|
if v := os.Getenv(key); v != "" {
|
|
*dst, err = strconv.ParseInt(v, 10, 64)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid %s", key)
|
|
}
|
|
}
|
|
}
|
|
for key, dst := range map[string]*time.Duration{"UPLOAD_TIMEOUT": &c.Timeout, "RECONCILE_GRACE_PERIOD": &c.Grace} {
|
|
if v := os.Getenv(key); v != "" {
|
|
*dst, err = time.ParseDuration(v)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid %s", key)
|
|
}
|
|
}
|
|
}
|
|
if c.MaxBytes < 1 || c.MaxBytes > 10485760 || c.MaxPixels < 1 || c.MaxPixels > 40000000 || c.Timeout < time.Second || c.Timeout > 120*time.Second || c.Grace <= 2*c.Timeout {
|
|
return nil, fmt.Errorf("invalid attachment limits or grace period")
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
func env(k, d string) string {
|
|
if v := os.Getenv(k); v != "" {
|
|
return v
|
|
}
|
|
return d
|
|
}
|