diff --git a/README.md b/README.md
index 72d8a58a6..889019e4f 100644
--- a/README.md
+++ b/README.md
@@ -103,9 +103,11 @@ environments:
Omit `-e` / `--env` to target `environments.local`. Use `-e staging` (or another name) to target a different environment.
+`shopware-cli project create` and `shopware-cli project config init` write `environments.local`. Top-level `url` and `admin_api` are deprecated: they are used only when `environments.local` is absent. When both are present, `environments.local` wins.
+
### Anonymized dumps and extensions
-`shopware-cli project dump --anonymize` rewrites personal data in Shopware core tables. An extension can add its own tables and system config secrets in `.config/shopware-extension.yml`. A project dump with `--anonymize` merges those rules from every installed extension. A column already set under `dump.rewrite` in the project config is left unchanged.
+`shopware-cli project dump --anonymize` rewrites personal data in Shopware core tables. An extension can add its own tables and system config secrets in `.config/shopware-extension.yml`. A project dump with `--anonymize` merges those rules from every installed extension. A column already set under `dump.rewrite` in the project config, or by the built-in rules, is left unchanged. If an extension config cannot be read, the dump stops with an error instead of skipping that extension.
```yaml
anonymize:
@@ -121,9 +123,7 @@ anonymize:
value: sandbox
```
-`tables` uses the same column expressions as the project `dump.rewrite` map. Write `"''"` to store an empty string and `"NULL"` to store NULL. `system_config` matches `system_config.configuration_key`. A plain key omits that row from the dump. `value` replaces `configuration_value` with `{"_value": value}`. A value that starts with `faker.` is generated per row.
-
-`shopware-cli project create` and `shopware-cli project config init` write `environments.local`. Top-level `url` and `admin_api` are deprecated: they are used only when `environments.local` is absent. When both are present, `environments.local` wins.
+`tables` uses the same column expressions as the project `dump.rewrite` map. Write `"''"` to store an empty string and `"NULL"` to store NULL. `system_config` matches `system_config.configuration_key`. A plain key omits that row from the dump. `value` replaces `configuration_value` with `{"_value": value}`. A value that starts with `faker.` is generated per row. When several extensions remove keys from the same column with `JSON_REMOVE`, their rules are combined.
### Disable update notifications
diff --git a/cmd/project/project_dump.go b/cmd/project/project_dump.go
index 0e3cfda6b..8d411f78c 100644
--- a/cmd/project/project_dump.go
+++ b/cmd/project/project_dump.go
@@ -55,7 +55,10 @@ var projectDatabaseDumpCmd = &cobra.Command{
var extensionTables map[string]map[string]string
var systemConfigRules []shop.SystemConfigRule
if anonymize {
- extensionTables, systemConfigRules = anonymizationFromInstalledExtensions(cmd.Context())
+ extensionTables, systemConfigRules, err = anonymizationFromInstalledExtensions(cmd.Context())
+ if err != nil {
+ return err
+ }
}
return shop.DumpDatabase(cmd.Context(), mysqlConfig, projectCfg.ConfigDump, shop.DumpDatabaseOptions{
@@ -136,14 +139,17 @@ func assembleConnectionURI(cmd *cobra.Command) (*mysql.Config, error) {
// anonymizationFromInstalledExtensions collects anonymize rules from extensions
// in the current Shopware project. Outside a project it returns empty rules.
-func anonymizationFromInstalledExtensions(ctx context.Context) (map[string]map[string]string, []shop.SystemConfigRule) {
+func anonymizationFromInstalledExtensions(ctx context.Context) (map[string]map[string]string, []shop.SystemConfigRule, error) {
// Dump stays usable outside a Shopware project. There are no extensions to read.
if projectRoot, err := shop.FindClosestShopwareProject(false); err == nil {
- rules := extension.CollectAnonymization(ctx, projectRoot)
- return rules.Tables, rules.SystemConfig
+ rules, err := extension.CollectAnonymization(ctx, projectRoot)
+ if err != nil {
+ return nil, nil, err
+ }
+ return rules.Tables, rules.SystemConfig, nil
}
- return nil, nil
+ return nil, nil, nil
}
// resolveDumpDatabaseConnection resolves credentials like the other database
diff --git a/cmd/project/project_dump_test.go b/cmd/project/project_dump_test.go
index a6c975d50..cb027eb2b 100644
--- a/cmd/project/project_dump_test.go
+++ b/cmd/project/project_dump_test.go
@@ -86,7 +86,8 @@ func TestAssembleConnectionURIUsernameClearsPassword(t *testing.T) {
func TestAnonymizationFromInstalledExtensions(t *testing.T) {
chdirOutsideProject(t)
- tables, rules := anonymizationFromInstalledExtensions(t.Context())
+ tables, rules, err := anonymizationFromInstalledExtensions(t.Context())
+ require.NoError(t, err)
assert.Nil(t, tables)
assert.Nil(t, rules)
@@ -111,7 +112,8 @@ anonymize:
t.Setenv("PROJECT_ROOT", "")
t.Chdir(projectRoot)
- tables, rules = anonymizationFromInstalledExtensions(t.Context())
+ tables, rules, err = anonymizationFromInstalledExtensions(t.Context())
+ require.NoError(t, err)
assert.Equal(t, map[string]map[string]string{
"swag_example_token": {"access_token": "''"},
}, tables)
diff --git a/internal/extension/anonymize.go b/internal/extension/anonymize.go
index e87772b48..cf7437279 100644
--- a/internal/extension/anonymize.go
+++ b/internal/extension/anonymize.go
@@ -2,6 +2,8 @@ package extension
import (
"context"
+ "errors"
+ "fmt"
"regexp"
"slices"
"strings"
@@ -13,6 +15,9 @@ import (
// anonymizeIdentifierPattern matches Shopware table and column names.
var anonymizeIdentifierPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
+// jsonRemovePattern matches JSON_REMOVE(column, paths) and captures the column and the paths.
+var jsonRemovePattern = regexp.MustCompile("(?is)^\\s*JSON_REMOVE\\s*\\(\\s*(`?([A-Za-z_][A-Za-z0-9_]*)`?)\\s*,(.+)\\)\\s*$")
+
// AnonymizationRules are the column rewrites and system config keys declared
// by extensions installed in a project.
type AnonymizationRules struct {
@@ -33,11 +38,23 @@ type systemConfigOwner struct {
}
// CollectAnonymization reads the anonymize section of every extension in the
-// Shopware project and merges them. Extensions are visited in name order.
-// When two extensions rewrite the same column with different expressions, the
-// first extension is kept and a warning is logged.
-func CollectAnonymization(ctx context.Context, project string) AnonymizationRules {
- extensions := FindExtensionsFromProject(ctx, project, false)
+// Shopware project and merges them in name order. JSON_REMOVE rules on the same
+// column are combined; for other conflicts the first extension wins with a warning.
+// An unreadable extension config is an error, so no rules are skipped silently.
+func CollectAnonymization(ctx context.Context, project string) (AnonymizationRules, error) {
+ var configErrors []error
+ seenPaths := map[string]bool{}
+ extensions := findExtensionsFromProject(ctx, project, false, func(err error) {
+ var configErr *ConfigError
+ if errors.As(err, &configErr) && !seenPaths[configErr.Path] {
+ seenPaths[configErr.Path] = true
+ configErrors = append(configErrors, err)
+ }
+ })
+ if len(configErrors) > 0 {
+ return AnonymizationRules{}, fmt.Errorf("cannot collect anonymize rules from extensions: %w", errors.Join(configErrors...))
+ }
+
slices.SortFunc(extensions, func(a, b Extension) int {
return strings.Compare(extensionSortName(a), extensionSortName(b))
})
@@ -61,15 +78,21 @@ func CollectAnonymization(ctx context.Context, project string) AnonymizationRule
column = strings.ToLower(column)
key := table + "." + column
if owner, exists := owners[key]; exists {
- if owner.expression != expression {
- logging.FromContext(ctx).Warnf(
- "Extension %s rewrites %s.%s, keeping the anonymization rule from %s",
- name,
- table,
- column,
- owner.extension,
- )
+ if owner.expression == expression {
+ continue
+ }
+ if merged, ok := mergeJSONRemove(column, owner.expression, expression); ok {
+ owners[key] = columnOwner{extension: owner.extension, expression: merged}
+ rules.Tables[table][column] = merged
+ continue
}
+ logging.FromContext(ctx).Warnf(
+ "Extension %s rewrites %s.%s, keeping the anonymization rule from %s",
+ name,
+ table,
+ column,
+ owner.extension,
+ )
continue
}
@@ -115,7 +138,18 @@ func CollectAnonymization(ctx context.Context, project string) AnonymizationRule
)
}
- return rules
+ return rules, nil
+}
+
+// mergeJSONRemove combines two JSON_REMOVE rules on the same column into one, so both remove their keys.
+func mergeJSONRemove(column, existing, incoming string) (string, bool) {
+ current := jsonRemovePattern.FindStringSubmatch(existing)
+ next := jsonRemovePattern.FindStringSubmatch(incoming)
+ if current == nil || next == nil || !strings.EqualFold(current[2], column) || !strings.EqualFold(next[2], column) {
+ return "", false
+ }
+
+ return "JSON_REMOVE(" + current[1] + ", " + strings.TrimSpace(current[3]) + ", " + strings.TrimSpace(next[3]) + ")", true
}
func extensionSortName(ext Extension) string {
diff --git a/internal/extension/anonymize_test.go b/internal/extension/anonymize_test.go
index afa925b4a..a92c9cb9a 100644
--- a/internal/extension/anonymize_test.go
+++ b/internal/extension/anonymize_test.go
@@ -1,6 +1,7 @@
package extension
import (
+ "os"
"path/filepath"
"strings"
"testing"
@@ -213,7 +214,8 @@ anonymize:
core, logs := observer.New(zap.InfoLevel)
ctx := logging.WithLogger(t.Context(), zap.New(core).Sugar())
- rules := CollectAnonymization(ctx, project)
+ rules, err := CollectAnonymization(ctx, project)
+ require.NoError(t, err)
assert.Equal(t, map[string]map[string]string{
"swag_shared": {
@@ -258,6 +260,75 @@ anonymize:
assert.Contains(t, merged, "3 system config keys")
}
+func TestCollectAnonymizationFailsOnUnreadableConfig(t *testing.T) {
+ project := t.TempDir()
+ writePlugin(t, project, "AaaPlugin", "Swag\\Aaa\\AaaPlugin", `
+compatibility_date: "2026-01-01"
+anonymize:
+ tables:
+ aaa_token:
+ access_token: "''"
+`)
+ writePlugin(t, project, "BrokenPlugin", "Swag\\Broken\\BrokenPlugin", `
+compatibility_date: "2026-01-01"
+anonymize:
+ system_config:
+ - key: Broken.config.secret
+ omitt: true
+`)
+
+ _, err := CollectAnonymization(t.Context(), project)
+
+ var configErr *ConfigError
+ require.ErrorAs(t, err, &configErr)
+ assert.True(t, strings.HasSuffix(configErr.Path, filepath.Join("BrokenPlugin", ".config", "shopware-extension.yml")))
+}
+
+func TestCollectAnonymizationCombinesJSONRemove(t *testing.T) {
+ project := t.TempDir()
+ writePlugin(t, project, "AaaPlugin", "Swag\\Aaa\\AaaPlugin", `
+compatibility_date: "2026-01-01"
+anonymize:
+ tables:
+ customer:
+ custom_fields: "JSON_REMOVE(custom_fields, '$.aaa_vat', '$.aaa_phone')"
+`)
+ writePlugin(t, project, "ZzzPlugin", "Swag\\Zzz\\ZzzPlugin", `
+compatibility_date: "2026-01-01"
+anonymize:
+ tables:
+ customer:
+ custom_fields: "json_remove(custom_fields, '$.zzz_token')"
+`)
+ require.NoError(t, os.MkdirAll(filepath.Join(project, "custom", "plugins", "not-an-extension"), 0o755))
+
+ rules, err := CollectAnonymization(t.Context(), project)
+ require.NoError(t, err)
+
+ assert.Equal(t, "JSON_REMOVE(custom_fields, '$.aaa_vat', '$.aaa_phone', '$.zzz_token')", rules.Tables["customer"]["custom_fields"])
+}
+
+func TestReadExtensionConfigRejectsUnknownAnonymizeField(t *testing.T) {
+ dir := t.TempDir()
+ testhelper.WriteFile(t, filepath.Join(dir, ".shopware-extension.yml"), `
+compatibility_date: "2026-01-01"
+anonymize:
+ system-config:
+ - SwagExample.config.clientSecret
+`)
+
+ _, err := readExtensionConfig(t.Context(), dir)
+ var configErr *ConfigError
+ assert.ErrorAs(t, err, &configErr)
+
+ testhelper.WriteFile(t, filepath.Join(dir, ".shopware-extension.yml"), `
+compatibility_date: "2026-01-01"
+anonymize:
+`)
+ _, err = readExtensionConfig(t.Context(), dir)
+ assert.NoError(t, err)
+}
+
func writePlugin(t *testing.T, project, folder, class, config string) {
t.Helper()
dir := filepath.Join(project, "custom", "plugins", folder)
diff --git a/internal/extension/config.go b/internal/extension/config.go
index 44ff9b46a..9ce500961 100644
--- a/internal/extension/config.go
+++ b/internal/extension/config.go
@@ -259,6 +259,34 @@ type ConfigAnonymize struct {
SystemConfig []ConfigSystemConfigRule `yaml:"system_config,omitempty"`
}
+// UnmarshalYAML rejects unknown keys, so a typo cannot silently drop rules.
+func (c *ConfigAnonymize) UnmarshalYAML(value *yaml.Node) error {
+ if value.Kind == yaml.MappingNode {
+ for i := 0; i+1 < len(value.Content); i += 2 {
+ if field := value.Content[i].Value; field != "tables" && field != "system_config" {
+ return fmt.Errorf("unknown anonymize field %q", field)
+ }
+ }
+ }
+
+ type plain ConfigAnonymize
+ return value.Decode((*plain)(c))
+}
+
+// ConfigError reports an extension config file that cannot be loaded.
+type ConfigError struct {
+ Path string
+ Err error
+}
+
+func (e *ConfigError) Error() string {
+ return "file: " + e.Path + ": " + e.Err.Error()
+}
+
+func (e *ConfigError) Unwrap() error {
+ return e.Err
+}
+
func (c *Config) HasCompatibilityDate() bool {
return c.CompatibilityDate != ""
}
@@ -286,16 +314,14 @@ func readExtensionConfig(ctx context.Context, dir string) (*Config, error) {
return config, nil
}
- errorFormat := "file: " + config.storageLocation + ": %v"
-
fileHandle, err := os.ReadFile(config.storageLocation)
if err != nil {
- return nil, fmt.Errorf(errorFormat, err)
+ return nil, &ConfigError{Path: config.storageLocation, Err: err}
}
err = yaml.Unmarshal(fileHandle, &config)
if err != nil {
- return nil, fmt.Errorf(errorFormat, err)
+ return nil, &ConfigError{Path: config.storageLocation, Err: err}
}
if config.CompatibilityDate == "" {
@@ -305,7 +331,7 @@ func readExtensionConfig(ctx context.Context, dir string) (*Config, error) {
err = validateExtensionConfig(config)
if err != nil {
- return nil, fmt.Errorf(errorFormat, err)
+ return nil, &ConfigError{Path: config.storageLocation, Err: err}
}
return config, nil
diff --git a/internal/extension/config_schema.json b/internal/extension/config_schema.json
index 8dccd75ff..6ecf823a5 100644
--- a/internal/extension/config_schema.json
+++ b/internal/extension/config_schema.json
@@ -544,7 +544,11 @@
"description": "Replacement stored as {\"_value\": value}. A string starting with faker. is generated per row, for example faker.Internet.Email()."
}
},
- "type": "object"
+ "additionalProperties": false,
+ "type": "object",
+ "required": [
+ "key"
+ ]
}
]
},
diff --git a/internal/extension/project.go b/internal/extension/project.go
index 867fdeba0..f47a6f3a0 100644
--- a/internal/extension/project.go
+++ b/internal/extension/project.go
@@ -234,10 +234,15 @@ func DumpAndLoadAssetSourcesOfProject(ctx context.Context, project string, shopC
}
func FindExtensionsFromProject(ctx context.Context, project string, onlyLocal bool) []Extension {
+ return findExtensionsFromProject(ctx, project, onlyLocal, nil)
+}
+
+// findExtensionsFromProject passes the error of every folder that cannot be loaded to onError.
+func findExtensionsFromProject(ctx context.Context, project string, onlyLocal bool, onError func(error)) []Extension {
extensions := make(map[string]Extension)
if !onlyLocal {
- for _, ext := range addExtensionsByComposer(ctx, project) {
+ for _, ext := range addExtensionsByComposer(ctx, project, onError) {
name, err := ext.GetName()
if err != nil {
continue
@@ -251,7 +256,7 @@ func FindExtensionsFromProject(ctx context.Context, project string, onlyLocal bo
}
}
- for _, ext := range addExtensionsByWildcard(ctx, path.Join(project, "custom", "static-plugins")) {
+ for _, ext := range addExtensionsByWildcard(ctx, path.Join(project, "custom", "static-plugins"), onError) {
name, err := ext.GetName()
if err != nil {
continue
@@ -269,7 +274,7 @@ func FindExtensionsFromProject(ctx context.Context, project string, onlyLocal bo
extensions[name] = ext
}
- for _, ext := range addExtensionsByWildcard(ctx, path.Join(project, "custom", "plugins")) {
+ for _, ext := range addExtensionsByWildcard(ctx, path.Join(project, "custom", "plugins"), onError) {
name, err := ext.GetName()
if err != nil {
continue
@@ -287,7 +292,7 @@ func FindExtensionsFromProject(ctx context.Context, project string, onlyLocal bo
extensions[name] = ext
}
- for _, ext := range addExtensionsByWildcard(ctx, path.Join(project, "custom", "apps")) {
+ for _, ext := range addExtensionsByWildcard(ctx, path.Join(project, "custom", "apps"), onError) {
name, err := ext.GetName()
if err != nil {
continue
@@ -308,7 +313,7 @@ func FindExtensionsFromProject(ctx context.Context, project string, onlyLocal bo
return extensionsSlice
}
-func addExtensionsByComposer(ctx context.Context, project string) []Extension {
+func addExtensionsByComposer(ctx context.Context, project string, onError func(error)) []Extension {
var list []Extension
lock, err := os.ReadFile(path.Join(project, "composer.lock"))
@@ -325,6 +330,9 @@ func addExtensionsByComposer(ctx context.Context, project string) []Extension {
if pkg.PackageType == ComposerTypePlugin || pkg.PackageType == ComposerTypeBundle || pkg.PackageType == ComposerTypeApp {
ext, err := GetExtensionByFolder(ctx, path.Join(project, "vendor", pkg.Name))
if err != nil {
+ if onError != nil {
+ onError(err)
+ }
continue
}
@@ -345,7 +353,7 @@ func addExtensionsByComposer(ctx context.Context, project string) []Extension {
return list
}
-func addExtensionsByWildcard(ctx context.Context, extensionDir string) []Extension {
+func addExtensionsByWildcard(ctx context.Context, extensionDir string, onError func(error)) []Extension {
var list []Extension
extensions, err := os.ReadDir(extensionDir)
@@ -374,6 +382,9 @@ func addExtensionsByWildcard(ctx context.Context, extensionDir string) []Extensi
if isDir {
ext, err := GetExtensionByFolder(ctx, evaluatedPath)
if err != nil {
+ if onError != nil {
+ onError(err)
+ }
continue
}
diff --git a/internal/extension/system_config.go b/internal/extension/system_config.go
index a6c929d91..b59628b47 100644
--- a/internal/extension/system_config.go
+++ b/internal/extension/system_config.go
@@ -87,8 +87,10 @@ func (ConfigSystemConfigRule) JSONSchema() *jsonschema.Schema {
Description: "configuration_key to omit from the dump.",
},
{
- Type: "object",
- Properties: object,
+ Type: "object",
+ Properties: object,
+ Required: []string{"key"},
+ AdditionalProperties: jsonschema.FalseSchema,
},
},
}
diff --git a/internal/mysqldump/faker.go b/internal/mysqldump/faker.go
index 3af37aa26..4711ebc0e 100644
--- a/internal/mysqldump/faker.go
+++ b/internal/mysqldump/faker.go
@@ -1,6 +1,8 @@
package mysqldump
import (
+ "bytes"
+ "encoding/json"
"errors"
"fmt"
"reflect"
@@ -42,6 +44,9 @@ func replaceStringWithFakerWhenRequested(request string) string {
// It handles quoted strings within arguments and chained calls both with and without parens.
r := regexp.MustCompile(`\{\{\-\s*faker(?:\.[a-zA-Z0-9]+(?:\((?:(?:"(?:[^"\\]|\\.)*"|[^"()])*)\))?)+\s*\-\}\}`)
+ // In valid JSON every template sits inside a string, so generated values are escaped to keep it valid.
+ inJSON := json.Valid([]byte(request))
+
return r.ReplaceAllStringFunc(request, func(match string) string {
// Remove {{- -}} and whitespace safely
trimmed := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(match, "{{-"), "-}}"))
@@ -50,10 +55,27 @@ func replaceStringWithFakerWhenRequested(request string) string {
return match
}
+ if inJSON {
+ return escapeJSONString(val)
+ }
+
return val
})
}
+// escapeJSONString escapes s for use inside a JSON string literal.
+func escapeJSONString(s string) string {
+ var buf bytes.Buffer
+ encoder := json.NewEncoder(&buf)
+ encoder.SetEscapeHTML(false)
+ if err := encoder.Encode(s); err != nil {
+ return s
+ }
+
+ encoded := bytes.TrimSpace(buf.Bytes())
+ return string(encoded[1 : len(encoded)-1])
+}
+
// evaluateFakerExpression evaluates a single faker expression (without the {{- -}} delimiters).
// It returns the result of the faker function or an error if evaluation fails.
// This function is intended to be called by replaceStringWithFakerWhenRequested,
diff --git a/internal/mysqldump/faker_test.go b/internal/mysqldump/faker_test.go
index 312501c0d..a6919975d 100644
--- a/internal/mysqldump/faker_test.go
+++ b/internal/mysqldump/faker_test.go
@@ -1,8 +1,12 @@
package mysqldump
import (
+ "encoding/json"
"strings"
"testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
const (
@@ -250,3 +254,16 @@ func Test_service_FakerError(t *testing.T) {
)
}
}
+
+func TestReplaceStringWithFakerKeepsJSONValid(t *testing.T) {
+ for range 20 {
+ got := replaceStringWithFakerWhenRequested(`{"_value":"{{- faker.Address.Address() -}}"}`)
+
+ var decoded map[string]string
+ require.NoError(t, json.Unmarshal([]byte(got), &decoded))
+ assert.NotEmpty(t, decoded["_value"])
+ assert.NotContains(t, decoded["_value"], "faker")
+ }
+
+ assert.Contains(t, replaceStringWithFakerWhenRequested("{{- faker.Address.Address() -}}"), "\n")
+}
diff --git a/internal/mysqldump/mysql.go b/internal/mysqldump/mysql.go
index 0bf842247..105e03e4d 100644
--- a/internal/mysqldump/mysql.go
+++ b/internal/mysqldump/mysql.go
@@ -736,21 +736,37 @@ func (d *Dumper) getColumnsForSelect(ctx context.Context, table string, consider
}
// rewriteSelectExpression quotes a faker template so MySQL returns it as text.
-// SQL that only contains a faker template inside a string literal, such as a
+// SQL that only contains faker templates inside string literals, such as a
// CASE expression, is left as SQL. The dumped text is evaluated afterwards.
func rewriteSelectExpression(replacement string) string {
if !strings.Contains(replacement, "faker.") {
return replacement
}
- trimmed := strings.TrimSpace(replacement)
- if strings.HasPrefix(trimmed, "faker.") || strings.HasPrefix(trimmed, "{{-") {
+ if strings.HasPrefix(strings.TrimSpace(replacement), "faker.") || hasTemplateOutsideStringLiteral(replacement) {
return "'" + replacement + "'"
}
return replacement
}
+// hasTemplateOutsideStringLiteral reports whether a {{- template appears outside a single-quoted SQL string.
+func hasTemplateOutsideStringLiteral(expression string) bool {
+ inLiteral := false
+ for i := 0; i < len(expression); i++ {
+ switch {
+ case inLiteral && expression[i] == '\\':
+ i++
+ case expression[i] == '\'':
+ inLiteral = !inLiteral
+ case !inLiteral && strings.HasPrefix(expression[i:], "{{-"):
+ return true
+ }
+ }
+
+ return false
+}
+
func (d *Dumper) rowCount(ctx context.Context, table string) (count uint64, err error) {
query := fmt.Sprintf("SELECT COUNT(*) FROM `%s`", table)
if where := d.effectiveWhere(table); where != "" {
diff --git a/internal/mysqldump/mysql_test.go b/internal/mysqldump/mysql_test.go
index 838146c21..0c7c9c93d 100644
--- a/internal/mysqldump/mysql_test.go
+++ b/internal/mysqldump/mysql_test.go
@@ -204,6 +204,10 @@ func TestRewriteSelectExpression(t *testing.T) {
expression := "CASE WHEN `configuration_key` = 'A.config.email' THEN '{\"_value\":\"{{- faker.Internet.Email() -}}\"}' ELSE `configuration_value` END"
assert.Equal(t, expression, rewriteSelectExpression(expression))
+
+ assert.Equal(t, "'qa+{{- faker.Internet.User() -}}@example.com'", rewriteSelectExpression("qa+{{- faker.Internet.User() -}}@example.com"))
+ assert.Equal(t, "IF(company IS NULL, company, '{{- faker.Person.Name() -}}')", rewriteSelectExpression("IF(company IS NULL, company, '{{- faker.Person.Name() -}}')"))
+ assert.Equal(t, "CONCAT('it''s ', '{{- faker.Person.Name() -}}')", rewriteSelectExpression("CONCAT('it''s ', '{{- faker.Person.Name() -}}')"))
}
func TestMySQLGetColumnsForSelect(t *testing.T) {
diff --git a/internal/shop/dump.go b/internal/shop/dump.go
index dde34925f..5fab38bf8 100644
--- a/internal/shop/dump.go
+++ b/internal/shop/dump.go
@@ -27,7 +27,7 @@ type DumpDatabaseOptions struct {
// extension-declared tables and system config keys
Anonymize bool
// ExtensionTables are column rewrites declared by installed extensions.
- // Applied only when Anonymize is true. Project dump.rewrite values win.
+ // Applied only when Anonymize is true. Project dump.rewrite values and the built-in rules win.
ExtensionTables map[string]map[string]string
// SystemConfigRules anonymize system_config rows declared by installed extensions.
// Applied only when Anonymize is true. A project rewrite of configuration_value wins
@@ -101,9 +101,9 @@ func dumpDatabase(ctx context.Context, db *sql.DB, cfg *ConfigDump, opts DumpDat
}
// prepareDumpConfig applies clean, anonymize, and limit options to cfg.
-// Extension tables are merged before the built-in customer anonymization, and
-// project dump.rewrite values are left in place. Extension system config keys
-// own system_config.configuration_value unless the project already rewrote it.
+// Extension tables are merged after the built-in customer anonymization, so they
+// only fill columns that neither the project nor the built-in rules set. Extension
+// system config keys own system_config.configuration_value unless the project already rewrote it.
func prepareDumpConfig(cfg *ConfigDump, opts DumpDatabaseOptions) (*ConfigDump, error) {
if cfg == nil {
cfg = &ConfigDump{}
@@ -115,6 +115,7 @@ func prepareDumpConfig(cfg *ConfigDump, opts DumpDatabaseOptions) (*ConfigDump,
if opts.Anonymize {
projectOwnsSystemConfigValue := cfg.hasColumnRewrite("system_config", "configuration_value")
+ cfg.EnableAnonymization()
cfg.MergeRewrite(opts.ExtensionTables)
rewrite, where, err := BuildSystemConfigAnonymization(opts.SystemConfigRules)
if err != nil {
@@ -124,7 +125,6 @@ func prepareDumpConfig(cfg *ConfigDump, opts DumpDatabaseOptions) (*ConfigDump,
cfg.forceRewrite("system_config", "configuration_value", rewrite)
}
cfg.mergeWhere("system_config", where)
- cfg.EnableAnonymization()
}
if err := applyLimitOverrides(cfg, opts.LimitOverrides); err != nil {
diff --git a/internal/shop/dump_test.go b/internal/shop/dump_test.go
index b0fc8bf79..e3be82994 100644
--- a/internal/shop/dump_test.go
+++ b/internal/shop/dump_test.go
@@ -49,7 +49,8 @@ func TestPrepareDumpConfigMergesExtensionAnonymization(t *testing.T) {
"Email": "faker.Internet.Email()",
},
"customer": {
- "email": "''",
+ "email": "''",
+ "custom_fields": "NULL",
},
},
SystemConfigRules: []SystemConfigRule{
@@ -61,7 +62,8 @@ func TestPrepareDumpConfigMergesExtensionAnonymization(t *testing.T) {
assert.Equal(t, "PROJECT", prepared.Rewrite["swag_example_token"]["access_token"])
assert.Equal(t, "{{- faker.Internet.Email() -}}", prepared.Rewrite["swag_example_token"]["email"])
- assert.Equal(t, "''", prepared.Rewrite["customer"]["email"])
+ assert.Equal(t, "{{- faker.Internet.Email() -}}", prepared.Rewrite["customer"]["email"])
+ assert.Equal(t, "NULL", prepared.Rewrite["customer"]["custom_fields"])
assert.Equal(t, "{{- faker.Person.FirstName() -}}", prepared.Rewrite["customer"]["first_name"])
assert.Contains(t, prepared.Rewrite["system_config"]["configuration_value"], "SwagExample.config.merchantEmail")
assert.Contains(t, prepared.Rewrite["system_config"]["configuration_value"], "{{- faker.Internet.Email() -}}")
diff --git a/skills/shopware-cli-extension-anonymize/SKILL.md b/skills/shopware-cli-extension-anonymize/SKILL.md
index 99a8b639b..0a89dc7fb 100644
--- a/skills/shopware-cli-extension-anonymize/SKILL.md
+++ b/skills/shopware-cli-extension-anonymize/SKILL.md
@@ -20,7 +20,8 @@ If the directory is a Shopware project, stop. Project dump rules belong in `.con
The technical name is the prefix for `system_config` keys:
-- Plugin or bundle: the part of `extra.shopware-plugin-class` after the last `\`.
+- Plugin: the part of `extra.shopware-plugin-class` after the last `\`.
+- Bundle: `extra.shopware-bundle-name`.
- App: `` in `manifest.xml`.
## Config file to edit
@@ -31,7 +32,11 @@ The CLI loads the first file that exists:
2. `.shopware-extension.yml`
3. `.shopware-extension.yaml`
-Edit that file only. If none exists, create the recommended one:
+Edit that file only.
+
+If none of them exists, search the build scripts for `shopware-extension` first. Some repositories keep the config elsewhere, such as `config/.shopware-extension.yml`, and copy it to the root when the ZIP is built. Edit that file instead, and tell the developer that only packages with the root file carry the rules.
+
+Only when the extension has no config at all, create the recommended one:
```bash
shopware-cli extension config init
@@ -56,7 +61,7 @@ Declare only tables, columns, and keys that this extension's code contains.
These are configuration keys, not database columns.
- In `config.xml` (plugins usually ship `src/Resources/config/config.xml`, apps `Resources/config/config.xml`): a field `` is stored as `{technicalName}.config.{name}`.
-- In PHP that reads or writes system config, such as `systemConfigService->get('SwagExample.settings.clientSecret')`: copy that string. A `.settings.` key is a different key from `.config.`.
+- In PHP that reads or writes system config, such as `systemConfigService->get('SwagExample.settings.clientSecret')`: copy that string. Keys are often built from constants, such as `SYSTEM_CONFIG_DOMAIN . 'clientSecret'`; resolve them to the full key. A `.settings.` key is a different key from `.config.`.
Include a key when it is a live credential or personal data stored in system config:
@@ -91,7 +96,7 @@ system_config:
`value` is written to `configuration_value` as `{"_value": value}`. A string that starts with `faker.` is generated for each dumped row. `value: null` keeps the row and stores `{"_value": null}`. Do not set `omit` and `value` on the same key.
-Skip settings that are not personal data and not secrets: titles, feature toggles, log level, locales, colors, CSS, snippet keys, and sales channel pickers. Omitting those makes a restored shop unusable. A sandbox flag that must stay on is a custom `value`, not an omission.
+Skip settings that are not personal data and not secrets: titles, feature toggles, log level, locales, colors, CSS, snippet keys, and sales channel pickers. Omitting those makes a restored shop unusable. If the extension has a sandbox or test-mode setting, set it to sandbox or test mode with `value` (for example `value: true` or `value: sandbox`), so a restored shop cannot take live payments.
### tables
@@ -101,9 +106,9 @@ Use database storage names. The DAL property name is not the column.
- Migrations: `CREATE TABLE` column lists. When an entity definition and a migration both describe the table, they should agree; use the storage name from the definition.
- Translated fields live in `{entity}_translation`. Mapping entities have their own entity name.
-Include a column when it stores personal data or a secret: email, first name, last name, company, title, street, zip code, city, phone, IP address, token, secret, password, API key, refresh token, or private key.
+Include a column when it stores personal data or a secret: email, first name, last name, company, title, street, zip code, city, phone, IP address, token, secret, password, API key, refresh token, or private key. Free text that can hold personal data, such as mail bodies, notes, or comments, counts too.
-Skip `id`, foreign keys (`*_id`), `version_id`, timestamps, state technical names, and quantities.
+Skip `id`, foreign keys (`*_id`, or camelCase such as `customerId`), `version_id`, timestamps, state technical names, and quantities.
Skip Shopware core tables. The dump already rewrites `customer`, `customer_address`, `log_entry`, `newsletter_recipient`, `order_address`, `order_customer`, and `product_review`.
@@ -115,7 +120,7 @@ tables:
custom_fields: "JSON_REMOVE(custom_fields, '$.swag_example_vat_id')"
```
-Do not replace the whole `custom_fields` value.
+Use `JSON_REMOVE` on the column itself. The CLI combines it with other extensions' `JSON_REMOVE` rules on the same column. Do not replace the whole `custom_fields` value.
Do not rewrite `system_config.configuration_value` under `tables`. That would wipe every shop setting. List keys under `system_config` instead.
@@ -136,20 +141,36 @@ Do not rewrite `system_config.configuration_value` under `tables`. That would wi
| IP address | `faker.Internet.Ipv4()` |
| secret or token on a required or `NOT NULL` column | `"''"` |
| secret or token on a nullable column | `"NULL"` |
+| free text, such as a mail body or a note | `"NULL"` on a nullable column, otherwise `"''"` |
+| JSON column | `"'{}'"`, or `JSON_OBJECT` with faker templates (see below) |
+| secret on a column with a UNIQUE index | `"NULL"` on a nullable column, otherwise a per-row value such as `"HEX(id)"` |
+
+When the whole rewrite is a bare faker call, write it without `{{- -}}`. The dump adds those delimiters.
-Write faker calls without `{{- -}}`. The dump adds those delimiters.
+Quote empty string and NULL as `"''"` and `"NULL"`. A bare `''` is an empty YAML value, and a bare `NULL` is YAML null. The CLI rejects both. The outer double quotes are YAML, and everything inside them is SQL:
-Quote empty string and NULL as `"''"` and `"NULL"`. A bare `''` is an empty YAML value, and a bare `NULL` is YAML null. The CLI rejects both.
+```yaml
+access_token: "''"
+refresh_token: "NULL"
+payload: "'{}'"
+```
A string column with `->addFlags(new Required())`, or a migration column declared `NOT NULL`, is required. When a string secret's nullability is unclear, use `"''"`. Importing `NULL` into a `NOT NULL` column fails.
-A rewrite that is only a faker expression is selected as text and then evaluated. Any other expression is SQL. A faker template inside that SQL result is evaluated when the row is written.
+Anything other than a bare faker call is SQL. To use faker inside SQL, put the template with its delimiters in a string literal. It is generated when the row is written:
+
+```yaml
+sender: "JSON_OBJECT('{{- faker.Internet.Email() -}}', '{{- faker.Person.Name() -}}')"
+company: "IF(company IS NULL, NULL, '{{- faker.Person.Name() -}}')"
+```
+
+A plain faker call also fills rows that were NULL; the `IF` form keeps them NULL. A JSON column needs a valid JSON value: a plain faker call or text there breaks the import.
Table and column names must match `^[A-Za-z_][A-Za-z0-9_]*$`. Config keys must match `^[A-Za-z0-9_.]+$`.
## Write the section
-Keep every other key, comment, and `compatibility_date`. Add missing tables, columns, and config keys.
+Keep every other key, comment, and `compatibility_date`. Do not add `compatibility_date` to a file that has none. Add missing tables, columns, and config keys.
When `anonymize` already sets a column, keep that expression. Tell the developer about the difference. Do not overwrite it.
@@ -175,7 +196,7 @@ anonymize:
Re-read the config file and check that:
-- the new keys are in the one file the CLI loads
+- the new keys are in the one file the CLI loads, or in the file the build copies there
- keys outside `anonymize` are unchanged
- every new column is a storage name present in the extension
- every new system config key is a `` from `config.xml` or a string passed to SystemConfig
@@ -183,9 +204,11 @@ Re-read the config file and check that:
Then run:
```bash
-shopware-cli extension validate . --format markdown
+shopware-cli extension validate . --only builtin --format markdown
```
+It loads the config and reports anonymize errors without PHP or JavaScript tooling. When the build copies the config to the root, the source tree has no config to load and the command checks nothing. Copy the file to the root path the build uses, run the command, then delete the copy.
+
Fix the config when the error names the extension config file and `anonymize`. Leave unrelated validation findings alone.
## Tell the developer
@@ -195,4 +218,6 @@ Close with two short lists:
- Added: `table.column` or config key, the expression, and the file it came from.
- Left out: fields you saw and did not treat as personal data or secrets, with the reason.
+If the extension also stores personal data in files, such as archived mails, say that the dump does not cover them.
+
Do not print live secret values from config, `.env`, or a database. Key names and column names are fine.
diff --git a/skills/shopware-cli/SKILL.md b/skills/shopware-cli/SKILL.md
index f7837547d..fa5c7f653 100644
--- a/skills/shopware-cli/SKILL.md
+++ b/skills/shopware-cli/SKILL.md
@@ -308,7 +308,7 @@ Prefer Shopware CLI's supported authentication and configuration mechanisms inst
Database dumps and other exports may contain sensitive customer or shop data. Treat their creation, storage, and sharing accordingly.
-`project dump --anonymize` also merges the `anonymize` section from each installed extension's `.config/shopware-extension.yml`: `tables` are column rewrites (same shape as project `dump.rewrite`) and `system_config` omits rows or replaces them with a custom or faker value. Project `dump.rewrite` wins when both set the same column.
+`project dump --anonymize` also merges the `anonymize` section from each installed extension's `.config/shopware-extension.yml`: `tables` are column rewrites (same shape as project `dump.rewrite`) and `system_config` omits rows or replaces them with a custom or faker value. Project `dump.rewrite` wins when both set the same column. If an extension config cannot be read, the dump stops: fix or report that config instead of dropping `--anonymize`.
To fill that section from an extension's entities and `config.xml`, use the `shopware-cli-extension-anonymize` skill when available.