From d8d7c1082b9c4791dbe18f582fdbc39aa8265bb2 Mon Sep 17 00:00:00 2001 From: Ralf Haferkamp Date: Wed, 11 Nov 2026 12:45:41 +0100 Subject: [PATCH] [full-ci] [stable-7.2] preparing 7.2.5 (#3953) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Merge pull request #45 from opencloud-eu/backports/stable-7.2-42 [stable-7.2] fix(web): merge copies of the theme sources so themeDefaults is never… * Merge pull request #47 from opencloud-eu/backports/stable-7.2-43 [stable-7.2] fix(search): handle missing operands in the bleve compiler * Merge pull request #49 from opencloud-eu/fix/stable-7.2/search-highlight-escaping [stable-7.2] fix(search): escape file content in OpenSearch highlights * Bump version --- pkg/version/version.go | 2 +- services/search/pkg/content/content.go | 2 +- services/search/pkg/content/content_test.go | 8 ++ services/search/pkg/opensearch/backend.go | 1 + .../search/pkg/opensearch/backend_test.go | 20 ++++ services/search/pkg/query/bleve/compiler.go | 5 + .../search/pkg/query/bleve/compiler_test.go | 22 ++++- services/search/pkg/search/service.go | 31 ++++++- services/search/pkg/search/service_test.go | 39 +++++++- services/web/pkg/theme/kv.go | 8 +- services/web/pkg/theme/kv_test.go | 91 +++++++++++++++++++ services/web/pkg/theme/service_test.go | 68 ++++++++++++++ 12 files changed, 289 insertions(+), 8 deletions(-) diff --git a/pkg/version/version.go b/pkg/version/version.go index 79e568defd..30cd0801c3 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -34,7 +34,7 @@ var ( // LatestTag is the latest released version plus the dev meta version. // Will be overwritten by the release pipeline // Needs a manual change for every tagged release - LatestTag = "7.2.4+dev" + LatestTag = "7.2.5+dev" // Date indicates the build date. // This has been removed, it looks like you can only replace static strings with recent go versions diff --git a/services/search/pkg/content/content.go b/services/search/pkg/content/content.go index e185351678..d61260a729 100644 --- a/services/search/pkg/content/content.go +++ b/services/search/pkg/content/content.go @@ -29,5 +29,5 @@ type Document struct { } func CleanString(content, langCode string) string { - return strings.TrimSpace(stopwords.CleanString(content, langCode, true)) + return strings.TrimSpace(stopwords.CleanString(content, langCode, false)) } diff --git a/services/search/pkg/content/content_test.go b/services/search/pkg/content/content_test.go index 389dcd001c..6e12592529 100644 --- a/services/search/pkg/content/content_test.go +++ b/services/search/pkg/content/content_test.go @@ -25,6 +25,14 @@ func TestCleanContent(t *testing.T) { given: "content contains https://localhost/remote.php/dav/files/admin/Photos/San%20Francisco.jpg and stop word", expect: "content contains https://localhost/remote.php/dav/files/admin/photos/san%20francisco.jpg stop word", }, + { + given: "needle <img src=x> needle", + expect: "needle <img src=x> needle", + }, + { + given: "List names from Alice ", + expect: "list names alice ", + }, } for _, tc := range tests { diff --git a/services/search/pkg/opensearch/backend.go b/services/search/pkg/opensearch/backend.go index 000b24ebf1..c1b3ea1b07 100644 --- a/services/search/pkg/opensearch/backend.go +++ b/services/search/pkg/opensearch/backend.go @@ -118,6 +118,7 @@ func (b *Backend) Search(ctx context.Context, sir *searchService.SearchIndexRequ osu.SearchBodyParams{ Highlight: &osu.BodyParamHighlight{ HighlightOptions: osu.HighlightOptions{ + Encoder: "html", NumberOfFragments: 2, PreTags: []string{""}, PostTags: []string{""}, diff --git a/services/search/pkg/opensearch/backend_test.go b/services/search/pkg/opensearch/backend_test.go index a8579180ac..63c5868a08 100644 --- a/services/search/pkg/opensearch/backend_test.go +++ b/services/search/pkg/opensearch/backend_test.go @@ -140,6 +140,26 @@ var _ = Describe("Backend", func() { Expect(resp.TotalMatches).To(Equal(int32(1))) Expect(fmt.Sprintf("%s$%s!%s", resp.Matches[0].Entity.Id.StorageId, resp.Matches[0].Entity.Id.SpaceId, resp.Matches[0].Entity.Id.OpaqueId)).To(Equal(document.ID)) }) + + DescribeTable("returns the content highlights as text", + func(content, query, expected string) { + highlighted := opensearchtest.Testdata.Resources.File + highlighted.ID = "1$2!5" + highlighted.Content = content + + tc.Require.DocumentCreate(indexName, highlighted.ID, strings.NewReader(opensearchtest.JSONMustMarshal(GinkgoTB(), highlighted))) + tc.Require.IndicesCount([]string{indexName}, nil, 2) + + resp, err := backend.Search(context.Background(), &searchService.SearchIndexRequest{ + Query: query, + }) + Expect(err).ToNot(HaveOccurred()) + Expect(resp.Matches).To(HaveLen(1)) + Expect(resp.Matches[0].Entity.Highlights).To(Equal(expected)) + }, + Entry("markup", "foo qux", "content:qux", "foo <img src=x> qux"), + Entry("escaped text", "foo <img src=x> zap", "content:zap", "foo &lt;img src=x&gt; zap"), + ) }) Describe("Upsert", func() { diff --git a/services/search/pkg/query/bleve/compiler.go b/services/search/pkg/query/bleve/compiler.go index 310397cae6..6577414c7f 100644 --- a/services/search/pkg/query/bleve/compiler.go +++ b/services/search/pkg/query/bleve/compiler.go @@ -6,6 +6,7 @@ import ( "github.com/blevesearch/bleve/v2" bleveQuery "github.com/blevesearch/bleve/v2/search/query" + "github.com/opencloud-eu/opencloud/pkg/ast" "github.com/opencloud-eu/opencloud/pkg/kql" ) @@ -215,6 +216,10 @@ func walk(offset int, nodes []ast.Node) (bleveQuery.Query, int, error) { } func nextNode(offset int, nodes []ast.Node) (bleveQuery.Query, int, error) { + if offset >= len(nodes) { + return nil, 0, fmt.Errorf("operator without an operand") + } + if n, ok := nodes[offset].(*ast.GroupNode); ok { gq, _, err := walk(0, n.Nodes) if err != nil { diff --git a/services/search/pkg/query/bleve/compiler_test.go b/services/search/pkg/query/bleve/compiler_test.go index ff94e88726..dd1e0f1719 100644 --- a/services/search/pkg/query/bleve/compiler_test.go +++ b/services/search/pkg/query/bleve/compiler_test.go @@ -5,8 +5,9 @@ import ( "time" "github.com/blevesearch/bleve/v2/search/query" - "github.com/opencloud-eu/opencloud/pkg/ast" tAssert "github.com/stretchr/testify/assert" + + "github.com/opencloud-eu/opencloud/pkg/ast" ) var timeMustParse = func(t *testing.T, ts string) time.Time { @@ -525,6 +526,25 @@ func Test_compile(t *testing.T) { }), wantErr: false, }, + { + name: `missing right operand`, + args: &ast.Ast{ + Nodes: []ast.Node{ + &ast.StringNode{Value: "foo"}, + &ast.OperatorNode{Value: "NOT"}, + }, + }, + wantErr: true, + }, + { + name: `no operands`, + args: &ast.Ast{ + Nodes: []ast.Node{ + &ast.OperatorNode{Value: "NOT"}, + }, + }, + wantErr: true, + }, } assert := tAssert.New(t) diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 3f0378f062..df7e20e65f 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -3,6 +3,7 @@ package search import ( "context" "fmt" + "html" "path/filepath" "sort" "strconv" @@ -297,7 +298,15 @@ func (s *Service) Search(ctx context.Context, req *searchsvc.SearchRequest) (*se }, nil } -func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest, space *provider.StorageSpace, mountpointID string) (*searchsvc.SearchIndexResponse, error) { +func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest, space *provider.StorageSpace, mountpointID string) (res *searchsvc.SearchIndexResponse, err error) { + // the workers run in an errgroup, which does not recover, one failing space must not affect the others + defer func() { + if r := recover(); r != nil { + s.logger.Error().Interface("recover", r).Str("space", space.GetId().GetOpaqueId()).Str("query", req.GetQuery()).Msg("failed to search a space") + res, err = nil, errSkipSpace + } + }() + if req.Ref != nil && (req.Ref.ResourceId.StorageId != space.Root.StorageId || req.Ref.ResourceId.SpaceId != space.Root.SpaceId) { @@ -402,7 +411,7 @@ func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest, PageSize: req.PageSize, } start := time.Now() - res, err := s.engine.Search(ctx, searchRequest) + res, err = s.engine.Search(ctx, searchRequest) duration := time.Since(start) if err != nil { s.logger.Error().Err(err).Str("duration", fmt.Sprint(duration)).Str("space", space.Id.OpaqueId).Msg("failed to search the index") @@ -425,6 +434,7 @@ func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest, } match.Entity.ShareRootName = rootName match.Entity.RemoteItemId = remoteItemId + match.Entity.Highlights = SanitizeHighlights(match.Entity.GetHighlights()) isShared := match.GetEntity().GetRef().GetResourceId().GetSpaceId() == utils.ShareStorageSpaceID isMountpoint := isShared && match.GetEntity().GetRef().GetPath() == "." @@ -687,6 +697,23 @@ func (s *Service) doUpsertItem(ref *provider.Reference, batch BatchOperator) { } } +// SanitizeHighlights keeps the tags and escapes everything else. +func SanitizeHighlights(highlights string) string { + var b strings.Builder + for i, open := range strings.Split(highlights, "") { + if i > 0 { + b.WriteString("") + } + for j, closed := range strings.Split(open, "") { + if j > 0 { + b.WriteString("") + } + b.WriteString(html.EscapeString(html.UnescapeString(closed))) + } + } + return b.String() +} + func addAudioMetadata(metadata map[string]string, audio *libregraph.Audio) { if audio == nil { return diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 301e9db031..08f3cd1b7b 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -171,7 +171,8 @@ var _ = Describe("Searchprovider", func() { StorageId: personalSpace.Root.StorageId, OpaqueId: "foo-id", }, - Name: "Foo.pdf", + Name: "Foo.pdf", + Highlights: `foo bar`, }, }, }, @@ -182,6 +183,15 @@ var _ = Describe("Searchprovider", func() { }, nil) }) + It("escapes the highlights whatever the engine returned", func() { + res, err := s.Search(ctx, &searchsvc.SearchRequest{ + Query: "bar", + }) + Expect(err).ToNot(HaveOccurred()) + Expect(res.Matches).To(HaveLen(1)) + Expect(res.Matches[0].Entity.Highlights).To(Equal(`foo <img src=x> bar`)) + }) + It("does not mess with field-based searches", func() { _, err := s.Search(ctx, &searchsvc.SearchRequest{ Query: "Size:<10", @@ -192,6 +202,19 @@ var _ = Describe("Searchprovider", func() { })) }) + It("continues with the remaining spaces when one fails", func() { + failingClient := &engineMocks.Engine{} + failingClient.On("Search", mock.Anything, mock.Anything).Run(func(mock.Arguments) { + panic("unexpected") + }).Return(nil, nil) + s := search.NewService(gatewaySelector, failingClient, extractor, nil, logger, &config.Config{}) + + res, err := s.Search(ctx, &searchsvc.SearchRequest{Query: "foo"}) + Expect(err).ToNot(HaveOccurred()) + Expect(res.TotalMatches).To(Equal(int32(0))) + Expect(res.Matches).To(BeEmpty()) + }) + It("searches the personal user space", func() { res, err := s.Search(ctx, &searchsvc.SearchRequest{ Query: "foo", @@ -490,6 +513,20 @@ var _ = Describe("Searchprovider", func() { }) }) +var _ = DescribeTable("SanitizeHighlights", + func(highlights, expected string) { + Expect(search.SanitizeHighlights(highlights)).To(Equal(expected)) + }, + Entry("plain text", "foo bar baz", "foo bar baz"), + Entry("raw markup", " bar", "<img src=x> bar"), + Entry("already escaped", "<img src=x> bar", "<img src=x> bar"), + Entry("escaped text from the file stays as typed", "&lt;img src=x&gt; bar", "&lt;img src=x&gt; bar"), + Entry("markup inside a mark", "bar", "<b>bar</b>"), + Entry("a mark with attributes", `bar`, "<mark class="x">bar"), + Entry("an escaped ampersand stays single", "Tom & Jerry", "Tom & Jerry"), + Entry("empty", "", ""), +) + var _ = DescribeTable("Parse Scope", func(pattern, wantSearch, wantScope string) { gotSearch, gotScope := search.ParseScope(pattern) diff --git a/services/web/pkg/theme/kv.go b/services/web/pkg/theme/kv.go index 928c7edb7a..33ae64cebe 100644 --- a/services/web/pkg/theme/kv.go +++ b/services/web/pkg/theme/kv.go @@ -6,18 +6,22 @@ import ( "strings" "dario.cat/mergo" + "github.com/mohae/deepcopy" "github.com/spf13/afero" ) // KV is a generic key-value map. type KV map[string]any -// MergeKV merges the given key-value maps. +// MergeKV merges the given key-value maps into a new one, the given maps are not modified. func MergeKV(values ...KV) (KV, error) { var kv KV for _, v := range values { - err := mergo.Merge(&kv, v, mergo.WithOverride) + // mergo reuses the nested maps of a source in the destination and merges later sources into them, + // so it must only see a copy; otherwise shared inputs like themeDefaults get modified, + // concurrently when requests run in parallel. + err := mergo.Merge(&kv, deepcopy.Copy(v).(KV), mergo.WithOverride) if err != nil { return nil, err } diff --git a/services/web/pkg/theme/kv_test.go b/services/web/pkg/theme/kv_test.go index 855da86ec7..18cec30f23 100644 --- a/services/web/pkg/theme/kv_test.go +++ b/services/web/pkg/theme/kv_test.go @@ -2,6 +2,8 @@ package theme_test import ( "encoding/json" + "strconv" + "sync" "testing" "github.com/spf13/afero" @@ -30,6 +32,95 @@ func TestMergeKV(t *testing.T) { }) } +func TestMergeKVDoesNotMutateInputs(t *testing.T) { + defaults := theme.KV{ + "common": theme.KV{ + "name": "default", + "shareRoles": theme.KV{ + "viewer": theme.KV{"iconName": "eye"}, + }, + }, + "list": []any{theme.KV{"a": "a"}}, + } + override := theme.KV{ + "common": map[string]any{ + "logo": "override.svg", + "shareRoles": map[string]any{ + "viewer": map[string]any{"iconName": "glasses"}, + }, + }, + } + + result, err := theme.MergeKV(defaults, override) + assert.Nil(t, err) + assert.Equal(t, theme.KV{ + "common": theme.KV{ + "name": "default", + "logo": "override.svg", + "shareRoles": theme.KV{ + "viewer": theme.KV{"iconName": "glasses"}, + }, + }, + "list": []any{theme.KV{"a": "a"}}, + }, result) + + // the inputs must be left untouched by the merge + assert.Equal(t, theme.KV{ + "common": theme.KV{ + "name": "default", + "shareRoles": theme.KV{ + "viewer": theme.KV{"iconName": "eye"}, + }, + }, + "list": []any{theme.KV{"a": "a"}}, + }, defaults) + + // changing the result must not leak back into the inputs + result["common"].(theme.KV)["name"] = "changed" + result["list"].([]any)[0].(theme.KV)["a"] = "changed" + assert.Equal(t, "default", defaults["common"].(theme.KV)["name"]) + assert.Equal(t, "a", defaults["list"].([]any)[0].(theme.KV)["a"]) + assert.Equal(t, "override.svg", override["common"].(map[string]any)["logo"]) + + // a later merge must not see values from an earlier one + result, err = theme.MergeKV(defaults, theme.KV{}) + assert.Nil(t, err) + assert.NotContains(t, result["common"], "logo") +} + +func TestMergeKVConcurrent(t *testing.T) { + defaults := theme.KV{ + "common": theme.KV{ + "name": "default", + "shareRoles": theme.KV{ + "viewer": theme.KV{"iconName": "eye"}, + }, + }, + } + + var wg sync.WaitGroup + for i := range 50 { + wg.Add(1) + go func() { + defer wg.Done() + name := strconv.Itoa(i) + result, err := theme.MergeKV(defaults, theme.KV{ + "common": map[string]any{ + "name": name, + "shareRoles": map[string]any{ + "viewer": map[string]any{"iconName": name}, + }, + }, + }) + assert.Nil(t, err) + assert.Equal(t, name, result["common"].(theme.KV)["name"]) + }() + } + wg.Wait() + + assert.Equal(t, "default", defaults["common"].(theme.KV)["name"]) +} + func TestPatchKV(t *testing.T) { in := theme.KV{ "a": map[string]any{ diff --git a/services/web/pkg/theme/service_test.go b/services/web/pkg/theme/service_test.go index 91d858761d..70af28bbc7 100644 --- a/services/web/pkg/theme/service_test.go +++ b/services/web/pkg/theme/service_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "sync" "testing" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" @@ -72,3 +73,70 @@ func TestService_Get(t *testing.T) { // themeDefaults assert.Equal(t, jsonData.Get("common.shareRoles."+unifiedrole.UnifiedRoleViewerID+".name").String(), "UnifiedRoleViewer") } + +func TestService_GetConcurrent(t *testing.T) { + primaryFS := fsx.NewMemMapFs() + fallbackFS := fsx.NewFallbackFS(primaryFS, fsx.NewMemMapFs()) + + add := func(filename string, content any) { + b, err := json.Marshal(content) + assert.Nil(t, err) + + assert.Nil(t, afero.WriteFile(primaryFS, filename, b, 0644)) + } + + // the base themes overlap with the defaults, like the shipped theme.json does + add("a/theme.json", map[string]any{ + "common": map[string]any{ + "name": "a", + "logo": "a.svg", + "shareRoles": map[string]any{ + unifiedrole.UnifiedRoleViewerID: map[string]any{"iconName": "a"}, + }, + }, + }) + add("b/theme.json", map[string]any{ + "common": map[string]any{ + "name": "b", + }, + }) + add("_branding/theme.json", map[string]any{ + "common": map[string]any{ + "slogan": "branding", + }, + }) + + service, _ := theme.NewService( + theme.ServiceOptions{}. + WithThemeFS(fallbackFS). + WithGatewaySelector(mocks.NewSelectable[gateway.GatewayAPIClient](t)), + ) + + get := func(id string) gjson.Result { + r := httptest.NewRequest(http.MethodGet, "/", nil) + r.SetPathValue("id", id) + w := httptest.NewRecorder() + service.Get(w, r) + assert.Equal(t, http.StatusOK, w.Code) + return gjson.Parse(w.Body.String()) + } + + var wg sync.WaitGroup + for i := range 50 { + id := []string{"a", "b"}[i%2] + wg.Add(1) + go func() { + defer wg.Done() + jsonData := get(id) + assert.Equal(t, id, jsonData.Get("common.name").String()) + assert.Equal(t, "branding", jsonData.Get("common.slogan").String()) + }() + } + wg.Wait() + + // values of theme a must never leak into the defaults and therefore into theme b + jsonData := get("b") + assert.Equal(t, "b", jsonData.Get("common.name").String()) + assert.False(t, jsonData.Get("common.logo").Exists()) + assert.Equal(t, "eye", jsonData.Get("common.shareRoles."+unifiedrole.UnifiedRoleViewerID+".iconName").String()) +}