Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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

Expand Down
16 changes: 11 additions & 5 deletions cmd/project/project_dump.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions cmd/project/project_dump_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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)
Expand Down
62 changes: 48 additions & 14 deletions internal/extension/anonymize.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package extension

import (
"context"
"errors"
"fmt"
"regexp"
"slices"
"strings"
Expand All @@ -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 {
Expand All @@ -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))
})
Expand All @@ -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
}

Expand Down Expand Up @@ -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 {
Expand Down
73 changes: 72 additions & 1 deletion internal/extension/anonymize_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package extension

import (
"os"
"path/filepath"
"strings"
"testing"
Expand Down Expand Up @@ -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": {
Expand Down Expand Up @@ -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)
Expand Down
36 changes: 31 additions & 5 deletions internal/extension/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 != ""
}
Expand Down Expand Up @@ -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 == "" {
Expand All @@ -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
Expand Down
6 changes: 5 additions & 1 deletion internal/extension/config_schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
]
}
]
},
Expand Down
Loading