1 parent
18b6dfbdf7
commit
dd04bdb49e
83 files changed
+4547
-583
No files matched your search
+54
-20
@@ -30,11 +30,11 @@ type PublicIssue struct {
|
||||
}
|
||||
|
||||
type ConfigStatus struct {
|
||||
SetupState SetupState
|
||||
ActiveGeneration uint64
|
||||
LastValidAt *time.Time
|
||||
PendingRestart []ServiceName
|
||||
DegradedReasons []PublicIssue
|
||||
SetupState SetupState `json:"setupState"`
|
||||
ActiveGeneration uint64 `json:"activeGeneration"`
|
||||
LastValidAt *time.Time `json:"lastValidAt,omitempty"`
|
||||
PendingRestart []ServiceName `json:"pendingRestart,omitempty"`
|
||||
DegradedReasons []PublicIssue `json:"degradedReasons,omitempty"`
|
||||
}
|
||||
|
||||
type ValidateRequest struct {
|
||||
@@ -67,9 +67,9 @@ type StepUpConfirmation struct {
|
||||
}
|
||||
|
||||
type ValidationResult struct {
|
||||
Valid bool
|
||||
Generation uint64
|
||||
Issues []PublicIssue
|
||||
Valid bool `json:"valid"`
|
||||
Generation uint64 `json:"generation"`
|
||||
Issues []PublicIssue `json:"issues,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateResult struct {
|
||||
@@ -85,10 +85,10 @@ type ApplyResult struct {
|
||||
}
|
||||
|
||||
type RollbackPreview struct {
|
||||
CurrentGeneration uint64
|
||||
TargetGeneration uint64
|
||||
CandidateGeneration uint64
|
||||
ChangedSections []Section
|
||||
CurrentGeneration uint64 `json:"currentGeneration"`
|
||||
TargetGeneration uint64 `json:"targetGeneration"`
|
||||
CandidateGeneration uint64 `json:"candidateGeneration"`
|
||||
ChangedSections []Section `json:"changedSections"`
|
||||
}
|
||||
|
||||
type rollbackTicket struct {
|
||||
@@ -624,25 +624,31 @@ func applySectionPayload(current RuntimeConfig, section Section, payload json.Ra
|
||||
candidate := cloneRuntimeConfig(current)
|
||||
switch section {
|
||||
case SectionRoot:
|
||||
var value RootConfig
|
||||
var value struct {
|
||||
RootConfig
|
||||
DatabasePasswordStatus json.RawMessage `json:"databasePasswordStatus"`
|
||||
}
|
||||
if err := ParseStrict(payload, &value); err != nil {
|
||||
return RuntimeConfig{}, err
|
||||
}
|
||||
if value.Database.Password.Configured() {
|
||||
if value.RootConfig.Database.Password.Configured() {
|
||||
return RuntimeConfig{}, ErrInvalidSecretChange
|
||||
}
|
||||
value.Database.Password = current.Root.Database.Password
|
||||
candidate.Root = normalizeRootConfig(value)
|
||||
value.RootConfig.Database.Password = current.Root.Database.Password
|
||||
candidate.Root = normalizeRootConfig(value.RootConfig)
|
||||
case SectionSMTP:
|
||||
var value SMTPSectionConfig
|
||||
var value struct {
|
||||
SMTPSectionConfig
|
||||
RelayPasswordStatus json.RawMessage `json:"relayPasswordStatus"`
|
||||
}
|
||||
if err := ParseStrict(payload, &value); err != nil {
|
||||
return RuntimeConfig{}, err
|
||||
}
|
||||
if value.Relay.Password.Configured() {
|
||||
if value.SMTPSectionConfig.Relay.Password.Configured() {
|
||||
return RuntimeConfig{}, ErrInvalidSecretChange
|
||||
}
|
||||
value.Relay.Password = current.SMTP.Relay.Password
|
||||
candidate.SMTP = value
|
||||
value.SMTPSectionConfig.Relay.Password = current.SMTP.Relay.Password
|
||||
candidate.SMTP = value.SMTPSectionConfig
|
||||
case SectionEmail:
|
||||
var value EmailSectionConfig
|
||||
if err := ParseStrict(payload, &value); err != nil {
|
||||
@@ -660,6 +666,15 @@ func applySectionPayload(current RuntimeConfig, section Section, payload json.Ra
|
||||
if err := ParseStrict(payload, &value); err != nil {
|
||||
return RuntimeConfig{}, err
|
||||
}
|
||||
for logicalID, plugin := range value.Plugins {
|
||||
if storedSecretHasMaterial(plugin.Secret) {
|
||||
return RuntimeConfig{}, ErrInvalidSecretChange
|
||||
}
|
||||
if currentPlugin, ok := current.Plugins.Plugins[logicalID]; ok {
|
||||
plugin.Secret = currentPlugin.Secret
|
||||
value.Plugins[logicalID] = plugin
|
||||
}
|
||||
}
|
||||
candidate.Plugins = value
|
||||
default:
|
||||
return RuntimeConfig{}, ErrInvalidSection
|
||||
@@ -727,6 +742,21 @@ func applySecretChanges(candidate *RuntimeConfig, section Section, changes map[s
|
||||
return err
|
||||
}
|
||||
candidate.SMTP.Relay.Password = stored
|
||||
case section == SectionPlugins && strings.HasPrefix(name, "plugins.") && strings.HasSuffix(name, ".secret"):
|
||||
logicalID := strings.TrimSuffix(strings.TrimPrefix(name, "plugins."), ".secret")
|
||||
if !logicalIDPattern.MatchString(logicalID) {
|
||||
return ErrInvalidSecretChange
|
||||
}
|
||||
plugin, ok := candidate.Plugins.Plugins[logicalID]
|
||||
if !ok {
|
||||
return ErrInvalidSecretChange
|
||||
}
|
||||
stored, err := ApplySecretChange(vault, plugin.Secret, change, SecretPolicy{AllowClear: true, MaxLength: 4096}, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
plugin.Secret = stored
|
||||
candidate.Plugins.Plugins[logicalID] = plugin
|
||||
default:
|
||||
return ErrInvalidSecretChange
|
||||
}
|
||||
@@ -734,6 +764,10 @@ func applySecretChanges(candidate *RuntimeConfig, section Section, changes map[s
|
||||
return nil
|
||||
}
|
||||
|
||||
func storedSecretHasMaterial(secret StoredSecret) bool {
|
||||
return secret.Ciphertext != "" || secret.Version != 0 || !secret.UpdatedAt.IsZero()
|
||||
}
|
||||
|
||||
func requiresSecretStepUp(changes map[string]SecretChange) bool {
|
||||
for _, change := range changes {
|
||||
if change.Operation == SecretClear || change.Operation == SecretReplace {
|
||||
|
||||
@@ -476,6 +476,158 @@ func TestConfigManagerSecretChangesUseVaultAndRejectUnknownFields(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigManagerPluginSecretChangesUseUnifiedVaultSemantics(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
runtime := validRuntimeConfig()
|
||||
writeRuntimeFixture(t, root, runtime)
|
||||
options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}
|
||||
manager, err := NewConfigManager(root, options)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
plugins := manager.Snapshot().Plugins
|
||||
plugin := plugins.Plugins["telegram_push"]
|
||||
plugin.Secret = StoredSecret{}
|
||||
plugins.Plugins["telegram_push"] = plugin
|
||||
payload, err := json.Marshal(plugins)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
replaceRequest := UpdateRequest{
|
||||
Section: SectionPlugins,
|
||||
ExpectedGeneration: 1,
|
||||
Payload: payload,
|
||||
SecretChanges: map[string]SecretChange{
|
||||
"plugins.telegram_push.secret": {Operation: SecretReplace, Value: &SecretInput{Plaintext: "plugin-secret"}},
|
||||
},
|
||||
Actor: authorizedConfigActor(),
|
||||
Confirmation: StepUpConfirmation{Confirmed: true, Method: "recent_auth"},
|
||||
}
|
||||
updated, err := manager.Update(context.Background(), replaceRequest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored := updated.Candidate.Plugins.Plugins["telegram_push"].Secret
|
||||
if !stored.Configured() || stored.Ciphertext == "plugin-secret" {
|
||||
t.Fatalf("plugin secret was not encrypted: %+v", stored)
|
||||
}
|
||||
if _, err := manager.Apply(context.Background(), updated.Generation); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
plugins = manager.Snapshot().Plugins
|
||||
plugin = plugins.Plugins["telegram_push"]
|
||||
plugin.Secret = StoredSecret{}
|
||||
plugins.Plugins["telegram_push"] = plugin
|
||||
payload, err = json.Marshal(plugins)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kept, err := manager.Update(context.Background(), UpdateRequest{
|
||||
Section: SectionPlugins,
|
||||
ExpectedGeneration: 2,
|
||||
Payload: payload,
|
||||
SecretChanges: map[string]SecretChange{"plugins.telegram_push.secret": {Operation: SecretKeep}},
|
||||
Actor: authorizedConfigActor(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if kept.Candidate.Plugins.Plugins["telegram_push"].Secret != stored {
|
||||
t.Fatalf("plugin keep changed the stored secret: got %+v want %+v", kept.Candidate.Plugins.Plugins["telegram_push"].Secret, stored)
|
||||
}
|
||||
if _, err := manager.Apply(context.Background(), kept.Generation); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
plugins = manager.Snapshot().Plugins
|
||||
plugin = plugins.Plugins["telegram_push"]
|
||||
plugin.Secret = StoredSecret{}
|
||||
plugins.Plugins["telegram_push"] = plugin
|
||||
payload, err = json.Marshal(plugins)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cleared, err := manager.Update(context.Background(), UpdateRequest{
|
||||
Section: SectionPlugins,
|
||||
ExpectedGeneration: 3,
|
||||
Payload: payload,
|
||||
SecretChanges: map[string]SecretChange{"plugins.telegram_push.secret": {Operation: SecretClear, Confirmed: true}},
|
||||
Actor: authorizedConfigActor(),
|
||||
Confirmation: StepUpConfirmation{Confirmed: true, Method: "webauthn"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cleared.Candidate.Plugins.Plugins["telegram_push"].Secret.Configured() {
|
||||
t.Fatal("plugin clear left the secret configured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigManagerRejectsInvalidPluginSecretChanges(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
runtime := validRuntimeConfig()
|
||||
writeRuntimeFixture(t, root, runtime)
|
||||
options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}
|
||||
manager, err := NewConfigManager(root, options)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
base := manager.Snapshot().Plugins
|
||||
tests := []struct {
|
||||
name string
|
||||
payload PluginsSectionConfig
|
||||
secretPath string
|
||||
}{
|
||||
{
|
||||
name: "unknown plugin",
|
||||
payload: base,
|
||||
secretPath: "plugins.unknown.secret",
|
||||
},
|
||||
{
|
||||
name: "invalid path",
|
||||
payload: base,
|
||||
secretPath: "plugins.telegram_push.secret.extra",
|
||||
},
|
||||
{
|
||||
name: "direct ciphertext",
|
||||
payload: func() PluginsSectionConfig {
|
||||
value := base
|
||||
plugin := value.Plugins["telegram_push"]
|
||||
plugin.Secret = StoredSecret{Ciphertext: "enc:v1:plaintext", Version: credential.CurrentVersion, UpdatedAt: time.Now().UTC()}
|
||||
value.Plugins["telegram_push"] = plugin
|
||||
return value
|
||||
}(),
|
||||
secretPath: "plugins.telegram_push.secret",
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
payloadValue := clonePluginsSection(test.payload)
|
||||
if test.name != "direct ciphertext" {
|
||||
plugin := payloadValue.Plugins["telegram_push"]
|
||||
plugin.Secret = StoredSecret{}
|
||||
payloadValue.Plugins["telegram_push"] = plugin
|
||||
}
|
||||
payload, err := json.Marshal(payloadValue)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = manager.Validate(context.Background(), ValidateRequest{
|
||||
Section: SectionPlugins,
|
||||
Payload: payload,
|
||||
SecretChanges: map[string]SecretChange{test.secretPath: {Operation: SecretKeep}},
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidSecretChange) {
|
||||
t.Fatalf("error = %v, want invalid secret change", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func findTransactionDirectory(t *testing.T, root string) string {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(filepath.Join(root, "config", "transaction"))
|
||||
@@ -835,3 +987,45 @@ func TestConfigManagerWritesRedactedAuditAndDegradesOnAuditFailure(t *testing.T)
|
||||
t.Fatalf("status after audit failure = %+v, want degraded", manager.Status())
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigManagerSnapshotResultsAreIndependentCopies(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
writeRuntimeFixture(t, root, validRuntimeConfig())
|
||||
manager, err := NewConfigManager(root, ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
current := manager.Snapshot()
|
||||
current.Root.Domains.Accepted[0] = "changed.example.com"
|
||||
current.Plugins.Plugins["telegram_push"].Settings[0] = '['
|
||||
if got := manager.Snapshot(); got.Root.Domains.Accepted[0] != "mail.example.com" || !json.Valid(got.Plugins.Plugins["telegram_push"].Settings) {
|
||||
t.Fatal("manager snapshot exposed active mutable data")
|
||||
}
|
||||
|
||||
email := manager.Snapshot().Email
|
||||
email.Policy.MaxMessageBytes = 8 << 20
|
||||
payload, err := json.Marshal(email)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated, err := manager.Update(context.Background(), UpdateRequest{
|
||||
Section: SectionEmail, ExpectedGeneration: 1, Payload: payload, Actor: authorizedConfigActor(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated.Candidate.Email.Policy.MaxMessageBytes = 64 << 20
|
||||
if got := manager.Snapshot(); got.Email.Policy.MaxMessageBytes == 64<<20 {
|
||||
t.Fatal("update result exposed manager-owned pending data")
|
||||
}
|
||||
|
||||
applied, err := manager.Apply(context.Background(), updated.Generation)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
applied.Snapshot.Email.Policy.MaxMessageBytes = 128 << 20
|
||||
if got := manager.Snapshot(); got.Email.Policy.MaxMessageBytes == 128<<20 {
|
||||
t.Fatal("apply result exposed manager-owned active data")
|
||||
}
|
||||
}
|
||||
@@ -62,3 +62,22 @@ func TestParseStrictAcceptsExactNestedFields(t *testing.T) {
|
||||
t.Fatalf("target = %+v", target)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseStrictDoesNotLeakSecretOrAbsolutePath(t *testing.T) {
|
||||
secret := "super-secret-value"
|
||||
absolutePath := `C:\private\smail\config.json`
|
||||
tests := [][]byte{
|
||||
[]byte(`{"password":"` + secret + `"}`),
|
||||
[]byte(`{"absolutePath":"` + absolutePath + `"}`),
|
||||
}
|
||||
for _, data := range tests {
|
||||
var target strictParserFixture
|
||||
err := ParseStrict(data, &target)
|
||||
if err == nil {
|
||||
t.Fatal("unsafe configuration was accepted")
|
||||
}
|
||||
if strings.Contains(err.Error(), secret) || strings.Contains(err.Error(), absolutePath) {
|
||||
t.Fatalf("error leaked sensitive value: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ func ValidateRuntimeConfig(runtime RuntimeConfig, options RuntimeValidationOptio
|
||||
return err
|
||||
}
|
||||
if runtime.SetupState == SetupStateReady {
|
||||
if !options.HasSuperAdmin || runtime.Root.Domains.Primary == "" || len(runtime.Root.Domains.Accepted) == 0 || !runtime.Root.Database.IsStructured() {
|
||||
if !options.HasSuperAdmin || runtime.Root.Domains.Primary == "" || len(runtime.Root.Domains.Accepted) == 0 || runtime.Root.Domains.Web == "" || !runtime.Root.Database.IsStructured() {
|
||||
return ErrInvalidRuntimeConfig
|
||||
}
|
||||
if runtime.Email.Policy.SMTPPort == 0 || runtime.Email.Policy.IMAPPort == 0 || runtime.Email.Policy.POP3Port == 0 {
|
||||
@@ -184,6 +184,9 @@ func validatePluginSection(section PluginsSectionConfig) error {
|
||||
if len(plugin.Settings) > maxPluginSettingsBytes || !validPluginSettings(plugin.Settings) {
|
||||
return ErrInvalidPlugin
|
||||
}
|
||||
if err := ValidateStoredSecret(plugin.Secret, false); err != nil {
|
||||
return ErrInvalidPlugin
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -230,7 +233,13 @@ func pluginList(section PluginsSectionConfig) []PluginConfig {
|
||||
for _, target := range plugin.Permissions.Network {
|
||||
targets = append(targets, target.Host)
|
||||
}
|
||||
result = append(result, PluginConfig{LogicalID: logicalID, FileName: plugin.Executable, Enabled: plugin.Enabled, NetworkAllowlist: targets})
|
||||
result = append(result, PluginConfig{
|
||||
LogicalID: logicalID,
|
||||
FileName: plugin.Executable,
|
||||
Enabled: plugin.Enabled,
|
||||
NetworkAllowlist: targets,
|
||||
Secret: plugin.Secret,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -76,6 +76,7 @@ type PluginInstance struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Executable string `json:"executable"`
|
||||
Permissions PluginPermissions `json:"permissions"`
|
||||
Secret StoredSecret `json:"secret,omitempty"`
|
||||
Settings json.RawMessage `json:"settings,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -28,8 +28,15 @@ func (s *SnapshotStore) Publish(candidate RuntimeConfig) error {
|
||||
if err := ValidateRuntimeConfig(candidate, s.options); err != nil {
|
||||
return err
|
||||
}
|
||||
s.current.Store(&candidate)
|
||||
return nil
|
||||
for {
|
||||
current := s.current.Load()
|
||||
if current != nil && candidate.Generation < current.Generation {
|
||||
return ErrGenerationConflict
|
||||
}
|
||||
if s.current.CompareAndSwap(current, &candidate) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SnapshotStore) Snapshot() (RuntimeConfig, error) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -147,3 +148,84 @@ func TestSnapshotStorePreservesOldSnapshotLifecycle(t *testing.T) {
|
||||
t.Fatal("publishing a new snapshot modified an old reader copy")
|
||||
}
|
||||
}
|
||||
func TestSnapshotStoreRejectsOlderGeneration(t *testing.T) {
|
||||
store, err := NewSnapshotStore(validRuntimeConfig(), RuntimeValidationOptions{HasSuperAdmin: true, Production: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
newer := validRuntimeConfig()
|
||||
newer.Generation = 3
|
||||
newer.Root.Generation = 3
|
||||
newer.Root.Sections = validSectionReferences(3)
|
||||
newer.SMTP.Meta.Generation = 3
|
||||
newer.Email.Meta.Generation = 3
|
||||
newer.SSL.Meta.Generation = 3
|
||||
newer.Plugins.Meta.Generation = 3
|
||||
if err := store.Publish(newer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
older := validRuntimeConfig()
|
||||
older.Generation = 2
|
||||
older.Root.Generation = 2
|
||||
older.Root.Sections = validSectionReferences(2)
|
||||
older.SMTP.Meta.Generation = 2
|
||||
older.Email.Meta.Generation = 2
|
||||
older.SSL.Meta.Generation = 2
|
||||
older.Plugins.Meta.Generation = 2
|
||||
if err := store.Publish(older); !errors.Is(err, ErrGenerationConflict) {
|
||||
t.Fatalf("older publication error = %v, want generation conflict", err)
|
||||
}
|
||||
if got := store.Generation(); got != 3 {
|
||||
t.Fatalf("active generation = %d, want 3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotStoreConcurrentOlderPublishesKeepNewestGeneration(t *testing.T) {
|
||||
store, err := NewSnapshotStore(validRuntimeConfig(), RuntimeValidationOptions{HasSuperAdmin: true, Production: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
newer := validRuntimeConfig()
|
||||
newer.Generation = 3
|
||||
newer.Root.Generation = 3
|
||||
newer.Root.Sections = validSectionReferences(3)
|
||||
newer.SMTP.Meta.Generation = 3
|
||||
newer.Email.Meta.Generation = 3
|
||||
newer.SSL.Meta.Generation = 3
|
||||
newer.Plugins.Meta.Generation = 3
|
||||
if err := store.Publish(newer); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
const publishers = 32
|
||||
var group sync.WaitGroup
|
||||
errorsFound := make(chan error, publishers)
|
||||
for index := 0; index < publishers; index++ {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
older := validRuntimeConfig()
|
||||
older.Generation = 2
|
||||
older.Root.Generation = 2
|
||||
older.Root.Sections = validSectionReferences(2)
|
||||
older.SMTP.Meta.Generation = 2
|
||||
older.Email.Meta.Generation = 2
|
||||
older.SSL.Meta.Generation = 2
|
||||
older.Plugins.Meta.Generation = 2
|
||||
if err := store.Publish(older); !errors.Is(err, ErrGenerationConflict) {
|
||||
errorsFound <- err
|
||||
}
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
close(errorsFound)
|
||||
for err := range errorsFound {
|
||||
t.Fatalf("older concurrent publication error = %v", err)
|
||||
}
|
||||
if got := store.Generation(); got != 3 {
|
||||
t.Fatalf("active generation = %d, want 3", got)
|
||||
}
|
||||
}
|
||||
+177
-5
@@ -3,6 +3,7 @@ package config
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
@@ -14,6 +15,9 @@ var (
|
||||
ErrInvalidSMTP = errors.New("invalid SMTP configuration")
|
||||
ErrInvalidSSL = errors.New("invalid SSL configuration")
|
||||
ErrInvalidPlugin = errors.New("invalid plugin configuration")
|
||||
ErrInvalidHTTP = errors.New("invalid HTTP configuration")
|
||||
ErrInvalidEmail = errors.New("invalid email configuration")
|
||||
ErrInvalidLogLevel = errors.New("invalid log level")
|
||||
)
|
||||
|
||||
var logicalIDPattern = regexp.MustCompile(`^[a-z][a-z0-9_-]{1,63}$`)
|
||||
@@ -23,6 +27,9 @@ func ValidateRootConfig(root RootConfig) error {
|
||||
if root.ConfigVersion > CurrentConfigVersion || root.SchemaVersion <= 0 || root.SchemaVersion > CurrentSchemaVersion || root.Generation == 0 || !root.SetupState.Valid() {
|
||||
return ErrInvalidSetupState
|
||||
}
|
||||
if !validLogLevel(root.LogLevel) {
|
||||
return ErrInvalidLogLevel
|
||||
}
|
||||
if len(root.Sections) > 0 {
|
||||
if err := ValidateSectionReferences(root.Sections, root.Generation); err != nil {
|
||||
return err
|
||||
@@ -37,6 +44,12 @@ func ValidateRootConfig(root RootConfig) error {
|
||||
if err := validateSSL(root.SSL); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateHTTP(root.HTTP); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateEmail(root.Email); err != nil {
|
||||
return err
|
||||
}
|
||||
seen := make(map[string]struct{}, len(root.Plugins))
|
||||
for _, plugin := range root.Plugins {
|
||||
if err := validatePlugin(plugin); err != nil {
|
||||
@@ -76,7 +89,7 @@ func validateDatabase(database DatabaseConfig) error {
|
||||
if err := ValidateStoredSecret(database.Password, true); err != nil {
|
||||
return ErrInvalidDatabase
|
||||
}
|
||||
if net.ParseIP(database.Host) == nil && strings.ContainsAny(database.Host, "/\\ ") {
|
||||
if net.ParseIP(database.Host) == nil && strings.ContainsAny(database.Host, `/\\ `) {
|
||||
return ErrInvalidDatabase
|
||||
}
|
||||
default:
|
||||
@@ -86,10 +99,47 @@ func validateDatabase(database DatabaseConfig) error {
|
||||
}
|
||||
|
||||
func validateSMTP(smtp SMTPConfig) error {
|
||||
if !validLoginVerificationPolicy(smtp.LoginPolicy) {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
if !smtp.VerificationEnabled {
|
||||
if smtp.RelayHost != "" && !validSMTPHost(smtp.RelayHost) {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
if smtp.RelayPort != 0 && !validPort(smtp.RelayPort) {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
if smtp.FromDomain != "" && !validCanonicalDomain(smtp.FromDomain) {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
if strings.TrimSpace(smtp.Username) != smtp.Username {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
if err := ValidateStoredSecret(smtp.Password, false); err != nil {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
if smtp.Username != "" {
|
||||
if err := ValidateStoredSecret(smtp.Password, true); err != nil {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
}
|
||||
if smtp.Security != "" {
|
||||
switch smtp.Security {
|
||||
case "starttls", "implicit_tls", "tls":
|
||||
case "plain":
|
||||
if !isLocalSMTPHost(smtp.RelayHost) {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
default:
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if smtp.RelayHost == "" || !validPort(smtp.RelayPort) || smtp.FromDomain == "" {
|
||||
if !validSMTPHost(smtp.RelayHost) || !validPort(smtp.RelayPort) || !validCanonicalDomain(smtp.FromDomain) {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
if strings.TrimSpace(smtp.Username) != smtp.Username {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
if smtp.Username == "" {
|
||||
@@ -100,7 +150,11 @@ func validateSMTP(smtp SMTPConfig) error {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
switch smtp.Security {
|
||||
case "starttls", "implicit_tls", "plain":
|
||||
case "starttls", "implicit_tls", "tls":
|
||||
case "plain":
|
||||
if !isLocalSMTPHost(smtp.RelayHost) {
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
default:
|
||||
return ErrInvalidSMTP
|
||||
}
|
||||
@@ -108,21 +162,79 @@ func validateSMTP(smtp SMTPConfig) error {
|
||||
}
|
||||
|
||||
func validateSSL(ssl SSLConfig) error {
|
||||
if !isControlledRelativePath(ssl.DefaultDirectory) {
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
activeDirectory := ssl.DefaultDirectory
|
||||
switch ssl.Mode {
|
||||
case "default":
|
||||
if ssl.DefaultDirectory == "" {
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
case "custom":
|
||||
if ssl.CustomDirectory == "" || filepath.IsAbs(ssl.CustomDirectory) {
|
||||
if !isControlledRelativePath(ssl.CustomDirectory) || ssl.CustomDirectory == "" {
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
activeDirectory = ssl.CustomDirectory
|
||||
default:
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
if (ssl.CertificateRef != "" && !isControlledRelativePath(ssl.CertificateRef)) ||
|
||||
(ssl.PrivateKeyRef != "" && !isControlledRelativePath(ssl.PrivateKeyRef)) {
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
if (ssl.CertificateRef == "") != (ssl.PrivateKeyRef == "") {
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
if ssl.CertificateRef != "" && (!isPathWithinDirectory(ssl.CertificateRef, activeDirectory) || !isPathWithinDirectory(ssl.PrivateKeyRef, activeDirectory)) {
|
||||
return ErrInvalidSSL
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateHTTP(http HTTPConfig) error {
|
||||
if http.Port != 0 && !validPort(http.Port) {
|
||||
return ErrInvalidHTTP
|
||||
}
|
||||
if http.HTTPSPort != 0 && !validPort(http.HTTPSPort) {
|
||||
return ErrInvalidHTTP
|
||||
}
|
||||
if http.HTTPSEnabled && http.HTTPSPort == 0 {
|
||||
return ErrInvalidHTTP
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateEmail(email EmailConfig) error {
|
||||
for _, port := range []int{email.SMTPPort, email.IMAPPort, email.POP3Port} {
|
||||
if port != 0 && !validPort(port) {
|
||||
return ErrInvalidEmail
|
||||
}
|
||||
}
|
||||
if email.MaxMessageBytes < 0 || email.SpamFilterLevel < 0 || email.SpamFilterLevel > 3 || !validLoginVerificationPolicy(email.LoginVerificationPolicy) {
|
||||
return ErrInvalidEmail
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isControlledRelativePath(value string) bool {
|
||||
if value == "" || path.IsAbs(value) || filepath.IsAbs(value) || isWindowsAbsolute(value) || strings.ContainsAny(value, `\\:`) {
|
||||
return false
|
||||
}
|
||||
cleaned := path.Clean(value)
|
||||
if cleaned != value || cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, "../") {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func isPathWithinDirectory(value, directory string) bool {
|
||||
if !isControlledRelativePath(value) || !isControlledRelativePath(directory) {
|
||||
return false
|
||||
}
|
||||
return value != directory && strings.HasPrefix(value, directory+"/")
|
||||
}
|
||||
|
||||
func validatePlugin(plugin PluginConfig) error {
|
||||
if !logicalIDPattern.MatchString(plugin.LogicalID) || filepath.Base(plugin.FileName) != plugin.FileName || plugin.FileName == "" {
|
||||
return ErrInvalidPlugin
|
||||
@@ -130,12 +242,72 @@ func validatePlugin(plugin PluginConfig) error {
|
||||
if err := ValidateStoredSecret(plugin.Secret, false); err != nil {
|
||||
return ErrInvalidPlugin
|
||||
}
|
||||
seenHosts := make(map[string]struct{}, len(plugin.NetworkAllowlist))
|
||||
for _, host := range plugin.NetworkAllowlist {
|
||||
if strings.TrimSpace(host) == "" || strings.ContainsAny(host, "/\\") {
|
||||
normalized, ok := normalizeSMTPHost(host)
|
||||
if !ok || net.ParseIP(normalized) != nil {
|
||||
return ErrInvalidPlugin
|
||||
}
|
||||
if _, exists := seenHosts[normalized]; exists {
|
||||
return ErrInvalidPlugin
|
||||
}
|
||||
seenHosts[normalized] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validLogLevel(value string) bool {
|
||||
switch value {
|
||||
case "", "debug", "info", "warn", "error":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func validLoginVerificationPolicy(value string) bool {
|
||||
switch value {
|
||||
case "", "off", "always", "new_device":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func validCanonicalDomain(value string) bool {
|
||||
normalized, err := normalizeConfigDomain(value)
|
||||
return err == nil && normalized == value
|
||||
}
|
||||
|
||||
func validSMTPHost(value string) bool {
|
||||
_, ok := normalizeSMTPHost(value)
|
||||
return ok
|
||||
}
|
||||
|
||||
func normalizeSMTPHost(value string) (string, bool) {
|
||||
if value == "" || strings.TrimSpace(value) != value || strings.ContainsAny(value, "@/\\\r\n\t ") {
|
||||
return "", false
|
||||
}
|
||||
if parsed := net.ParseIP(value); parsed != nil {
|
||||
return parsed.String(), true
|
||||
}
|
||||
normalized, err := normalizeConfigDomain(value)
|
||||
if err != nil || normalized != value {
|
||||
return "", false
|
||||
}
|
||||
return normalized, true
|
||||
}
|
||||
|
||||
func isLocalSMTPHost(value string) bool {
|
||||
normalized, ok := normalizeSMTPHost(value)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if normalized == "localhost" {
|
||||
return true
|
||||
}
|
||||
parsed := net.ParseIP(normalized)
|
||||
return parsed != nil && parsed.IsLoopback()
|
||||
}
|
||||
|
||||
func validPort(port int) bool { return port > 0 && port <= 65535 }
|
||||
@@ -0,0 +1,249 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateRootConfigRejectsUnsafeValues(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*RootConfig)
|
||||
want error
|
||||
}{
|
||||
{
|
||||
name: "invalid_log_level",
|
||||
mutate: func(root *RootConfig) {
|
||||
root.LogLevel = "trace"
|
||||
},
|
||||
want: ErrInvalidLogLevel,
|
||||
},
|
||||
{
|
||||
name: "invalid_http_port",
|
||||
mutate: func(root *RootConfig) {
|
||||
root.HTTP.Port = 70000
|
||||
},
|
||||
want: ErrInvalidHTTP,
|
||||
},
|
||||
{
|
||||
name: "https_requires_port",
|
||||
mutate: func(root *RootConfig) {
|
||||
root.HTTP.HTTPSEnabled = true
|
||||
root.HTTP.HTTPSPort = 0
|
||||
},
|
||||
want: ErrInvalidHTTP,
|
||||
},
|
||||
{
|
||||
name: "invalid_email_policy",
|
||||
mutate: func(root *RootConfig) {
|
||||
root.Email.LoginVerificationPolicy = "sometimes"
|
||||
},
|
||||
want: ErrInvalidEmail,
|
||||
},
|
||||
{
|
||||
name: "invalid_smtp_host",
|
||||
mutate: func(root *RootConfig) {
|
||||
root.SMTP = SMTPConfig{
|
||||
RelayHost: "smtp.example.com/relay",
|
||||
RelayPort: 587,
|
||||
Security: "starttls",
|
||||
FromDomain: "mail.example.com",
|
||||
VerificationEnabled: true,
|
||||
}
|
||||
},
|
||||
want: ErrInvalidSMTP,
|
||||
},
|
||||
{
|
||||
name: "remote_plain_smtp_relay",
|
||||
mutate: func(root *RootConfig) {
|
||||
root.SMTP = SMTPConfig{
|
||||
RelayHost: "smtp.example.com",
|
||||
RelayPort: 25,
|
||||
Security: "plain",
|
||||
FromDomain: "mail.example.com",
|
||||
VerificationEnabled: true,
|
||||
}
|
||||
},
|
||||
want: ErrInvalidSMTP,
|
||||
},
|
||||
{
|
||||
name: "inconsistent_disabled_smtp_secret",
|
||||
mutate: func(root *RootConfig) {
|
||||
root.SMTP.Password = StoredSecret{Ciphertext: "ENC[v1]invalid", Version: 1}
|
||||
},
|
||||
want: ErrInvalidSMTP,
|
||||
},
|
||||
{
|
||||
name: "ssl_path_escape",
|
||||
mutate: func(root *RootConfig) {
|
||||
root.SSL.CertificateRef = "config/ssl/../outside.pem"
|
||||
root.SSL.PrivateKeyRef = "config/ssl/key.pem"
|
||||
},
|
||||
want: ErrInvalidSSL,
|
||||
},
|
||||
{
|
||||
name: "ssl_certificate_key_mismatch",
|
||||
mutate: func(root *RootConfig) {
|
||||
root.SSL.CertificateRef = "config/ssl/certificate.pem"
|
||||
},
|
||||
want: ErrInvalidSSL,
|
||||
},
|
||||
{
|
||||
name: "duplicate_plugin_allowlist_target",
|
||||
mutate: func(root *RootConfig) {
|
||||
root.Plugins = []PluginConfig{{
|
||||
LogicalID: "telegram_push",
|
||||
FileName: "telegram_push",
|
||||
NetworkAllowlist: []string{"api.example.com", "api.example.com"},
|
||||
}}
|
||||
},
|
||||
want: ErrInvalidPlugin,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
root := testRootConfig()
|
||||
test.mutate(&root)
|
||||
if err := ValidateRootConfig(root); !errors.Is(err, test.want) {
|
||||
t.Fatalf("error = %v, want %v", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRuntimeConfigRejectsUnsafeCrossSectionValues(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*RuntimeConfig)
|
||||
want error
|
||||
}{
|
||||
{
|
||||
name: "duplicate_accepted_domain",
|
||||
mutate: func(runtime *RuntimeConfig) {
|
||||
runtime.Root.Domains.Accepted = []string{"mail.example.com", "mail.example.com"}
|
||||
},
|
||||
want: ErrInvalidDomainConfig,
|
||||
},
|
||||
{
|
||||
name: "ready_requires_web_domain",
|
||||
mutate: func(runtime *RuntimeConfig) {
|
||||
runtime.Root.Domains.Web = ""
|
||||
},
|
||||
want: ErrInvalidDomainConfig,
|
||||
},
|
||||
{
|
||||
name: "duplicate_plugin_network_target",
|
||||
mutate: func(runtime *RuntimeConfig) {
|
||||
plugin := runtime.Plugins.Plugins["telegram_push"]
|
||||
plugin.Permissions.Network = append(plugin.Permissions.Network, plugin.Permissions.Network[0])
|
||||
runtime.Plugins.Plugins["telegram_push"] = plugin
|
||||
},
|
||||
want: ErrInvalidPlugin,
|
||||
},
|
||||
{
|
||||
name: "plugin_network_ip_target",
|
||||
mutate: func(runtime *RuntimeConfig) {
|
||||
plugin := runtime.Plugins.Plugins["telegram_push"]
|
||||
plugin.Permissions.Network[0].Host = "127.0.0.1"
|
||||
runtime.Plugins.Plugins["telegram_push"] = plugin
|
||||
},
|
||||
want: ErrInvalidPlugin,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
runtime := validRuntimeConfig()
|
||||
test.mutate(&runtime)
|
||||
if err := ValidateRuntimeConfig(runtime, RuntimeValidationOptions{HasSuperAdmin: true, Production: true}); !errors.Is(err, test.want) {
|
||||
t.Fatalf("error = %v, want %v", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotStoreRejectsInvalidCandidateWithoutChangingSnapshot(t *testing.T) {
|
||||
initial := validRuntimeConfig()
|
||||
store, err := NewSnapshotStore(initial, RuntimeValidationOptions{HasSuperAdmin: true, Production: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := store.Snapshot()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
invalid := cloneRuntimeConfig(initial)
|
||||
invalid.Email.Policy.IMAPPort = invalid.Root.HTTP.HTTPSPort
|
||||
if err := store.Publish(invalid); !errors.Is(err, ErrPortConflict) {
|
||||
t.Fatalf("publish error = %v, want %v", err, ErrPortConflict)
|
||||
}
|
||||
if store.Generation() != before.Generation {
|
||||
t.Fatalf("generation = %d, want %d", store.Generation(), before.Generation)
|
||||
}
|
||||
after, err := store.Snapshot()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.Email.Policy.IMAPPort != before.Email.Policy.IMAPPort {
|
||||
t.Fatalf("snapshot changed after rejection: before=%d after=%d", before.Email.Policy.IMAPPort, after.Email.Policy.IMAPPort)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigManagerRejectsInvalidUpdateWithoutDiskOrStatusMutation(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
writeRuntimeFixture(t, root, validRuntimeConfig())
|
||||
options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}
|
||||
manager, err := NewConfigManager(root, options)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
beforeFiles := make(map[string][]byte)
|
||||
for _, name := range []string{"config.json", "smtp.json", "email.json", "ssl.json", "plugins.json"} {
|
||||
data, readErr := os.ReadFile(filepath.Join(root, "config", name))
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
beforeFiles[name] = data
|
||||
}
|
||||
beforeStatus := manager.Status()
|
||||
current := manager.Snapshot()
|
||||
invalidEmail := current.Email
|
||||
invalidEmail.Policy.IMAPPort = current.Root.HTTP.HTTPSPort
|
||||
payload, err := json.Marshal(invalidEmail)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := manager.Update(context.Background(), UpdateRequest{
|
||||
Section: SectionEmail,
|
||||
ExpectedGeneration: current.Generation,
|
||||
Payload: payload,
|
||||
Actor: authorizedConfigActor(),
|
||||
}); !errors.Is(err, ErrPortConflict) {
|
||||
t.Fatalf("update error = %v, want %v", err, ErrPortConflict)
|
||||
}
|
||||
|
||||
if got := manager.Snapshot().Generation; got != beforeStatus.ActiveGeneration {
|
||||
t.Fatalf("active generation = %d, want %d", got, beforeStatus.ActiveGeneration)
|
||||
}
|
||||
afterStatus := manager.Status()
|
||||
if afterStatus.ActiveGeneration != beforeStatus.ActiveGeneration || len(afterStatus.PendingRestart) != 0 {
|
||||
t.Fatalf("status changed after rejected update: before=%+v after=%+v", beforeStatus, afterStatus)
|
||||
}
|
||||
for name, before := range beforeFiles {
|
||||
after, readErr := os.ReadFile(filepath.Join(root, "config", name))
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if !bytes.Equal(after, before) {
|
||||
t.Fatalf("configuration file %s changed after rejected update", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user