From 25f536563ad4c833e0771cd8de4cc33a10bd0fb9 Mon Sep 17 00:00:00 2001 From: Dominik Schmidt Date: Fri, 9 Oct 2026 11:50:29 +0200 Subject: [PATCH] feat(proxy): accept lists and globs for the CSP config file locations --- services/proxy/README.md | 2 +- services/proxy/pkg/config/config.go | 4 +- .../pkg/config/defaults/defaultconfig.go | 8 +- services/proxy/pkg/middleware/security.go | 89 ++++++++++++++----- .../proxy/pkg/middleware/security_test.go | 71 +++++++++++++++ 5 files changed, 146 insertions(+), 28 deletions(-) diff --git a/services/proxy/README.md b/services/proxy/README.md index 8191a5cddb..ce913a69db 100644 --- a/services/proxy/README.md +++ b/services/proxy/README.md @@ -325,7 +325,7 @@ The proxy service passes the client address on to the other services in `X-Forwa For OpenCloud, external resources like an IDP (e.g. Keycloak) or when using web office documents or web apps, require defining a CSP. If not defined, the referenced services will not work. -To create a Content Security Policy (CSP), you need to create a yaml file containing the CSP definitions. To activate the settings, reference the file as value in the `PROXY_CSP_CONFIG_FILE_LOCATION` environment variable. For each change, a restart of the OpenCloud deployment or the proxy service is required. +To create a Content Security Policy (CSP), you need to create a yaml file containing the CSP definitions. To activate the settings, reference the file as value in the `PROXY_CSP_CONFIG_FILE_LOCATION` environment variable. The value can also be a comma-separated list, where each element is either a path or a glob pattern, for example `/etc/opencloud/csp.yaml,/web/apps/*/csp.yaml`. In the yaml config, use a yaml list instead. All matching files are merged into the default CSP in the given order, with the matches of a pattern sorted by name. A pattern without matches is ignored, while a path to a file that does not exist prevents the proxy from starting. This allows each web app to ship its own CSP file. Be aware that a pattern like `/web/apps/*/csp.yaml` hands control of the CSP to whoever can write into the matching directories: merging only adds sources, so every file found there can loosen the policy, for example by extending `script-src`. Only use patterns for directories whose content you trust. To replace the default CSP instead of extending it, use `PROXY_CSP_CONFIG_FILE_OVERRIDE_LOCATION`. It accepts the same list syntax, the files are merged with each other in the given order, at least one of them needs to exist, and `PROXY_CSP_CONFIG_FILE_LOCATION` is ignored. For each change, a restart of the OpenCloud deployment or the proxy service is required. A working example for a CSP can be found in a sub path of the `config` directory of the [opencloud-compose](https://github.com/opencloud-eu/opencloud-compose/tree/main/config) deployment example. diff --git a/services/proxy/pkg/config/config.go b/services/proxy/pkg/config/config.go index b10ecfdf35..f9ed3a2479 100644 --- a/services/proxy/pkg/config/config.go +++ b/services/proxy/pkg/config/config.go @@ -48,8 +48,8 @@ type Config struct { BackendHTTPSCACert string `yaml:"backend_https_cacert" env:"PROXY_HTTPS_CACERT" desc:"Path/File for the root CA certificate used to validate the server’s TLS certificate for https enabled backend services." introductionVersion:"1.0.0"` AuthMiddleware AuthMiddleware `yaml:"auth_middleware"` PoliciesMiddleware PoliciesMiddleware `yaml:"policies_middleware"` - CSPConfigFileLocation string `yaml:"csp_config_file_location" env:"PROXY_CSP_CONFIG_FILE_LOCATION" desc:"The location of the CSP configuration file." introductionVersion:"1.0.0"` - CSPConfigFileOverrideLocation string `yaml:"csp_config_file_override_location" env:"PROXY_CSP_CONFIG_FILE_OVERRIDE_LOCATION" desc:"The location of the CSP configuration file override." introductionVersion:"4.0.0"` + CSPConfigFileLocation []string `yaml:"csp_config_file_location" env:"PROXY_CSP_CONFIG_FILE_LOCATION" desc:"A comma-separated list of CSP configuration files, which are merged into the default CSP in the given order. Each element can be a path or a glob pattern like '/web/apps/*/csp.yaml'. A pattern without matches is ignored, a path to a missing file is an error." introductionVersion:"1.0.0"` + CSPConfigFileOverrideLocation []string `yaml:"csp_config_file_override_location" env:"PROXY_CSP_CONFIG_FILE_OVERRIDE_LOCATION" desc:"A comma-separated list of CSP configuration files, which replace the default CSP and are merged in the given order. Each element can be a path or a glob pattern like '/web/apps/*/csp.yaml'. A pattern without matches is ignored, a path to a missing file is an error. At least one file needs to exist. If set, PROXY_CSP_CONFIG_FILE_LOCATION is ignored." introductionVersion:"4.0.0"` Events Events `yaml:"events"` Audit Audit `yaml:"audit"` GuestLinkAuth GuestLinkAuth `yaml:"guest_link_auth"` diff --git a/services/proxy/pkg/config/defaults/defaultconfig.go b/services/proxy/pkg/config/defaults/defaultconfig.go index b2ec50a0f9..b7d01ed9f4 100644 --- a/services/proxy/pkg/config/defaults/defaultconfig.go +++ b/services/proxy/pkg/config/defaults/defaultconfig.go @@ -112,9 +112,7 @@ func DefaultConfig() *config.Config { Audit: config.Audit{ Mode: "best_effort", }, - InsecureBackends: false, - CSPConfigFileLocation: "", - CSPConfigFileOverrideLocation: "", + InsecureBackends: false, Events: config.Events{ Endpoint: "127.0.0.1:9233", Cluster: "opencloud-cluster", @@ -377,10 +375,10 @@ func Sanitize(cfg *config.Config) { } // if the CSP config file path is not set, we check if the default file exists and set it if it does - if cfg.CSPConfigFileLocation == "" { + if len(cfg.CSPConfigFileLocation) == 0 { defaultCSPConfigFilePath := filepath.Join(defaults.BaseDataPath(), "proxy", "csp.yaml") if _, err := os.Stat(defaultCSPConfigFilePath); err == nil { - cfg.CSPConfigFileLocation = defaultCSPConfigFilePath + cfg.CSPConfigFileLocation = []string{defaultCSPConfigFilePath} } } } diff --git a/services/proxy/pkg/middleware/security.go b/services/proxy/pkg/middleware/security.go index 0831679c08..5381a52b4f 100644 --- a/services/proxy/pkg/middleware/security.go +++ b/services/proxy/pkg/middleware/security.go @@ -1,9 +1,12 @@ package middleware import ( + "fmt" "net/http" "os" + "path/filepath" "reflect" + "strings" gofig "github.com/gookit/config/v2" "github.com/gookit/config/v2/yaml" @@ -15,43 +18,46 @@ import ( // LoadCSPConfig loads CSP header configuration from a yaml file. func LoadCSPConfig(proxyCfg *config.Config) (*config.CSP, error) { - yamlContent, customYamlContent, err := loadCSPYaml(proxyCfg) + yamlContent, customYamlContents, err := loadCSPYaml(proxyCfg) if err != nil { return nil, err } - return loadCSPConfig(yamlContent, customYamlContent) + return loadCSPConfig(yamlContent, customYamlContents...) } -// LoadCSPConfig loads CSP header configuration from a yaml file. -func loadCSPConfig(presetYamlContent, customYamlContent []byte) (*config.CSP, error) { +// loadCSPConfig merges the custom yaml contents into the preset, in the given order. +func loadCSPConfig(presetYamlContent []byte, customYamlContents ...[]byte) (*config.CSP, error) { // substitute env vars and load to struct - gofig.WithOptions(gofig.ParseEnv) - gofig.AddDriver(yaml.Driver) + cspLoader := gofig.NewWithOptions("csp", gofig.ParseEnv) + cspLoader.AddDriver(yaml.Driver) presetMap := map[string]any{} err := yamlv3.Unmarshal(presetYamlContent, &presetMap) if err != nil { return nil, err } - customMap := map[string]any{} - err = yamlv3.Unmarshal(customYamlContent, &customMap) - if err != nil { - return nil, err + mergedMap := presetMap + for _, customYamlContent := range customYamlContents { + customMap := map[string]any{} + err = yamlv3.Unmarshal(customYamlContent, &customMap) + if err != nil { + return nil, err + } + mergedMap = deepMerge(mergedMap, customMap) } - mergedMap := deepMerge(presetMap, customMap) mergedYamlContent, err := yamlv3.Marshal(mergedMap) if err != nil { return nil, err } - err = gofig.LoadSources("yaml", mergedYamlContent) + err = cspLoader.LoadSources("yaml", mergedYamlContent) if err != nil { return nil, err } // read yaml cspConfig := config.CSP{} - err = gofig.BindStruct("", &cspConfig) + err = cspLoader.BindStruct("", &cspConfig) if err != nil { return nil, err } @@ -121,16 +127,59 @@ func sliceContains(slice []any, val any) bool { return false } -func loadCSPYaml(proxyCfg *config.Config) ([]byte, []byte, error) { - if proxyCfg.CSPConfigFileOverrideLocation != "" { - overrideCSPYaml, err := os.ReadFile(proxyCfg.CSPConfigFileOverrideLocation) - return overrideCSPYaml, []byte{}, err +func loadCSPYaml(proxyCfg *config.Config) ([]byte, [][]byte, error) { + if len(proxyCfg.CSPConfigFileOverrideLocation) > 0 { + overrideCSPYamls, err := readCSPConfigFiles(proxyCfg.CSPConfigFileOverrideLocation) + if err != nil { + return nil, nil, err + } + if len(overrideCSPYamls) == 0 { + return nil, nil, fmt.Errorf("no CSP configuration file found for override location %q", strings.Join(proxyCfg.CSPConfigFileOverrideLocation, ",")) + } + return overrideCSPYamls[0], overrideCSPYamls[1:], nil } - if proxyCfg.CSPConfigFileLocation == "" { + if len(proxyCfg.CSPConfigFileLocation) == 0 { return []byte(config.DefaultCSPConfig), nil, nil } - customCSPYaml, err := os.ReadFile(proxyCfg.CSPConfigFileLocation) - return []byte(config.DefaultCSPConfig), customCSPYaml, err + customCSPYamls, err := readCSPConfigFiles(proxyCfg.CSPConfigFileLocation) + return []byte(config.DefaultCSPConfig), customCSPYamls, err +} + +func readCSPConfigFiles(locations []string) ([][]byte, error) { + files, err := resolveCSPConfigFiles(locations) + if err != nil { + return nil, err + } + yamlContents := make([][]byte, 0, len(files)) + for _, file := range files { + yamlContent, err := os.ReadFile(file) + if err != nil { + return nil, err + } + yamlContents = append(yamlContents, yamlContent) + } + return yamlContents, nil +} + +func resolveCSPConfigFiles(locations []string) ([]string, error) { + files := []string{} + for _, location := range locations { + location = strings.TrimSpace(location) + if location == "" { + continue + } + // keep plain paths so that a missing file still fails + if !strings.ContainsAny(location, `*?[`) { + files = append(files, location) + continue + } + matches, err := filepath.Glob(location) + if err != nil { + return nil, err + } + files = append(files, matches...) + } + return files, nil } // Security is a middleware to apply security relevant http headers like CSP. diff --git a/services/proxy/pkg/middleware/security_test.go b/services/proxy/pkg/middleware/security_test.go index cc681f6d14..698ae6bfbe 100644 --- a/services/proxy/pkg/middleware/security_test.go +++ b/services/proxy/pkg/middleware/security_test.go @@ -3,6 +3,8 @@ package middleware import ( "net/http" "net/http/httptest" + "os" + "path/filepath" "testing" "github.com/opencloud-eu/opencloud/services/proxy/pkg/config" @@ -88,3 +90,72 @@ directives: assert.Assert(t, cmp.Contains(config.Directives["img-src"], "'self'")) assert.Assert(t, cmp.Contains(config.Directives["img-src"], "data:")) } + +func writeCSPFile(t *testing.T, path string, frameSrc string) { + t.Helper() + assert.NilError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + content := "directives:\n frame-src:\n - '" + frameSrc + "'\n" + assert.NilError(t, os.WriteFile(path, []byte(content), 0o600)) +} + +func TestLoadCSPConfigFromLocations(t *testing.T) { + dir := t.TempDir() + writeCSPFile(t, filepath.Join(dir, "csp.yaml"), "https://global.test/") + writeCSPFile(t, filepath.Join(dir, "apps", "a", "csp.yaml"), "https://a.test/") + writeCSPFile(t, filepath.Join(dir, "apps", "b", "csp.yaml"), "https://b.test/") + + t.Run("single path", func(t *testing.T) { + cspConfig, err := LoadCSPConfig(&config.Config{CSPConfigFileLocation: []string{filepath.Join(dir, "csp.yaml")}}) + assert.NilError(t, err) + assert.Assert(t, cmp.Contains(cspConfig.Directives["frame-src"], "'self'")) + assert.Assert(t, cmp.Contains(cspConfig.Directives["frame-src"], "https://global.test/")) + }) + + t.Run("list of path and glob", func(t *testing.T) { + location := []string{filepath.Join(dir, "csp.yaml"), filepath.Join(dir, "apps", "*", "csp.yaml")} + cspConfig, err := LoadCSPConfig(&config.Config{CSPConfigFileLocation: location}) + assert.NilError(t, err) + frameSrc := cspConfig.Directives["frame-src"] + assert.Assert(t, cmp.Contains(frameSrc, "'self'")) + assert.DeepEqual(t, frameSrc[len(frameSrc)-3:], []string{"https://global.test/", "https://a.test/", "https://b.test/"}) + }) + + t.Run("glob without matches is ignored", func(t *testing.T) { + cspConfig, err := LoadCSPConfig(&config.Config{CSPConfigFileLocation: []string{filepath.Join(dir, "none", "*", "csp.yaml")}}) + assert.NilError(t, err) + assert.Assert(t, cmp.Contains(cspConfig.Directives["frame-src"], "'self'")) + }) + + t.Run("empty locations are skipped", func(t *testing.T) { + location := []string{filepath.Join(dir, "csp.yaml"), "", " "} + cspConfig, err := LoadCSPConfig(&config.Config{CSPConfigFileLocation: location}) + assert.NilError(t, err) + assert.Assert(t, cmp.Contains(cspConfig.Directives["frame-src"], "https://global.test/")) + }) + + t.Run("missing path fails", func(t *testing.T) { + _, err := LoadCSPConfig(&config.Config{CSPConfigFileLocation: []string{filepath.Join(dir, "missing.yaml")}}) + assert.Assert(t, os.IsNotExist(err)) + }) + + t.Run("override replaces the default and ignores locations", func(t *testing.T) { + cspConfig, err := LoadCSPConfig(&config.Config{ + CSPConfigFileLocation: []string{filepath.Join(dir, "apps", "a", "csp.yaml")}, + CSPConfigFileOverrideLocation: []string{filepath.Join(dir, "csp.yaml")}, + }) + assert.NilError(t, err) + assert.DeepEqual(t, cspConfig.Directives["frame-src"], []string{"https://global.test/"}) + }) + + t.Run("override list of path and glob", func(t *testing.T) { + location := []string{filepath.Join(dir, "csp.yaml"), filepath.Join(dir, "apps", "*", "csp.yaml")} + cspConfig, err := LoadCSPConfig(&config.Config{CSPConfigFileOverrideLocation: location}) + assert.NilError(t, err) + assert.DeepEqual(t, cspConfig.Directives["frame-src"], []string{"https://global.test/", "https://a.test/", "https://b.test/"}) + }) + + t.Run("override without any file fails", func(t *testing.T) { + _, err := LoadCSPConfig(&config.Config{CSPConfigFileOverrideLocation: []string{filepath.Join(dir, "none", "*", "csp.yaml")}}) + assert.ErrorContains(t, err, "no CSP configuration file found") + }) +}