Files
supermarket/internal/config/config.go
T
davidandClaude Opus 5.5 d2f1658708 Phase 9, part 5: file storage, a folder or an S3 bucket
internal/storage keeps files that must outlast the app's disk (exports,
uploads) behind one interface: a folder (<data>/files) or an S3-compatible
bucket (minio-go, path-style, for Garage). Names that would reach outside
the store are refused. An S3 store is checked at start; supermarket config
checks the storage and Postgres for real. The same tests run on a folder
and on Garage (SUPERMARKET_TEST_S3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:42:11 -07:00

374 lines
13 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package config reads how Supermarket is run from its environment: which
// edition (local, server or multi-tenant), and what that edition needs
// (a database, a key for secrets, file storage, a mail server). It checks
// that the settings fit together, and says what's wrong when they don't.
package config
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"net"
"net/mail"
"net/url"
"path/filepath"
"strings"
)
// Edition is how Supermarket is run.
type Edition string
const (
// Local is one person on their own computer: no sign-in, SQLite, the
// data folder. The default.
Local Edition = "local"
// Server is one team on a server: sign-in, Postgres.
Server Edition = "server"
// Multi is many teams at one address: sign-in, Postgres, object
// storage, billing.
Multi Edition = "multi"
)
// Name is the edition as the app shows it.
func (e Edition) Name() string {
switch e {
case Server:
return "Server"
case Multi:
return "Multi-tenant"
}
return "Local"
}
// Storage is where files go: a folder, or an S3-compatible bucket.
type Storage struct {
Dir string // a folder, when not S3
Bucket, Prefix string // s3://bucket/prefix
Endpoint string // the S3 server (Garage, …), https://…
Region string
AccessKey string
SecretKey string
}
// S3 says whether files go to object storage.
func (s Storage) S3() bool { return s.Bucket != "" }
// String describes it, without credentials.
func (s Storage) String() string {
if s.S3() {
u := "s3://" + s.Bucket
if s.Prefix != "" {
u += "/" + s.Prefix
}
return u + " at " + s.Endpoint
}
return s.Dir
}
// Mail is the SMTP server the app sends its own mail through
// (invitations, password resets): not a team's outreach mail.
type Mail struct {
Host string // host:port
TLS bool // smtps: TLS from the start; smtp: STARTTLS when offered
User string
Password string
From string // the sender, e.g. "Supermarket <no-reply@example.com>"
}
// Config is how this Supermarket is run.
type Config struct {
Edition Edition
DataDir string // where the local edition keeps everything, and scratch files on the others
Addr string // the address to listen on
PublicURL string // the address people use, without a trailing slash
CoreConf string
MCPSocket string
HostData string // the data folder's path on the host, for instructions
DatabaseURL string // postgres://…; empty on the local edition
SecretKey []byte // 32 bytes that encrypt secrets in the database; nil if not set
OldKey []byte // the key being replaced: secrets under it are encrypted again with SecretKey
Storage Storage
Mail *Mail // nil if not set
}
// Environment variables.
const (
EnvMode = "SUPERMARKET_MODE"
EnvData = "SUPERMARKET_DATA"
EnvAddr = "SUPERMARKET_ADDR"
EnvPublicURL = "SUPERMARKET_PUBLIC_URL"
EnvCoreConf = "SUPERMARKET_CORE_CONF"
EnvMCPSocket = "SUPERMARKET_MCP_SOCKET"
EnvHostData = "SUPERMARKET_HOST_DATA"
EnvDatabaseURL = "SUPERMARKET_DATABASE_URL"
EnvSecretKey = "SUPERMARKET_SECRET_KEY"
EnvOldKey = "SUPERMARKET_SECRET_KEY_OLD"
EnvStorage = "SUPERMARKET_STORAGE"
EnvS3Endpoint = "SUPERMARKET_S3_ENDPOINT"
EnvS3Region = "SUPERMARKET_S3_REGION"
EnvS3AccessKey = "SUPERMARKET_S3_ACCESS_KEY"
EnvS3SecretKey = "SUPERMARKET_S3_SECRET_KEY"
EnvMailURL = "SUPERMARKET_MAIL_URL"
EnvMailFrom = "SUPERMARKET_MAIL_FROM"
)
// Load reads the settings through getenv (os.Getenv) and checks them. All
// the problems found are returned together, one per line.
func Load(getenv func(string) string) (*Config, error) {
get := func(k, def string) string {
if v := strings.TrimSpace(getenv(k)); v != "" {
return v
}
return def
}
var problems []string
bad := func(format string, a ...any) { problems = append(problems, fmt.Sprintf(format, a...)) }
c := &Config{Edition: Edition(strings.ToLower(get(EnvMode, string(Local))))}
switch c.Edition {
case Local, Server, Multi:
default:
bad("%s is %q: it must be local, server or multi", EnvMode, getenv(EnvMode))
}
c.DataDir = get(EnvData, "/data")
c.Addr = get(EnvAddr, ":8080")
c.CoreConf = get(EnvCoreConf, filepath.Join(c.DataDir, "core.conf"))
c.MCPSocket = get(EnvMCPSocket, filepath.Join(c.DataDir, "mcp.sock"))
c.HostData = get(EnvHostData, c.DataDir)
shared := c.Edition == Server || c.Edition == Multi
// The address people use.
c.PublicURL = strings.TrimRight(get(EnvPublicURL, "http://localhost:8470"), "/")
if u, err := url.Parse(c.PublicURL); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
bad("%s is %q: give the address people open, such as https://supermarket.example.com", EnvPublicURL, c.PublicURL)
} else if shared && u.Scheme != "https" {
bad("%s must start with https:// on the %s edition: people sign in through it", EnvPublicURL, c.Edition.Name())
} else if shared && getenv(EnvPublicURL) == "" {
bad("%s is needed on the %s edition: the https:// address people open", EnvPublicURL, c.Edition.Name())
}
// The database.
c.DatabaseURL = get(EnvDatabaseURL, "")
switch {
case c.Edition == Local && c.DatabaseURL != "":
bad("%s is set, but the local edition keeps its database in the data folder (SQLite): unset it, or set %s=server", EnvDatabaseURL, EnvMode)
case shared && c.DatabaseURL == "":
bad("%s is needed on the %s edition: postgres://user:password@host:5432/supermarket", EnvDatabaseURL, c.Edition.Name())
case shared:
if u, err := url.Parse(c.DatabaseURL); err != nil || (u.Scheme != "postgres" && u.Scheme != "postgresql") || u.Host == "" {
bad("%s must be a Postgres address: postgres://user:password@host:5432/supermarket", EnvDatabaseURL)
}
}
// The key for secrets.
if k := get(EnvSecretKey, ""); k != "" {
key, err := ParseKey(k)
if err != nil {
bad("%s: %v (supermarket secret-key makes one)", EnvSecretKey, err)
}
c.SecretKey = key
} else if shared {
bad("%s is needed on the %s edition: it encrypts the keys and tokens kept in the database. Run supermarket secret-key to make one, and keep a copy somewhere safe", EnvSecretKey, c.Edition.Name())
}
if k := get(EnvOldKey, ""); k != "" {
key, err := ParseKey(k)
switch {
case err != nil:
bad("%s: %v", EnvOldKey, err)
case c.SecretKey == nil:
bad("%s is set without %s: give the new key too", EnvOldKey, EnvSecretKey)
case string(key) == string(c.SecretKey):
bad("%s is the same key as %s", EnvOldKey, EnvSecretKey)
}
c.OldKey = key
}
// Files.
c.Storage = loadStorage(get, bad, c.DataDir)
switch {
case c.Edition == Local && c.Storage.S3():
bad("%s is an S3 bucket, but the local edition keeps its files in the data folder: unset it", EnvStorage)
case c.Edition == Multi && !c.Storage.S3():
bad("%s must be an S3 bucket on the multi-tenant edition (s3://bucket/prefix), so every copy of the app sees the same files", EnvStorage)
}
// The app's own mail.
if m := get(EnvMailURL, ""); m != "" {
mm, err := parseMail(m, get(EnvMailFrom, ""), c.PublicURL)
if err != nil {
bad("%s: %v", EnvMailURL, err)
}
c.Mail = mm
} else if shared {
bad("%s is needed on the %s edition, to send invitations and password resets: smtp://user:password@mail.example.com:587", EnvMailURL, c.Edition.Name())
}
if len(problems) > 0 {
return c, errors.New(strings.Join(problems, "\n"))
}
return c, nil
}
func loadStorage(get func(string, string) string, bad func(string, ...any), dataDir string) Storage {
v := get(EnvStorage, "")
if v == "" {
return Storage{Dir: filepath.Join(dataDir, "files")}
}
if !strings.HasPrefix(v, "s3://") {
if !filepath.IsAbs(v) {
bad("%s is %q: give a folder's full path, or s3://bucket/prefix", EnvStorage, v)
}
return Storage{Dir: filepath.Clean(v)}
}
u, err := url.Parse(v)
if err != nil || u.Host == "" {
bad("%s is %q: an S3 bucket is s3://bucket or s3://bucket/prefix", EnvStorage, v)
return Storage{}
}
s := Storage{
Bucket: u.Host, Prefix: strings.Trim(u.Path, "/"),
Endpoint: strings.TrimRight(get(EnvS3Endpoint, ""), "/"),
Region: get(EnvS3Region, "garage"),
AccessKey: get(EnvS3AccessKey, ""),
SecretKey: get(EnvS3SecretKey, ""),
}
if e, err := url.Parse(s.Endpoint); s.Endpoint == "" || err != nil || (e.Scheme != "https" && e.Scheme != "http") || e.Host == "" {
bad("%s is needed with an S3 bucket: the storage server's address, such as https://s3.example.com", EnvS3Endpoint)
}
if s.AccessKey == "" || s.SecretKey == "" {
bad("%s and %s are needed with an S3 bucket", EnvS3AccessKey, EnvS3SecretKey)
}
return s
}
func parseMail(raw, from, publicURL string) (*Mail, error) {
u, err := url.Parse(raw)
if err != nil || (u.Scheme != "smtp" && u.Scheme != "smtps") || u.Hostname() == "" {
return nil, errors.New("give the mail server as smtp://user:password@host:587 (STARTTLS) or smtps://…:465 (TLS)")
}
m := &Mail{TLS: u.Scheme == "smtps", Host: u.Host}
if u.Port() == "" {
port := "587"
if m.TLS {
port = "465"
}
m.Host = net.JoinHostPort(u.Hostname(), port)
}
if u.User != nil {
m.User = u.User.Username()
m.Password, _ = u.User.Password()
}
if from == "" {
from = u.Query().Get("from")
}
if from == "" {
host := "localhost"
if pu, err := url.Parse(publicURL); err == nil && pu.Hostname() != "" {
host = pu.Hostname()
}
from = "Supermarket <no-reply@" + host + ">"
}
if _, err := mail.ParseAddress(from); err != nil {
return nil, fmt.Errorf("the sender %q isn't an email address (%s)", from, EnvMailFrom)
}
m.From = from
return m, nil
}
// ParseKey reads a secret key: 32 bytes as 64 hex digits, or as base64.
func ParseKey(s string) ([]byte, error) {
s = strings.TrimSpace(s)
if b, err := hex.DecodeString(s); err == nil && len(b) == 32 {
return b, nil
}
for _, enc := range []*base64.Encoding{base64.StdEncoding, base64.RawStdEncoding, base64.URLEncoding, base64.RawURLEncoding} {
if b, err := enc.DecodeString(s); err == nil && len(b) == 32 {
return b, nil
}
}
return nil, errors.New("it must be 32 random bytes, as 64 hex digits or base64")
}
// NewKey makes a secret key, as 64 hex digits.
func NewKey() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
// Ready says whether this version of Supermarket can run the edition. The
// server and multi-tenant editions are planned (PLAN.md, Phases 9–14) and
// come in steps; until they're built, only the settings are checked.
func (c *Config) Ready() error {
if c.Edition == Local {
return nil
}
return fmt.Errorf("This version of Supermarket runs only the local edition: the %s edition isn't built yet. Its settings are fine", c.Edition.Name())
}
// Item is one line of the settings, to show.
type Item struct {
Name, Value, Help string
}
// Summary describes the settings for Settings → About and `supermarket
// config`, without passwords or keys.
func (c *Config) Summary() []Item {
items := []Item{
{"Edition", c.Edition.Name(), editionHelp[c.Edition]},
{"Address", c.PublicURL, "Where people open Supermarket (" + EnvPublicURL + ")."},
}
switch {
case c.DatabaseURL == "" && c.Edition == Local:
items = append(items, Item{"Database", "SQLite: " + filepath.Join(c.HostData, "app.db"), "One file in the data folder."})
case c.DatabaseURL == "":
items = append(items, Item{"Database", "Not set", EnvDatabaseURL + "."})
default:
items = append(items, Item{"Database", "Postgres: " + RedactURL(c.DatabaseURL), EnvDatabaseURL + "."})
}
files := Item{"Files", c.Storage.String(), "Exports and uploaded files (" + EnvStorage + ")."}
if !c.Storage.S3() && c.Storage.Dir == filepath.Join(c.DataDir, "files") {
files.Value = filepath.Join(c.HostData, "files")
files.Help = "Exports and uploaded files, in the data folder."
}
items = append(items, files)
switch {
case c.Edition == Local:
items = append(items, Item{"Secrets", filepath.Join(c.HostData, "secrets.json"), "Readable only by you; never in backups unless you ask."})
case c.SecretKey != nil:
help := "With the key in " + EnvSecretKey + "."
if c.OldKey != nil {
help = "Moving from the key in " + EnvOldKey + " to the one in " + EnvSecretKey + ": unset " + EnvOldKey + " once Supermarket has started."
}
items = append(items, Item{"Secrets", "Encrypted in the database", help})
}
if c.Mail != nil {
items = append(items, Item{"Mail", c.Mail.From + " through " + c.Mail.Host, "The app's own mail: invitations and password resets (" + EnvMailURL + ")."})
} else if c.Edition == Local {
items = append(items, Item{"Mail", "Not needed", "The local edition sends no mail of its own; outreach uses Settings → Email."})
}
return items
}
var editionHelp = map[Edition]string{
Local: "One person, on this computer, with no sign-in: only this computer can reach it.",
Server: "One team, on a server, signing in.",
Multi: "Many teams at one address, each working on its own domain.",
}
// RedactURL hides a URL's password.
func RedactURL(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return "(unreadable)"
}
return u.Redacted()
}