Compare commits

..
Author SHA1 Message Date
Michal Klos 02fb9e8593 feat: text N items in a dir 2026-03-24 12:04:42 +01:00
Paul FaureandClaude Opus 4.6 5ccb09f4d2 test(search): scale SkipDir test to 10,000 directories for pessimistic-case benchmark
Increases the "descends into already-indexed directories" test from 100
to 10,000 directories. Restructures mocks to use map-based dispatch
instead of per-directory mock.MatchedBy registrations, keeping the test
at O(n) instead of O(n²).

Result: 10,000 already-indexed dirs with 10,000 unindexed child files
completes in ~14 seconds, confirming linear scaling.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 16:38:22 -04:00
Paul FaureandClaude Opus 4.6 9bcf14a897 test(search): add unit test for descending into already-indexed directories
Verifies that IndexSpace visits children inside 100 already-indexed
directories whose mtimes match the index.  Before the SkipDir fix
these subtrees would be permanently skipped after an interrupted
reindex run.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 11:07:04 -04:00
Paul FaureandClaude Opus 4.6 0e5233dd50 docs: update changelog with PR number
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 00:28:24 -04:00
Paul FaureandClaude Opus 4.6 2cc1640085 fix(search): always descend into directories during IndexSpace walk
The SkipDir optimization skipped entire subtrees when a directory was
already indexed with a matching mtime. After a failed indexing run
(e.g. Tika crash), this permanently prevented unindexed children from
being visited since the parent directory's mtime doesn't change when
child extraction fails. With O(1) DocID lookups the per-file skip
check is negligible, making SkipDir unnecessary for correctness.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 00:23:36 -04:00
Martin 0cfa1ad3f0 Automated changelog update [skip ci] 2026-03-14 09:04:49 +00:00
Martin eb9fae42fd Merge pull request #12060 from paul43210/fix/uploadready-add-resourceid
[docs-only] fix: add ResourceID field to UploadReady event with file's node ID
2026-03-14 10:02:27 +01:00
Paul FaureandClaude Opus 4.6 4a2004784c docs: add reva #560 link to changelog
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 09:52:46 +01:00
Paul FaureandClaude Opus 4.6 c778609044 fix: add ResourceID field to UploadReady event with file's node ID
The UploadReady event's FileRef.ResourceId.OpaqueId is set to the space
root ID (required for CS3 gateway path resolution via WalkPath). This
means consumers that need the file's actual node ID for Graph API URLs
get the space root instead.

Add a separate ResourceID field (following the BytesReceived pattern)
that carries the file's actual resource identifier with the correct
OpaqueId set to session.NodeID().

Upstream: https://github.com/owncloud/reva/pull/XXXXX

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 09:52:46 +01:00
Martin 3ac19ca463 Merge pull request #12112 from owncloud/fix/ci-codacy-2
fix: ci, codacy, skip artifact upload when no tests run i.e. doc only…
2026-03-13 11:07:30 +01:00
Michal Klos 297a00fc44 fix: ci, codacy, skip artifact upload when no tests run i.e. doc only change 2026-03-13 10:26:25 +01:00
Martin 953dc0f319 Automated changelog update [skip ci] 2026-03-13 08:59:47 +00:00
Martin e687a05800 Merge pull request #12103 from paul43210/fix/search-indexspace-docid-lookup
perf(search): use O(1) DocID lookup instead of full search in IndexSpace
2026-03-13 09:57:18 +01:00
Martin 0c6e574d15 Merge pull request #12104 from paul43210/fix/search-bleve-optimize
enhancement(search): optimize bleve index after bulk reindexing
2026-03-13 09:57:15 +01:00
Paul FaureandClaude Opus 4.6 0d95d40f7c docs: add doc comments to Lookup mock call methods
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 20:37:48 -04:00
kobergj 90655c56a3 Automated changelog update [skip ci] 2026-03-12 07:30:11 +00:00
kobergj dd99e6daf1 Merge pull request #12102 from kobergj/TestBlobstoreCli
Add CLI command to test Blobstore
2026-03-12 08:27:18 +01:00
Paul FaureandClaude Opus 4.6 eb357f820d perf(search): use O(1) DocID lookup instead of full search in IndexSpace
Replace the per-file Search() call in IndexSpace with a direct Lookup()
using Bleve's DocIDQuery. The old approach parsed a KQL query string,
compiled it, and ran a full-text search for each file — taking 600-950ms
per file on large indexes. The new approach does an O(1) document lookup
by ID and compares mtime/Extracted fields in memory.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 07:45:15 +01:00
Paul FaureandClaude Opus 4.6 728a7b4d8d fix: name parameters in forceMerger interface to satisfy inamedparam linter
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 07:44:29 +01:00
Paul FaureandClaude Opus 4.6 6270553209 enhancement(search): optimize bleve index after bulk reindexing
Add an Optimizer optional interface and Bleve.Optimize() method that
triggers ForceMerge to compact all index segments into one. Called
automatically after IndexSpace completes its walk. Over time, writes
create multiple segments that degrade query performance — compaction
consolidates them for faster searches.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 07:44:29 +01:00
Sawjan Gurung 1a5aeeb2e9 Automated changelog update [skip ci] 2026-03-12 05:03:56 +00:00
Sawjan Gurung 39192c7bea ci: use existing servers (#12100)
* ci: enable k8s setup for remaining suites

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* ci: use existing servers

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* ci: fix

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* test: fix tests

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* test: increase timeout

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* ci: fix mail setup

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* test: increase timeout

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* ci: fix tika

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* test: fix csp directives

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* ci: merge ocm provider configs

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* test: fix notification tests

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* ci: fix script file

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* ci: enable ocm server logs

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* ci: fix pattern

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* ci: fix cluster wait

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* ci: run auth-app only when required

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* test: fix sharing tests

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

* test: fix tests

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>

---------

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>
2026-03-12 10:46:13 +05:45
Julian Koberg 15b1c38e38 fix: adjust to comments from CR
Signed-off-by: Julian Koberg <julian.koberg@kiteworks.com>
2026-03-11 08:55:54 +01:00
Martin 0ca881b400 Automated changelog update [skip ci] 2026-03-11 07:49:51 +00:00
Martin c65dff7fac Merge pull request #12070 from paul43210/fix/csp-font-src
fix(proxy): add data: to font-src CSP to allow bundled KaTeX fonts
2026-03-11 08:47:29 +01:00
Paul FaureandClaude Opus 4.6 d4367fb224 fix(proxy): update tests and example configs for font-src data: CSP change
Update acceptance tests and all deployment example CSP configs to include
'data:' in font-src, consistent with the default csp.yaml change.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 22:22:17 -04:00
Julian Koberg 1d2c329e66 feat: add cli command to test the blobstore
Signed-off-by: Julian Koberg <julian.koberg@kiteworks.com>
2026-03-10 16:40:00 +01:00
Paul FaureandClaude Opus 4.6 d8984c4c06 docs: add changelog for CSP font-src fix
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 11:08:52 +01:00
Paul FaureandClaude Opus 4.6 ece1043ca2 fix(proxy): add data: to font-src CSP to allow bundled KaTeX fonts
The bundled Web UI CSS (from owncloud/web) inlines the KaTeX_Size3 font
as a base64 data:font/woff2 URI. The default CSP sets font-src to 'self'
only, which blocks these data URIs and produces a console error on every
page load:

  Loading the font 'data:font/woff2;base64,...' violates the following
  Content Security Policy directive: "font-src 'self'".

Add 'data:' to font-src, matching the existing pattern where img-src
already permits data: URIs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 11:08:52 +01:00
Martin 4fba74c1f7 Automated changelog update [skip ci] 2026-03-10 08:20:45 +00:00
Martin 296609da98 Merge pull request #12095 from paul43210/fix/search-incomplete-extraction
fix(search): prevent incomplete Tika extractions from blocking re-index
2026-03-10 09:18:11 +01:00
Martin 03bfabec55 Merge pull request #12094 from paul43210/feature/kql-numeric-range-queries
feat(kql): support numeric range queries
2026-03-10 09:17:38 +01:00
Michal Klos 983dc5f7b5 fix: X-XSS-Protection header (#12092) 2026-03-10 09:15:35 +01:00
Sawjan Gurung d65dd806de ci: use script to prepare ocis charts (#12081)
ci: fix path



ci: fix wopi servers



ci: conditional resources

Signed-off-by: Saw-jan <saw.jan.grg3e@gmail.com>
2026-03-10 12:58:43 +05:45
Paul FaureandClaude Opus 4.6 b52af29f8e refactor(kql): extract dateTimeQuery helper to further reduce walk() complexity
Extracts DateTimeNode handling into dateTimeQuery(), same pattern as
numericQuery(). Brings walk() cyclomatic complexity from 36 to ~30,
well below the SonarCloud threshold of 35.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 17:45:13 -04:00
Paul FaureandClaude Opus 4.6 b1218d868a docs: add changelog for incomplete extraction fix
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 17:38:23 -04:00
Paul FaureandClaude Opus 4.6 8471094c1d fix(search): prevent incomplete Tika extractions from blocking re-index
Two changes to fix permanently stuck index entries:

1. (Option D) Validate Tika responses: if MetaRecursive() returns an
   empty metadata list, treat it as an error. This prevents Tika HTTP 200
   responses with no actual content from being accepted as successful
   extractions.

2. (Option B) Add Extracted field to Resource: a boolean that is set to
   true only when UpsertItem completes successfully. The IndexSpace skip
   check now requires Extracted:true in addition to matching id+mtime.
   Documents that were written with incomplete extraction data will be
   automatically re-processed on the next reindex.

Background: When Tika returns HTTP 200 but its child processes (OCR,
ImageMagick) fail due to resource limits (EAGAIN, OOM), the Go Tika
client receives metadata headers but no X-TIKA:content. The doc gets
written to Bleve with the correct mtime, and subsequent reindexes skip
it forever because the id+mtime check passes.

Fixes: #12093

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 17:36:30 -04:00
Paul FaureandClaude Opus 4.6 d5e3e16397 refactor(kql): extract numericQuery helper to reduce walk() complexity
Fixes SonarCloud gocyclo finding — walk() cyclomatic complexity
was 40 (threshold 35). Extracted numeric range query building
into a separate numericQuery() function.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 00:16:15 -05:00
Paul FaureandClaude Opus 4.6 4b7349037f feat(kql): support numeric range queries (>=, <=, >, <)
Add NumericRestrictionNode to the KQL PEG grammar so that range
operators work with numeric values, not just DateTimes. This enables
queries like `size>=1048576`, `photo.iso>=100`, `photo.fNumber>=2.8`,
and `photo.focalLength<50`.

Changes:
- ast: add NumericNode with Key, Operator, Value (float64)
- kql/dictionary.peg: add NumericRestrictionNode and Number rules
- kql/factory.go: add buildNumericNode()
- kql/cast.go: add toFloat64()
- bleve/compiler.go: compile NumericNode to NumericRangeQuery

Fixes: #12093

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 23:51:08 -05:00
ownClouders 8b5bffcff9 Automated changelog update [skip ci] 2026-03-08 00:38:03 +00:00
ownClouders 928b8d4823 [tx] updated from transifex 2026-03-08 00:35:19 +00:00
Roman Perekhod 0ee201628c Automated changelog update [skip ci] 2026-03-06 13:07:59 +00:00
Roman Perekhod b5b4d25e45 Merge pull request #12087 from owncloud/feat/bump-reva-ce3149532498
[full-ci] feat: bump reva to latest
2026-03-06 14:05:21 +01:00
kobergj 26587468e7 Merge pull request #12090 from owncloud/DeepDiver1975-patch-1
[full-ci] ci: use plugins/s3:1.4.0
2026-03-06 13:58:06 +01:00
Martin 3fc236be96 Merge pull request #12000 from paul43210/fix/search-skip-tika-reindex
fix(search): skip Tika re-extraction when file content has not changed
2026-03-06 11:39:25 +01:00
Thomas Müller 4106776808 ci: use plugins/s3:1.4.0 2026-03-06 11:20:24 +01:00
Paul FaureandClaude Opus 4.6 1163f51496 fix(search): guard uint64-to-int64 conversion to prevent overflow (gosec G115)
Clamp ContentExtractionSizeLimit to math.MaxInt64 before casting to
int64 for io.LimitReader.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 10:52:30 +01:00
Paul FaureandClaude Opus 4.6 d54727c9ea docs(search): note race condition in engine.Update GoDoc
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 10:52:30 +01:00
Paul FaureandClaude Opus 4.6 329482e8ec refactor(search): address review — tags-only update, sentinel error, GoDoc
- UpdateTags now updates only the tags field instead of all basic
  metadata (name, size, mimetype, path, parentID), per reviewer
  feedback that those are structural fields not metadata.
- Removed refreshMetadata helper that was over-reaching.
- Introduced ErrResourceNotFound sentinel in engine package so
  UpdateTags can distinguish "not indexed" (fallback to UpsertItem)
  from connectivity or other errors (log and stop).
- Added GoDoc example for the Update mutateFn callback.
- Added test for non-retriable error path.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 10:52:30 +01:00
Paul FaureandClaude Opus 4.6 ee9b6f3007 refactor(search): replace Retrieve with Update, remove checksum guard
Address reviewer feedback:
- Remove checksum field from index (bloats index, not searched)
- Remove skipUnchangedContent guard (not needed with UpdateTags path)
- Replace engine.Retrieve() with engine.Update(id, mutateFn) that does
  get+mutate+set internally, avoiding public exposure of raw retrieval
- Simplify UpdateTags to use engine.Update() with mutation function

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 10:52:30 +01:00
Paul FaureandClaude Opus 4.6 dd0d8fe923 refactor(search): extract storeExtractedMetadata to reduce UpsertItem complexity
Moves the metadata-storage block from UpsertItem into a dedicated helper
method to bring cognitive complexity below the SonarCloud threshold of 15.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 10:52:30 +01:00
Paul FaureandClaude Opus 4.6 de7cc1670b refactor(search): extract skipUnchangedContent to reduce cognitive complexity
Move the checksum fast-path logic into a dedicated helper method to
bring UpsertItem below the SonarCloud cognitive complexity threshold
of 15.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 10:52:30 +01:00
Paul FaureandClaude Opus 4.6 d7df509043 test(search): add coverage for checksum fast-path and UpdateTags
Add tests for:
- UpsertItem skips Tika when checksum unchanged
- UpsertItem runs Tika when checksum differs
- UpsertItem runs Tika when resource not yet indexed
- UpdateTags preserves Tika content when resource is indexed
- UpdateTags falls back to full UpsertItem when not indexed

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 10:52:30 +01:00
Paul FaureandClaude Opus 4.6 eaa02c3d4d fix(search): skip Tika re-extraction when file content has not changed
Tag events (TagsAdded/TagsRemoved) previously called UpsertItem which
triggered a full Tika content extraction for metadata-only changes.
Additionally, UpsertItem's SetArbitraryMetadata writeback bumped the
mtime, causing IndexSpace to call UpsertItem again — running Tika
twice per file. On servers with large libraries this caused a
denial-of-service from runaway convert/tesseract processes.

Fix by:
- Adding UpdateTags() to the Searcher interface for tag-only updates
  that preserve existing Tika-extracted content
- Adding Retrieve() to the Engine interface to load indexed resources
- Comparing the content checksum (already computed by decomposedfs on
  upload) in UpsertItem to skip Tika and the metadata writeback when
  the blob has not been written to
- Extracting refreshMetadata() helper shared by both code paths

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 10:52:30 +01:00
Martin f11c315607 Automated changelog update [skip ci] 2026-03-06 09:08:38 +00:00
Martin 1333fe7c13 Merge pull request #12078 from paul43210/fix/search-photo-case-sensitive
fix(search): use case-insensitive analyzer for photo metadata fields
2026-03-06 10:06:05 +01:00
ownClouders cfa5bb9ebc Automated changelog update [skip ci] 2026-03-05 14:48:41 +00:00
ownClouders 23e5bed778 [tx] updated from transifex 2026-03-05 14:45:28 +00:00
ownClouders 7edacfcb0e [tx] updated from transifex 2026-03-05 00:05:30 +00:00
Roman Perekhod 837fff3ab6 feat: bump reva to latest 2026-03-04 16:02:26 +01:00
Paul FaureandClaude Opus 4.6 ceaff680a8 refactor(search): extract lowercaseKeyword analyzer name to constant
Addresses SonarCloud goconst finding — the string "lowercaseKeyword"
appeared 4 times without a named constant.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 22:36:22 -05:00
Paul FaureandClaude Opus 4.6 452f7bce34 docs: update changelog with PR number
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:13:15 -05:00
Paul FaureandClaude Opus 4.6 0e8eb927f3 fix(search): use case-insensitive analyzer for photo metadata fields
Bleve's query string parser lowercases search terms, but the keyword
analyzer stores values as-is. This made photo field searches like
cameraMake:google fail to match "Google". Switch from keyword to
lowercaseKeyword analyzer so both sides are lowercased.

Note: existing Bleve indexes need to be rebuilt after this change.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 21:12:52 -05:00
150 changed files with 4233 additions and 3571 deletions

No files matched your search

+95 -214
View File
@@ -33,7 +33,9 @@ PLUGINS_GH_PAGES = "plugins/gh-pages:1"
PLUGINS_GITHUB_RELEASE = "plugins/github-release:1"
PLUGINS_GIT_ACTION = "plugins/git-action:1"
PLUGINS_MANIFEST = "plugins/manifest:1"
PLUGINS_S3 = "plugins/s3:1"
# 1.4.0 is required due to minio compatibility
PLUGINS_S3 = "plugins/s3:1.4.0"
PLUGINS_S3_CACHE = "plugins/s3-cache:1"
REDIS = "redis:6-alpine"
SONARSOURCE_SONAR_SCANNER_CLI = "sonarsource/sonar-scanner-cli:11.0"
@@ -117,6 +119,7 @@ config = {
],
"skip": False,
"withRemotePhp": [False],
"k8s": True,
"emailNeeded": True,
"extraEnvironment": {
"EMAIL_HOST": EMAIL_SMTP_HOST,
@@ -163,6 +166,7 @@ config = {
"apiActivities",
],
"skip": False,
"k8s": True,
},
"groupAndSearch1": {
"suites": [
@@ -207,6 +211,7 @@ config = {
],
"skip": False,
"withRemotePhp": [False],
"k8s": True,
},
"sharingNgLinkShare": {
"suites": [
@@ -305,6 +310,7 @@ config = {
"NOTIFICATIONS_DEBUG_ADDR": "0.0.0.0:9174",
"ANTIVIRUS_SCANNER_TYPE": "clamav",
"ANTIVIRUS_CLAMAV_SOCKET": "tcp://clamav:3310",
"ANTIVIRUS_DEBUG_ADDR": "0.0.0.0:9277",
"OCIS_ADD_RUN_SERVICES": "antivirus,notifications",
},
},
@@ -370,6 +376,7 @@ config = {
"coreApiWebdavMove2",
],
"skip": False,
"k8s": True,
},
"7": {
"suites": [
@@ -892,6 +899,7 @@ def uploadScanResults(ctx):
"git checkout $DRONE_COMMIT",
],
},
] + skipIfUnchanged(ctx, "unit-tests") + [
{
"name": "sync-from-cache",
"image": MINIO_MC,
@@ -1123,19 +1131,28 @@ def localApiTestPipeline(ctx):
# SETUP STEPS #
####################
setup_steps = skipIfUnchanged(ctx, "acceptance-tests")
if params["tikaNeeded"]:
setup_steps += waitForServices("tika", ["tika:9998"])
if params["antivirusNeeded"]:
setup_steps += waitForServices("clamav", ["clamav:3310"])
if params["emailNeeded"]:
setup_steps += waitForServices("email", ["%s:%s" % (EMAIL_SMTP_HOST, EMAIL_PORT)])
if params["collaborationServiceNeeded"]:
setup_steps += waitForServices("online-offices", ["collabora:9980", "onlyoffice:443", "fakeoffice:8080"])
if run_on_k8s:
enable_auth_app = False
if "OCIS_ADD_RUN_SERVICES" in params["extraServerEnvironment"]:
enable_auth_app = "auth-app" in params["extraServerEnvironment"]["OCIS_ADD_RUN_SERVICES"]
setup_steps += ocisServerK8s(
params["federationServer"],
params["antivirusNeeded"],
params["emailNeeded"],
params["tikaNeeded"],
params["collaborationServiceNeeded"],
enable_auth_app,
)
if params["antivirusNeeded"]:
setup_steps += exposeAntivirusServiceK8s()
if params["emailNeeded"]:
setup_steps += exposeEmailServiceK8s()
if params["collaborationServiceNeeded"]:
setup_steps += exposeNodePortsK8s([
["collaboration-collabora", 9300],
@@ -1145,15 +1162,6 @@ def localApiTestPipeline(ctx):
])
else:
setup_steps += restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin")
if params["tikaNeeded"]:
setup_steps += tikaService()
if params["collaborationServiceNeeded"]:
setup_steps += waitForServices("online-offices", ["collabora:9980", "onlyoffice:443", "fakeoffice:8080"])
if params["antivirusNeeded"]:
setup_steps += waitForClamavService()
if params["emailNeeded"]:
setup_steps += waitForEmailService()
setup_steps += ocisServer(
storage,
extra_server_environment = params["extraServerEnvironment"],
@@ -1178,17 +1186,18 @@ def localApiTestPipeline(ctx):
# SERVICES #
####################
services = []
if params["tikaNeeded"]:
services += tikaService()
if params["emailNeeded"]:
services += emailService()
if params["antivirusNeeded"]:
services += clamavService()
if params["collaborationServiceNeeded"]:
services += fakeOffice() + collaboraService() + onlyofficeService()
if run_on_k8s:
services += k3sCluster(ocm = params["federationServer"])
if params["federationServer"]:
services += k3sCluster(name = FED_OCIS_SERVER_NAME, ocm = True)
else:
if params["emailNeeded"]:
services += emailService()
if params["antivirusNeeded"]:
services += clamavService()
if params["collaborationServiceNeeded"]:
services += fakeOffice() + collaboraService() + onlyofficeService()
####################
# PIPELINE #
@@ -1299,9 +1308,6 @@ def localApiTests(name, suites, storage = "ocis", extra_environment = {}, with_r
}
for item in extra_environment:
if item == "EMAIL_HOST" and k8s:
environment[item] = OCIS_SERVER_NAME
continue
environment[item] = extra_environment[item]
return [{
@@ -1509,23 +1515,20 @@ def coreApiTestPipeline(ctx):
# SETUP STEPS #
####################
setup_steps = skipIfUnchanged(ctx, "acceptance-tests")
if params["tikaNeeded"]:
setup_steps += waitForServices("tika", ["tika:9998"])
if params["antivirusNeeded"]:
setup_steps += waitForServices("clamav", ["clamav:3310"])
if params["emailNeeded"]:
setup_steps += waitForServices("email", ["%s:%s" % (EMAIL_SMTP_HOST, EMAIL_PORT)])
if run_on_k8s:
ocis_url = OCIS_URL_K8S
wrapper_url = "http://ociswrapper:5200"
setup_steps += ocisServerK8s(antivirus = params["antivirusNeeded"], email = params["emailNeeded"])
if params["antivirusNeeded"]:
setup_steps += exposeAntivirusServiceK8s()
if params["emailNeeded"]:
setup_steps += exposeEmailServiceK8s()
else:
setup_steps += restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin")
if params["tikaNeeded"]:
setup_steps += tikaService()
if params["antivirusNeeded"]:
setup_steps += waitForClamavService()
if params["emailNeeded"]:
setup_steps += waitForEmailService()
setup_steps += ocisServer(
storage,
extra_server_environment = params["extraServerEnvironment"],
@@ -1538,13 +1541,14 @@ def coreApiTestPipeline(ctx):
# SERVICES #
####################
services = []
if params["tikaNeeded"]:
services += tikaService()
if params["emailNeeded"]:
services += emailService()
if params["antivirusNeeded"]:
services += clamavService()
if run_on_k8s:
services += k3sCluster()
else:
if params["emailNeeded"]:
services += emailService()
if params["antivirusNeeded"]:
services += clamavService()
####################
# PIPELINE #
@@ -1695,13 +1699,14 @@ def e2eTestPipeline(ctx):
})
services = postgresService() if params["keycloakNeeded"] else []
services += tikaService() if params["tikaNeeded"] else []
steps_before = \
skipIfUnchanged(ctx, "e2e-tests") + \
restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin/ocis") + \
restoreWebCache() + \
restoreWebPnpmCache() + \
(tikaService() if params["tikaNeeded"] else []) + \
(waitForServices("tika", ["tika:9998"]) if params["tikaNeeded"] else []) + \
(keycloakService() if params["keycloakNeeded"] else []) + \
ocisServer(extra_server_environment = extra_server_environment, with_wrapper = not params["keycloakNeeded"], tika_enabled = params["tikaNeeded"], debug = False, external_idp = params["keycloakNeeded"])
@@ -1845,7 +1850,7 @@ def multiServiceE2ePipeline(ctx):
restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin/ocis") + \
restoreWebCache() + \
restoreWebPnpmCache() + \
tikaService() + \
waitForServices("tika", ["tika:9998"]) + \
ocisServer(extra_server_environment = extra_server_environment, tika_enabled = params["tikaNeeded"], debug = False) + \
storage_users_services + \
[{
@@ -1879,6 +1884,7 @@ def multiServiceE2ePipeline(ctx):
},
pipelineVolumeGo,
],
"services": tikaService(),
})
return pipelines
@@ -2863,41 +2869,52 @@ def startOcisService(service = None, name = None, environment = {}, volumes = []
},
]
def ocisServerK8s(federation = False, antivirus = False, email = False, tika = False, wopi = False):
def ocisServerK8s(federation = False, antivirus = False, email = False, tika = False, wopi = False, auth_app = False):
name = OCIS_SERVER_NAME
url = OCIS_URL_K8S
fed_name = FED_OCIS_SERVER_NAME
fed_url = OCIS_FED_URL_K8S
steps = []
expose_ext_server_step = []
external_servers = []
steps = prepareOcisDeployment()
environment = {
"ENABLE_ANTIVIRUS": antivirus,
"ENABLE_EMAIL": email,
"ENABLE_TIKA": tika,
"ENABLE_WOPI": wopi,
"ENABLE_OCM": federation,
"ENABLE_AUTH_APP": auth_app,
}
if antivirus:
steps += enableAntivirusServiceK8s()
if email:
steps += enableEmailServiceK8s()
external_servers.append(["clamav", 3310])
if tika:
steps += enableTikaServiceK8s()
external_servers.append(["tika", 9998])
if email:
external_servers.append([EMAIL_SMTP_HOST, EMAIL_SMTP_PORT])
if wopi:
steps += enableAppsIntegrationK8s()
external_servers += [["collabora", 9980], ["fakeoffice", 8080], ["onlyoffice", 443]]
if external_servers:
expose_ext_server_step = exposeExternalServersK8s(external_servers)
steps += prepareChartsK8s(environment)
steps += waitK3sCluster(name) + \
(waitK3sCluster(fed_name) if federation else []) + \
setupOcisConfigMaps(name) + \
(setupOcisConfigMaps(fed_name) if federation else []) + \
setupConfigMapsK8s(name) + \
(setupConfigMapsK8s(fed_name) if federation else []) + \
expose_ext_server_step + \
deployOcis(name) + \
(deployOcis(fed_name) if federation else []) + \
streamK8sOcisLogs(name) + \
deployOcisK8s(name) + \
(deployOcisK8s(fed_name) if federation else []) + \
streamOcisLogsK8s(name) + \
(streamOcisLogsK8s(fed_name) if federation else []) + \
waitForOcis(name, url) + \
(waitForOcis(fed_name, fed_url) if federation else [])
return steps + ociswrapperK8s(name)
(waitForOcis(fed_name, fed_url) if federation else []) + \
ociswrapperK8s(name)
return steps
def redis():
return [
@@ -3591,30 +3608,12 @@ def emailService():
"image": AXLLENT_MAILPIT,
}]
def waitForEmailService():
return [{
"name": "wait-for-email",
"image": OC_CI_WAIT_FOR,
"commands": [
"wait-for -it email:%s -t 600" % EMAIL_PORT,
],
}]
def clamavService():
return [{
"name": "clamav",
"image": OC_CI_CLAMAVD,
}]
def waitForClamavService():
return [{
"name": "wait-for-clamav",
"image": OC_CI_WAIT_FOR,
"commands": [
"wait-for -it clamav:3310 -t 600",
],
}]
def fakeOffice():
return [
{
@@ -3670,13 +3669,6 @@ def tikaService():
"name": "tika",
"type": "docker",
"image": APACHE_TIKA,
"detach": True,
}, {
"name": "wait-for-tika-service",
"image": OC_CI_WAIT_FOR,
"commands": [
"wait-for -it tika:9998 -t 300",
],
}]
def apiTestFailureLog():
@@ -3965,7 +3957,7 @@ def k3sCluster(name = OCIS_SERVER_NAME, ocm = False):
"mkdir -p %s && chmod 777 %s" % (log_dir, log_dir),
# create cluster
"k3d cluster create %s --api-port %s:33199 " % (name, name) +
"-p '80:80@loadbalancer' -p '443:443@loadbalancer' -p '8025:32025@loadbalancer' -p '9100-9399:30100-30399@loadbalancer' " +
"-p '80:80@loadbalancer' -p '443:443@loadbalancer' -p '9100-9399:30100-30399@loadbalancer' " +
"--k3s-arg '--tls-san=k3d@server:*' --k3s-arg '--disable=metrics-server@server:*' " +
"-v %s:/logs" % log_dir,
# wait for services to be ready
@@ -4018,56 +4010,28 @@ def waitK3sCluster(name = OCIS_SERVER_NAME):
"image": K3D_IMAGE,
"user": "root",
"commands": [
"export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-" + OCIS_SERVER_NAME + ".yaml",
"export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name,
"timeout 300 bash -c 'until test -f $${KUBECONFIG}; do sleep 1; done'",
"kubectl config view",
"kubectl get pods -A",
],
}]
def prepareOcisDeployment():
def prepareChartsK8s(environment = []):
commands = [
# build ocis wrapper
"make -C %s build" % dirs["ocisWrapper"],
# get ocis charts
"if [ ! -d %s/ocis-charts ]; then git clone --single-branch -b main --depth 1 https://github.com/owncloud/ocis-charts.git; fi" % dirs["base"],
# move CI values file
"mv %s/tests/config/drone/k8s/values.yaml %s/ocis-charts/charts/ocis/ci/deployment-values.yaml" % (dirs["base"], dirs["base"]),
# enable authbasic service
"cp -r %s/tests/config/drone/k8s/authbasic %s/ocis-charts/charts/ocis/templates/" % (dirs["base"], dirs["base"]),
# copy override template
"cp tests/config/drone/k8s/_zoverride.tpl ocis-charts/charts/ocis/templates/_common/",
"cd ocis-charts",
# patch activitylog service
"sed -i '/env:/a\\\\{{- include \"ocis.caEnv\" $ | nindent 12}}' ./charts/ocis/templates/activitylog/deployment.yaml",
"sed -i '/volumeMounts:/a\\\\{{- include \"ocis.caPath\" $ | nindent 12}}' ./charts/ocis/templates/activitylog/deployment.yaml",
"sed -i '/volumes:/a\\\\{{- include \"ocis.caVolume\" $ | nindent 8}}' ./charts/ocis/templates/activitylog/deployment.yaml",
# disable audit logs in console
"sed -i '/AUDIT_LOG_TO_CONSOLE/{n;s/true/false/;}' ./charts/ocis/templates/audit/deployment.yaml",
"sed -i '/{{- define \"ocis.basicServiceTemplates\" -}}/a\\\\ {{- $_ := set .scope \"appNameAuthBasic\" \"authbasic\" -}}' ./charts/ocis/templates/_common/_tplvalues.tpl",
"sed -i '/- name: IDM_ADMIN_PASSWORD/{n;N;N;N;d;}' ./charts/ocis/templates/idm/deployment.yaml",
"sed -i '/- name: IDM_ADMIN_PASSWORD/a\\\\\\n value: \"admin\"' ./charts/ocis/templates/idm/deployment.yaml",
"sed -i '/- name: STORAGE_PUBLICLINK_DEBUG_ADDR/i\\\\ {{- include \"ocis.persistentStore\" . | nindent 12 }}\\\n' ./charts/ocis/templates/storagepubliclink/deployment.yaml",
"sed -i '/- name: PROXY_HTTP_ADDR/i\\\\ - name: PROXY_ENABLE_BASIC_AUTH\\\n value: \"true\"' ./charts/ocis/templates/proxy/deployment.yaml",
"sed -i 's|/etc/ocis/sharing-banned-passwords.txt|config/drone/banned-password-list.txt|' ./charts/ocis/templates/sharing/deployment.yaml",
"sed -i 's|- name: configs|- name: banned-passwords|' ./charts/ocis/templates/sharing/deployment.yaml",
"sed -i 's|mountPath: /etc/ocis$|mountPath: /etc/ocis/config/drone|' ./charts/ocis/templates/sharing/deployment.yaml",
"sed -i 's|name: sharing-banned-passwords-{{ .appName }}|name: sharing-banned-passwords|' ./charts/ocis/templates/sharing/deployment.yaml",
"sed -i 's|/etc/ocis/sharing-banned-passwords.txt|config/drone/banned-password-list.txt|' ./charts/ocis/templates/frontend/deployment.yaml",
"sed -i 's|- name: configs|- name: banned-passwords|' ./charts/ocis/templates/frontend/deployment.yaml",
"sed -i 's|mountPath: /etc/ocis$|mountPath: /etc/ocis/config/drone|' ./charts/ocis/templates/frontend/deployment.yaml",
"sed -i 's|name: sharing-banned-passwords-{{ .appName }}|name: sharing-banned-passwords|' ./charts/ocis/templates/frontend/deployment.yaml",
# Patch thumbnails deployment to mount Unicode fonts (ConfigMaps created in k3sCluster)
"sed -i '/- name: THUMBNAILS_TRANSFER_TOKEN/i\\\\ - name: THUMBNAILS_TXT_FONTMAP_FILE\\\n value: /etc/ocis/fontsMap.json\\\n' ./charts/ocis/templates/thumbnails/deployment.yaml",
"sed -i '/volumeMounts:/a\\\\ - name: ocis-fonts-ttf\\\n mountPath: /etc/ocis/fonts\\\n - name: ocis-fonts-map\\\n mountPath: /etc/ocis/fontsMap.json\\\n subPath: fontsMap.json' ./charts/ocis/templates/thumbnails/deployment.yaml",
"sed -i '/volumes:/a\\\\ - name: ocis-fonts-ttf\\\n configMap:\\\n name: ocis-fonts-ttf\\\n - name: ocis-fonts-map\\\n configMap:\\\n name: ocis-fonts-map' ./charts/ocis/templates/thumbnails/deployment.yaml",
"sed -i -E 's|value: http:\\\\/\\\\/.*:9300|value: {{ $officeSuite.wopiSrc }}|' ./charts/ocis/templates/collaboration/deployment.yaml",
"cat ./charts/ocis/templates/collaboration/deployment.yaml",
"[ ! -d %s/ocis-charts ] && " % dirs["base"] +
"git clone --single-branch -b main --depth 1 https://github.com/owncloud/ocis-charts.git",
# prepare charts for the tests
"bash %s/tests/config/drone/k8s/setup.sh %s/ocis-charts" % (dirs["base"], dirs["base"]),
]
return [{
"name": "prepare-ocis-deployment",
"image": OC_CI_GOLANG,
"environment": environment,
"commands": commands,
"volumes": [
{
@@ -4077,18 +4041,15 @@ def prepareOcisDeployment():
],
}]
def setupOcisConfigMaps(name = OCIS_SERVER_NAME):
def setupConfigMapsK8s(name = OCIS_SERVER_NAME):
step_name = "setup-configmaps-" + name
commands = [
"export KUBECONFIG=%s/kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % (dirs["base"], name),
# Create namespace for oCIS deployment
"kubectl create namespace ocis || true",
"kubectl create configmap -n ocis sharing-banned-passwords --from-file=banned-password-list.txt=%s/tests/config/drone/banned-password-list.txt" % dirs["base"],
# Setup Unicode font support for thumbnails - create ConfigMaps
"echo '{\"defaultFont\": \"/etc/ocis/fonts/NotoSans.ttf\"}' > %s/fontsMap.json" % dirs["base"],
"kubectl create configmap -n ocis ocis-fonts-ttf --from-file=%s/tests/config/drone/NotoSans.ttf" % dirs["base"],
"kubectl create configmap -n ocis ocis-fonts-map --from-file=%s/fontsMap.json" % dirs["base"],
]
return [{
@@ -4098,39 +4059,27 @@ def setupOcisConfigMaps(name = OCIS_SERVER_NAME):
"commands": commands,
}]
def deployOcis(name = OCIS_SERVER_NAME):
def deployOcisK8s(name = OCIS_SERVER_NAME):
step_name = "deploy-" + name
commands = [
"export KUBECONFIG=%s/kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % (dirs["base"], name),
"cd %s/ocis-charts" % dirs["base"],
]
if name == FED_OCIS_SERVER_NAME:
commands.extend([
"sed -i 's|externalDomain: ocis-server|externalDomain: %s|' ./charts/ocis/ci/deployment-values.yaml" % FED_OCIS_SERVER_NAME,
])
commands.extend([
# [NOTE]
# Remove schema validation to add extra configs in values.yaml.
# Also this allows us to use fakeoffice as web-office server
"rm ./charts/ocis/values.schema.json",
"make helm-install-atomic",
])
return [{
"name": step_name,
"image": OC_CI_GOLANG,
"commands": commands,
"volumes": [
{
"name": "gopath",
"path": "/go",
},
"commands": [
"export KUBECONFIG=%s/kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % (dirs["base"], name),
"cd %s/ocis-charts" % dirs["base"],
# update external domain
"sed -i 's|externalDomain:.*|externalDomain: %s|' ./charts/ocis/ci/deployment-values.yaml" % name,
# [NOTE]
# Remove schema validation to add extra configs in values.yaml.
# Also this allows us to use fakeoffice as web-office server
"rm ./charts/ocis/values.schema.json || true",
# deploy ocis
"make helm-install-atomic",
],
}]
def streamK8sOcisLogs(name = OCIS_SERVER_NAME):
def streamOcisLogsK8s(name = OCIS_SERVER_NAME):
return [{
"name": "%s-logs" % name,
"image": OC_CI_ALPINE,
@@ -4141,62 +4090,6 @@ def streamK8sOcisLogs(name = OCIS_SERVER_NAME):
],
}]
def enableAntivirusServiceK8s():
return [{
"name": "enable-antivirus-service",
"image": OC_CI_ALPINE,
"commands": [
"cp -r %s/tests/config/drone/k8s/clamav %s/ocis-charts/charts/ocis/templates/" % (dirs["base"], dirs["base"]),
"sed -i '/^ virusscan:/,/^ *[^ ]/ s/enabled: .*/enabled: true/' %s/ocis-charts/charts/ocis/ci/deployment-values.yaml" % dirs["base"],
"sed -i '/name: ANTIVIRUS_SCANNER_TYPE/{n;s/value: *\"icap\"/value: \"clamav\"/}' %s/ocis-charts/charts/ocis/templates/antivirus/deployment.yaml" % dirs["base"],
"sed -i '/- name: ANTIVIRUS_SCANNER_TYPE/i\\\\ - name: ANTIVIRUS_CLAMAV_SOCKET\\\n value: \"tcp://clamav:3310\"' %s/ocis-charts/charts/ocis/templates/antivirus/deployment.yaml" % dirs["base"],
],
}]
def enableAppsIntegrationK8s():
return [{
"name": "enable-apps-integration",
"image": OC_CI_ALPINE,
"commands": [
"sed -i '/^ appsIntegration:/,/^ *[^ ]/ s/enabled: .*/enabled: true/' %s/ocis-charts/charts/ocis/ci/deployment-values.yaml" % dirs["base"],
],
}]
def enableEmailServiceK8s():
return [{
"name": "copy-%s-service" % EMAIL_SMTP_HOST,
"image": OC_CI_ALPINE,
"commands": [
"cp -r %s/tests/config/drone/k8s/mailpit %s/ocis-charts/charts/ocis/templates/" % (dirs["base"], dirs["base"]),
],
}]
def exposeEmailServiceK8s(name = OCIS_SERVER_NAME):
return [{
"name": EMAIL_SMTP_HOST,
"image": K3D_IMAGE,
"commands": [
"export KUBECONFIG=%s/kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % (dirs["base"], name),
"until test -f $${KUBECONFIG}; do sleep 1s; done",
"kubectl -n ocis expose deployment mailpit --type=NodePort --port=8025 --name=mailpit-np",
"kubectl -n ocis patch svc mailpit-np -p '{\"spec\":{\"ports\":[{\"port\":8025,\"nodePort\":32025,\"targetPort\":8025}]}}'",
],
"detach": True,
}]
def exposeAntivirusServiceK8s(name = OCIS_SERVER_NAME):
return [{
"name": "expose-antivirus-service",
"image": K3D_IMAGE,
"commands": [
"export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name,
"until test -f $${KUBECONFIG}; do sleep 1s; done",
# expose antivirus service via NodePort
"kubectl -n ocis expose deployment antivirus --type=NodePort --port=9277 --name=antivirus-np",
"kubectl -n ocis patch svc antivirus-np -p '{\"spec\":{\"ports\":[{\"port\":9277,\"nodePort\":30277}]}}'",
],
}]
def ociswrapperK8s(name = OCIS_SERVER_NAME, ocis_url = OCIS_URL_K8S):
return [{
"name": "ociswrapper",
@@ -4217,18 +4110,6 @@ def ociswrapperK8s(name = OCIS_SERVER_NAME, ocis_url = OCIS_URL_K8S):
],
}]
def enableTikaServiceK8s():
return [{
"name": "tika",
"type": "docker",
"image": OC_CI_ALPINE,
"commands": [
"until test -f %s/ocis-charts/charts/ocis/templates/search/deployment.yaml; do sleep 1s; done" % dirs["base"],
"cp -r %s/tests/config/drone/k8s/tika %s/ocis-charts/charts/ocis/templates/" % (dirs["base"], dirs["base"]),
"sed -i '/^[[:space:]]*storagesystem:/i\\\\ search:\\\n extractor:\\\n type: \"tika\"\\\n tika:\\\n url: \"http://tika:9998\"\\\n persistence:\\\n enabled: true\\\n accessModes:\\\n - ReadWriteOnce' %s/ocis-charts/charts/ocis/ci/deployment-values.yaml" % dirs["base"],
],
}]
def exposeNodePortsK8s(services = [], name = OCIS_SERVER_NAME):
commands = []
for idx, service in enumerate(services):
+3 -1
View File
@@ -64,4 +64,6 @@ go.work.sum
.envrc
CLAUDE.md
.claude/
.agents/
# charts
ocis-charts/
+141
View File
@@ -69,6 +69,7 @@ The following sections list the changes for unreleased.
## Summary
* Security - Add X-XSS-Protection header: [#12092](https://github.com/owncloud/ocis/pull/12092)
* Bugfix - Fix postprocessing resume command --restart flag: [#11692](https://github.com/owncloud/ocis/issues/11692)
* Bugfix - Don't use hardcoded groupOfNames in group creation: [#11776](https://github.com/owncloud/ocis/pull/11776)
* Bugfix - Translation for some email notifications: [#11979](https://github.com/owncloud/ocis/pull/11979)
@@ -76,15 +77,34 @@ The following sections list the changes for unreleased.
* Bugfix - Extract metadata from oversized files and fix ISO field: [#12000](https://github.com/owncloud/ocis/pull/12000)
* Bugfix - Make tag unassignment idempotent and handle publish failures: [#12001](https://github.com/owncloud/ocis/pull/12001)
* Bugfix - Expose the signature-auth attribute: [#12016](https://github.com/owncloud/ocis/pull/12016)
* Bugfix - Fix CSP blocking bundled KaTeX font: [#12070](https://github.com/owncloud/ocis/pull/12070)
* Bugfix - Fix case-sensitive photo metadata search: [#12078](https://github.com/owncloud/ocis/pull/12078)
* Bugfix - Prevent incomplete Tika extractions from permanently blocking re-index: [#12095](https://github.com/owncloud/ocis/pull/12095)
* Bugfix - Use O(1) document lookup instead of full search during reindexing: [#12096](https://github.com/owncloud/ocis/pull/12096)
* Enhancement - Add web extensions deployment configuration: [#11940](https://github.com/owncloud/ocis/pull/11940)
* Enhancement - Add AI-assisted development guide: [#11941](https://github.com/owncloud/ocis/pull/11941)
* Enhancement - Bump Web to 12.3.1: [#12015](https://github.com/owncloud/ocis/pull/12015)
* Enhancement - Add space ID to incoming shares: [#12024](https://github.com/owncloud/ocis/pull/12024)
* Enhancement - Add spaceid to REPORT: [#12028](https://github.com/owncloud/ocis/pull/12028)
* Enhancement - Bump Reva version: [#12051](https://github.com/owncloud/ocis/pull/12051)
* Enhancement - Add ResourceID field to UploadReady event: [#12060](https://github.com/owncloud/ocis/pull/12060)
* Enhancement - Support numeric range queries in KQL: [#12094](https://github.com/owncloud/ocis/pull/12094)
* Enhancement - Add blobstore CLI commands to storage-users service: [#12102](https://github.com/owncloud/ocis/pull/12102)
* Enhancement - Optimize search index after bulk reindexing: [#12104](https://github.com/owncloud/ocis/pull/12104)
## Details
* Security - Add X-XSS-Protection header: [#12092](https://github.com/owncloud/ocis/pull/12092)
Added the X-XSS-Protection header set to "0" to explicitly disable the
deprecated browser XSS filter, which can introduce side-channel vulnerabilities.
Modern XSS protection is provided through the Content-Security-Policy header.
This change addresses security audit findings requiring explicit configuration
of HTTP security headers per OWASP recommendations.
https://github.com/owncloud/ocis/pull/12092
* Bugfix - Fix postprocessing resume command --restart flag: [#11692](https://github.com/owncloud/ocis/issues/11692)
The `--restart` / `-r` flag for `ocis postprocessing resume` was broken due to a
@@ -162,6 +182,63 @@ The following sections list the changes for unreleased.
https://github.com/owncloud/ocis/pull/12016
* Bugfix - Fix CSP blocking bundled KaTeX font: [#12070](https://github.com/owncloud/ocis/pull/12070)
The default Content Security Policy blocked the bundled KaTeX math font (used by
the md-editor) because it is inlined as a `data:` URI in the Web UI CSS. Added
`data:` to the `font-src` directive to resolve the console error on every page
load. Users with custom CSP files (`PROXY_CSP_CONFIG_FILE_LOCATION`) will need
to add `data:` to their `font-src` directive manually.
https://github.com/owncloud/ocis/pull/12070
* Bugfix - Fix case-sensitive photo metadata search: [#12078](https://github.com/owncloud/ocis/pull/12078)
Searching for photo metadata fields like camera make/model was case-sensitive,
so searching for "google" would not match a camera make stored as "Google".
Changed the photo string field analyzer from `keyword` to `lowercaseKeyword` so
both indexed values and search terms are lowercased. Existing Bleve indexes need
to be rebuilt after this change.
https://github.com/owncloud/ocis/pull/12078
* Bugfix - Prevent incomplete Tika extractions from permanently blocking re-index: [#12095](https://github.com/owncloud/ocis/pull/12095)
When Tika returned HTTP 200 but its child processes (OCR, ImageMagick) failed
due to resource limits, the search index received metadata but no content. The
document was written to Bleve with the correct mtime, and subsequent reindexes
skipped it because the id+mtime check passed. This left files permanently stuck
as "indexed" with no searchable content.
Two fixes are applied:
1. Validate Tika responses: if `MetaRecursive()` returns an empty metadata list,
it is now treated as an extraction error so the document is not written to the
index.
2. Add an `Extracted` field to indexed resources. It is set to `true` only after
successful extraction. The reindex skip check now requires `Extracted:true`, so
incompletely indexed documents are automatically re-processed on the next
reindex run.
Note: existing search indexes will trigger a full re-extraction on the next
reindex because documents written before this change lack the `Extracted` field.
https://github.com/owncloud/ocis/issues/12093
https://github.com/owncloud/ocis/pull/12095
* Bugfix - Use O(1) document lookup instead of full search during reindexing: [#12096](https://github.com/owncloud/ocis/pull/12096)
The `IndexSpace` bulk reindexer was using a full KQL search query per file to
check whether re-extraction was needed. On large indexes this query took
600–950ms each, making a 61,000-file space take ~13.5 hours just to walk.
Replaced the per-file `Search()` call with an O(1) `Lookup()` using Bleve's
`DocIDQuery`, then comparing mtime and extraction status in memory. This reduces
per-file check time from ~800ms to <1ms.
https://github.com/owncloud/ocis/issues/12093
https://github.com/owncloud/ocis/pull/12096
* Enhancement - Add web extensions deployment configuration: [#11940](https://github.com/owncloud/ocis/pull/11940)
We added deployment configuration for the photo-addon and advanced-search web
@@ -211,6 +288,70 @@ The following sections list the changes for unreleased.
Bumped reva version
https://github.com/owncloud/ocis/pull/12051
https://github.com/owncloud/ocis/pull/12087
* Enhancement - Add ResourceID field to UploadReady event: [#12060](https://github.com/owncloud/ocis/pull/12060)
The UploadReady NATS event now includes a `ResourceID` field containing the
file's actual resource identifier (with the correct node OpaqueId). Previously,
only `FileRef` was available, whose `ResourceId.OpaqueId` is set to the space
root ID (required for CS3 gateway path resolution). Consumers that need the
file's unique identifier for Graph API or WebDAV operations can now use
`ResourceID.OpaqueId` directly.
https://github.com/owncloud/ocis/issues/12056
https://github.com/owncloud/ocis/pull/12060
https://github.com/owncloud/reva/pull/547
https://github.com/owncloud/reva/pull/560
* Enhancement - Support numeric range queries in KQL: [#12094](https://github.com/owncloud/ocis/pull/12094)
The KQL parser now supports numeric range queries using comparison operators
(>=, <=, >, <) on numeric fields. Previously, range operators only worked with
DateTime values, causing queries like `size>=1048576` or `photo.iso>=100` to
silently fail by falling through to free-text search.
Affected numeric fields: Size, photo.iso, photo.fNumber, photo.focalLength,
photo.orientation.
https://github.com/owncloud/ocis/issues/12093
https://github.com/owncloud/ocis/pull/12094
* Enhancement - Add blobstore CLI commands to storage-users service: [#12102](https://github.com/owncloud/ocis/pull/12102)
Added two new CLI commands under `ocis storage-users blobstore` to help
operators verify and inspect the configured blobstore without needing direct
access to the underlying storage system.
`blobstore check` performs a full upload/download/delete round-trip using a
random payload. The payload size is configurable via `--blob-size` and accepts
human-readable values such as `64`, `1KB` or `4MiB` (default: 64 bytes).
`blobstore get` downloads a specific blob by its ID to verify it is readable.
The blob can be identified either with `--blob-id` and `--space-id`, or by
passing the raw blob path from a log line directly via `--path`. Both the s3ng
key format (`<spaceID>/<pathified_blobID>`) and the ocis filesystem path format
(`…/spaces/<pathified_spaceID>/blobs/<pathified_blobID>`) are accepted. When
using the s3ng driver without a known blob size, an automatic retry with the
actual size is performed on a size mismatch.
Both commands read the existing service configuration, so they always target the
same blobstore as the running service. Only the `ocis` and `s3ng` storage
drivers are supported.
https://github.com/owncloud/ocis/pull/12102
* Enhancement - Optimize search index after bulk reindexing: [#12104](https://github.com/owncloud/ocis/pull/12104)
After an `IndexSpace` walk completes, the search engine now triggers a segment
merge (compaction) on the bleve index. Over time, writes create multiple index
segments that degrade query performance. The new `Optimize()` method calls
bleve's `ForceMerge` to consolidate all segments into one, improving subsequent
search and lookup speed. This is especially beneficial after bulk reindexing
large spaces.
https://github.com/owncloud/ocis/issues/12093
https://github.com/owncloud/ocis/pull/12104
# Changelog for [8.0.0] (2026-02-13)
+1
View File
@@ -3,4 +3,5 @@ Enhancement: Bump Reva version
bumped reva version
https://github.com/owncloud/ocis/pull/12051
https://github.com/owncloud/ocis/pull/12087
@@ -0,0 +1,13 @@
Enhancement: Support numeric range queries in KQL
The KQL parser now supports numeric range queries using comparison
operators (>=, <=, >, <) on numeric fields. Previously, range operators
only worked with DateTime values, causing queries like `size>=1048576`
or `photo.iso>=100` to silently fail by falling through to free-text
search.
Affected numeric fields: Size, photo.iso, photo.fNumber,
photo.focalLength, photo.orientation.
https://github.com/owncloud/ocis/pull/12094
https://github.com/owncloud/ocis/issues/12093
@@ -0,0 +1,11 @@
Enhancement: Optimize search index after bulk reindexing
After an `IndexSpace` walk completes, the search engine now triggers a
segment merge (compaction) on the bleve index. Over time, writes create
multiple index segments that degrade query performance. The new
`Optimize()` method calls bleve's `ForceMerge` to consolidate all
segments into one, improving subsequent search and lookup speed. This is
especially beneficial after bulk reindexing large spaces.
https://github.com/owncloud/ocis/pull/12104
https://github.com/owncloud/ocis/issues/12093
@@ -0,0 +1,24 @@
Enhancement: Add blobstore CLI commands to storage-users service
Added two new CLI commands under `ocis storage-users blobstore` to help
operators verify and inspect the configured blobstore without needing
direct access to the underlying storage system.
`blobstore check` performs a full upload/download/delete round-trip using
a random payload. The payload size is configurable via `--blob-size` and
accepts human-readable values such as `64`, `1KB` or `4MiB` (default: 64 bytes).
`blobstore get` downloads a specific blob by its ID to verify it is
readable. The blob can be identified either with `--blob-id` and
`--space-id`, or by passing the raw blob path from a log line directly
via `--path`. Both the s3ng key format
(`<spaceID>/<pathified_blobID>`) and the ocis filesystem path format
(`…/spaces/<pathified_spaceID>/blobs/<pathified_blobID>`) are accepted.
When using the s3ng driver without a known blob size, an automatic retry
with the actual size is performed on a size mismatch.
Both commands read the existing service configuration, so they always
target the same blobstore as the running service. Only the `ocis` and
`s3ng` storage drivers are supported.
https://github.com/owncloud/ocis/pull/12102
+5
View File
@@ -0,0 +1,5 @@
Bugfix: Fix CSP blocking bundled KaTeX font
The default Content Security Policy blocked the bundled KaTeX math font (used by the md-editor) because it is inlined as a `data:` URI in the Web UI CSS. Added `data:` to the `font-src` directive to resolve the console error on every page load. Users with custom CSP files (`PROXY_CSP_CONFIG_FILE_LOCATION`) will need to add `data:` to their `font-src` directive manually.
https://github.com/owncloud/ocis/pull/12070
@@ -0,0 +1,26 @@
Bugfix: Prevent incomplete Tika extractions from permanently blocking re-index
When Tika returned HTTP 200 but its child processes (OCR, ImageMagick)
failed due to resource limits, the search index received metadata but
no content. The document was written to Bleve with the correct mtime,
and subsequent reindexes skipped it because the id+mtime check passed.
This left files permanently stuck as "indexed" with no searchable
content.
Two fixes are applied:
1. Validate Tika responses: if `MetaRecursive()` returns an empty
metadata list, it is now treated as an extraction error so the
document is not written to the index.
2. Add an `Extracted` field to indexed resources. It is set to `true`
only after successful extraction. The reindex skip check now requires
`Extracted:true`, so incompletely indexed documents are automatically
re-processed on the next reindex run.
Note: existing search indexes will trigger a full re-extraction on the
next reindex because documents written before this change lack the
`Extracted` field.
https://github.com/owncloud/ocis/pull/12095
https://github.com/owncloud/ocis/issues/12093
@@ -0,0 +1,11 @@
Bugfix: Use O(1) document lookup instead of full search during reindexing
The `IndexSpace` bulk reindexer was using a full KQL search query per file
to check whether re-extraction was needed. On large indexes this query
took 600–950ms each, making a 61,000-file space take ~13.5 hours just to
walk. Replaced the per-file `Search()` call with an O(1) `Lookup()` using
Bleve's `DocIDQuery`, then comparing mtime and extraction status in memory.
This reduces per-file check time from ~800ms to <1ms.
https://github.com/owncloud/ocis/pull/12096
https://github.com/owncloud/ocis/issues/12093
@@ -0,0 +1,5 @@
Bugfix: Fix case-sensitive photo metadata search
Searching for photo metadata fields like camera make/model was case-sensitive, so searching for "google" would not match a camera make stored as "Google". Changed the photo string field analyzer from `keyword` to `lowercaseKeyword` so both indexed values and search terms are lowercased. Existing Bleve indexes need to be rebuilt after this change.
https://github.com/owncloud/ocis/pull/12078
@@ -0,0 +1,11 @@
Bugfix: Always descend into directories during space reindexing
The search indexer's `IndexSpace` walk previously used `filepath.SkipDir`
to skip entire directory subtrees when the directory itself was already
indexed. After a failed or interrupted indexing run (e.g. Tika crash),
this caused thousands of unindexed files to be permanently skipped
because the parent directory's mtime had not changed. The indexer now
always descends into directories, relying on the O(1) per-file DocID
lookup to skip already-indexed files efficiently.
https://github.com/owncloud/ocis/pull/12119
@@ -0,0 +1,11 @@
Security: Add X-XSS-Protection header
Added the X-XSS-Protection header set to "0" to explicitly disable the
deprecated browser XSS filter, which can introduce side-channel
vulnerabilities. Modern XSS protection is provided through the
Content-Security-Policy header.
This change addresses security audit findings requiring explicit
configuration of HTTP security headers per OWASP recommendations.
https://github.com/owncloud/ocis/pull/12092
@@ -0,0 +1,13 @@
Enhancement: Add ResourceID field to UploadReady event
The UploadReady NATS event now includes a `ResourceID` field containing the
file's actual resource identifier (with the correct node OpaqueId). Previously,
only `FileRef` was available, whose `ResourceId.OpaqueId` is set to the space
root ID (required for CS3 gateway path resolution). Consumers that need the
file's unique identifier for Graph API or WebDAV operations can now use
`ResourceID.OpaqueId` directly.
https://github.com/owncloud/ocis/pull/12060
https://github.com/owncloud/ocis/issues/12056
https://github.com/owncloud/reva/pull/547
https://github.com/owncloud/reva/pull/560
@@ -13,6 +13,7 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''self'''
frame-src:
@@ -11,6 +11,7 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''none'''
frame-src:
@@ -10,6 +10,7 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''self'''
frame-src:
@@ -11,6 +11,7 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''none'''
frame-src:
@@ -9,6 +9,7 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''self'''
frame-src:
@@ -9,6 +9,7 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''self'''
frame-src:
@@ -9,6 +9,7 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''self'''
frame-src:
+1 -1
View File
@@ -64,7 +64,7 @@ require (
github.com/open-policy-agent/opa v1.12.3
github.com/orcaman/concurrent-map v1.0.0
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
github.com/owncloud/reva/v2 v2.0.0-20260303153746-059bcdfc4fbb
github.com/owncloud/reva/v2 v2.0.0-20260304131727-ce3149532498
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.23.2
+2 -2
View File
@@ -742,8 +742,8 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
github.com/owncloud/reva/v2 v2.0.0-20260303153746-059bcdfc4fbb h1:+g9i1ZCb5EAufhjX967R2Zkw3UtgKk6XfXNQ4LQg9iE=
github.com/owncloud/reva/v2 v2.0.0-20260303153746-059bcdfc4fbb/go.mod h1:+rCy6oGYb2/qs5gmQa8y/pHARw634vB73MZGDY2SBIQ=
github.com/owncloud/reva/v2 v2.0.0-20260304131727-ce3149532498 h1:ozyudPff1XLWSeTDW4ajT1tCoSQf18cFQRxtLWFCNbk=
github.com/owncloud/reva/v2 v2.0.0-20260304131727-ce3149532498/go.mod h1:+rCy6oGYb2/qs5gmQa8y/pHARw634vB73MZGDY2SBIQ=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pablodz/inotifywaitgo v0.0.9 h1:njquRbBU7fuwIe5rEvtaniVBjwWzcpdUVptSgzFqZsw=
+12
View File
@@ -60,6 +60,14 @@ type DateTimeNode struct {
Value time.Time
}
// NumericNode represents a float64 value with a comparison operator
type NumericNode struct {
*Base
Key string
Operator *OperatorNode
Value float64
}
// OperatorNode represents an operator value like
// AND, OR, NOT, =, <= ... and so on
type OperatorNode struct {
@@ -81,6 +89,8 @@ func NodeKey(n Node) string {
return node.Key
case *DateTimeNode:
return node.Key
case *NumericNode:
return node.Key
case *BooleanNode:
return node.Key
case *GroupNode:
@@ -97,6 +107,8 @@ func NodeValue(n Node) interface{} {
return node.Value
case *DateTimeNode:
return node.Value
case *NumericNode:
return node.Value
case *BooleanNode:
return node.Value
case *GroupNode:
+1
View File
@@ -21,6 +21,7 @@ func DiffAst(x, y interface{}, opts ...cmp.Option) string {
cmpopts.IgnoreFields(ast.GroupNode{}, "Base"),
cmpopts.IgnoreFields(ast.BooleanNode{}, "Base"),
cmpopts.IgnoreFields(ast.DateTimeNode{}, "Base"),
cmpopts.IgnoreFields(ast.NumericNode{}, "Base"),
)...,
)
}
+11 -1
View File
@@ -2,6 +2,7 @@ package kql
import (
"fmt"
"strconv"
"time"
"github.com/jinzhu/now"
@@ -25,7 +26,7 @@ func toNodes[T ast.Node](in interface{}) ([]T, error) {
return []T{v}, nil
case []T:
return v, nil
case []*ast.OperatorNode, []*ast.DateTimeNode:
case []*ast.OperatorNode, []*ast.DateTimeNode, []*ast.NumericNode:
return toNodes[T](v)
case []interface{}:
var nodes []T
@@ -70,6 +71,15 @@ func toString(in interface{}) (string, error) {
}
}
func toFloat64(in interface{}) (float64, error) {
s, err := toString(in)
if err != nil {
return 0, err
}
return strconv.ParseFloat(s, 64)
}
func toTime(in interface{}) (time.Time, error) {
ts, err := toString(in)
if err != nil {
+16
View File
@@ -40,6 +40,7 @@ GroupNode <-
PropertyRestrictionNodes <-
YesNoPropertyRestrictionNode /
DateTimeRestrictionNode /
NumericRestrictionNode /
TextPropertyRestrictionNode
YesNoPropertyRestrictionNode <-
@@ -69,6 +70,16 @@ DateTimeRestrictionNode <-
return buildNaturalLanguageDateTimeNodes(k, v, c.text, c.pos)
}
NumericRestrictionNode <-
k:Char+ o:(
OperatorGreaterOrEqualNode /
OperatorLessOrEqualNode /
OperatorGreaterNode /
OperatorLessNode
) v:Number {
return buildNumericNode(k, o, v, c.text, c.pos)
}
TextPropertyRestrictionNode <-
k:Char+ (OperatorColonNode / OperatorEqualNode) v:(String / [^ ()]+){
return buildStringNode(k, v, c.text, c.pos)
@@ -224,6 +235,11 @@ String <-
return v, nil
}
Number <-
[0-9]+ ("." [0-9]+)? {
return c.text, nil
}
Digit <-
[0-9] {
return c.text, nil
File diff suppressed because it is too large. Load diff
+91
View File
@@ -858,6 +858,97 @@ func TestParse_DateTimeRestrictionNode(t *testing.T) {
}
}
func TestParse_NumericRestrictionNode(t *testing.T) {
tests := []testCase{
{
name: `size>=1048576`,
ast: &ast.Ast{
Nodes: []ast.Node{
&ast.NumericNode{
Key: "size",
Operator: &ast.OperatorNode{Value: ">="},
Value: 1048576,
},
},
},
},
{
name: `size<=10485760`,
ast: &ast.Ast{
Nodes: []ast.Node{
&ast.NumericNode{
Key: "size",
Operator: &ast.OperatorNode{Value: "<="},
Value: 10485760,
},
},
},
},
{
name: `size>=1024 AND size<=2048`,
query: `size>=1024 AND size<=2048`,
ast: &ast.Ast{
Nodes: []ast.Node{
&ast.NumericNode{
Key: "size",
Operator: &ast.OperatorNode{Value: ">="},
Value: 1024,
},
&ast.OperatorNode{Value: kql.BoolAND},
&ast.NumericNode{
Key: "size",
Operator: &ast.OperatorNode{Value: "<="},
Value: 2048,
},
},
},
},
{
name: `photo.fNumber>=2.8`,
ast: &ast.Ast{
Nodes: []ast.Node{
&ast.NumericNode{
Key: "photo.fNumber",
Operator: &ast.OperatorNode{Value: ">="},
Value: 2.8,
},
},
},
},
{
name: `photo.iso>100`,
ast: &ast.Ast{
Nodes: []ast.Node{
&ast.NumericNode{
Key: "photo.iso",
Operator: &ast.OperatorNode{Value: ">"},
Value: 100,
},
},
},
},
{
name: `photo.focalLength<50`,
ast: &ast.Ast{
Nodes: []ast.Node{
&ast.NumericNode{
Key: "photo.focalLength",
Operator: &ast.OperatorNode{Value: "<"},
Value: 50,
},
},
},
},
}
for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
testKQL(t, tc)
})
}
}
func TestParse_Errors(t *testing.T) {
tests := []testCase{
{
+29
View File
@@ -73,6 +73,35 @@ func buildStringNode(k, v interface{}, text []byte, pos position) (*ast.StringNo
}, nil
}
func buildNumericNode(k, o, v interface{}, text []byte, pos position) (*ast.NumericNode, error) {
b, err := base(text, pos)
if err != nil {
return nil, err
}
operator, err := toNode[*ast.OperatorNode](o)
if err != nil {
return nil, err
}
key, err := toString(k)
if err != nil {
return nil, err
}
value, err := toFloat64(v)
if err != nil {
return nil, err
}
return &ast.NumericNode{
Base: b,
Key: key,
Operator: operator,
Value: value,
}, nil
}
func buildDateTimeNode(k, o, v interface{}, text []byte, pos position) (*ast.DateTimeNode, error) {
b, err := base(text, pos)
if err != nil {
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Catalan (https://app.transifex.com/owncloud-org/teams/6149/ca/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: German (https://app.transifex.com/owncloud-org/teams/6149/de/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: English (United Kingdom) (https://app.transifex.com/owncloud-org/teams/6149/en_GB/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: English (United States) (https://app.transifex.com/owncloud-org/teams/6149/en_US/)\n"
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-13 00:17+0000\n"
"POT-Creation-Date: 2026-03-05 14:42+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Victor Vinuela <vinuela.victor@dissectio.com>, 2026\n"
"Language-Team: Spanish (https://app.transifex.com/owncloud-org/teams/6149/es/)\n"
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-13 00:17+0000\n"
"POT-Creation-Date: 2026-03-05 14:42+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Cesare Capoferri, 2026\n"
"Language-Team: Italian (https://app.transifex.com/owncloud-org/teams/6149/it/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Japanese (https://app.transifex.com/owncloud-org/teams/6149/ja/)\n"
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Portuguese (https://app.transifex.com/owncloud-org/teams/6149/pt/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Portuguese (Brazil) (https://app.transifex.com/owncloud-org/teams/6149/pt_BR/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Russian (https://app.transifex.com/owncloud-org/teams/6149/ru/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Albanian (https://app.transifex.com/owncloud-org/teams/6149/sq/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Uyghur (https://app.transifex.com/owncloud-org/teams/6149/ug/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Ukrainian (https://app.transifex.com/owncloud-org/teams/6149/uk/)\n"
@@ -160,14 +160,6 @@ func spacesProviders(cfg *config.Config, logger log.Logger) map[string]map[strin
"mount_point": "/projects",
"path_template": "/projects/{{.Space.Name}}",
},
"protected-personal": map[string]interface{}{
"mount_point": "/protected-users",
"path_template": "/protected-users/{{.Space.Name}}",
},
"protected-project": map[string]interface{}{
"mount_point": "/protected-projects",
"path_template": "/protected-projects/{{.Space.Name}}",
},
},
},
cfg.StorageSharesEndpoint: {
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-16 00:18+0000\n"
"POT-Creation-Date: 2026-03-08 00:34+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Ivan Fustero, 2026\n"
"Language-Team: Catalan (https://app.transifex.com/owncloud-org/teams/6149/ca/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: German (https://app.transifex.com/owncloud-org/teams/6149/de/)\n"
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Jesús Recio <jrecio@izertis.com>, 2026\n"
"Language-Team: Spanish (https://app.transifex.com/owncloud-org/teams/6149/es/)\n"
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Roman Perekhod, 2026\n"
"Language-Team: Russian (https://app.transifex.com/owncloud-org/teams/6149/ru/)\n"
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Besnik Bleta <besnik@programeshqip.org>, 2026\n"
"Language-Team: Albanian (https://app.transifex.com/owncloud-org/teams/6149/sq/)\n"
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Roman Perekhod, 2026\n"
"Language-Team: Ukrainian (https://app.transifex.com/owncloud-org/teams/6149/uk/)\n"
+22 -45
View File
@@ -37,13 +37,11 @@ import (
)
const (
_spaceTypePersonal = "personal"
_spaceTypeProject = "project"
_spaceTypeProtectedPersonal = "protected-personal"
_spaceTypeProtectedProject = "protected-project"
_spaceTypeVirtual = "virtual"
_spaceTypeMountpoint = "mountpoint"
_spaceStateTrashed = "trashed"
_spaceTypePersonal = "personal"
_spaceTypeProject = "project"
_spaceTypeVirtual = "virtual"
_spaceTypeMountpoint = "mountpoint"
_spaceStateTrashed = "trashed"
_sortDescending = "desc"
)
@@ -80,7 +78,7 @@ func (g Graph) GetDrives(version APIVersion) http.HandlerFunc {
// GetDrivesV1 attempts to retrieve the current users drives;
// it lists all drives the current user has access to.
func (g Graph) GetDrivesV1(w http.ResponseWriter, r *http.Request) {
spaces, errCode := g.getDrives(w, r, false, APIVersion_1)
spaces, errCode := g.getDrives(r, false, APIVersion_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -101,7 +99,7 @@ func (g Graph) GetDrivesV1(w http.ResponseWriter, r *http.Request) {
// it includes the grantedtoV2 property
// it uses unified roles instead of the cs3 representations
func (g Graph) GetDrivesV1Beta1(w http.ResponseWriter, r *http.Request) {
spaces, errCode := g.getDrives(w, r, false, APIVersion_1_Beta_1)
spaces, errCode := g.getDrives(r, false, APIVersion_1_Beta_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -135,11 +133,14 @@ func (g Graph) GetAllDrives(version APIVersion) http.HandlerFunc {
// GetAllDrivesV1 attempts to retrieve the current users drives;
// it includes another user's drives, if the current user has the permission.
func (g Graph) GetAllDrivesV1(w http.ResponseWriter, r *http.Request) {
if !g.validateMFA(r, w) {
if !mfa.Has(r.Context()) {
logger := g.logger.SubloggerWithRequestID(r.Context())
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return
}
spaces, errCode := g.getDrives(w, r, true, APIVersion_1)
spaces, errCode := g.getDrives(r, true, APIVersion_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -159,11 +160,14 @@ func (g Graph) GetAllDrivesV1(w http.ResponseWriter, r *http.Request) {
// it includes the grantedtoV2 property
// it uses unified roles instead of the cs3 representations
func (g Graph) GetAllDrivesV1Beta1(w http.ResponseWriter, r *http.Request) {
if !g.validateMFA(r, w) {
if !mfa.Has(r.Context()) {
logger := g.logger.SubloggerWithRequestID(r.Context())
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return
}
drives, errCode := g.getDrives(w, r, true, APIVersion_1_Beta_1)
drives, errCode := g.getDrives(r, true, APIVersion_1_Beta_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -180,7 +184,7 @@ func (g Graph) GetAllDrivesV1Beta1(w http.ResponseWriter, r *http.Request) {
}
// getDrives implements the Service interface.
func (g Graph) getDrives(w http.ResponseWriter, r *http.Request, unrestricted bool, apiVersion APIVersion) ([]*libregraph.Drive, error) {
func (g Graph) getDrives(r *http.Request, unrestricted bool, apiVersion APIVersion) ([]*libregraph.Drive, error) {
logger := g.logger.SubloggerWithRequestID(r.Context())
logger.Info().
Interface("query", r.URL.Query()).
@@ -193,10 +197,6 @@ func (g Graph) getDrives(w http.ResponseWriter, r *http.Request, unrestricted bo
logger.Debug().Err(err).Interface("query", r.URL.Query()).Msg("could not get drives: query error")
return nil, errorcode.New(errorcode.InvalidRequest, err.Error())
}
if !g.validateQueryMFA(r, w, odataReq.Query, DriveTypeValidator{}) {
return nil, errorcode.New(errorcode.AccessDenied, "")
}
ctx := r.Context()
filters, err := generateCs3Filters(odataReq)
@@ -409,8 +409,6 @@ func (g Graph) createDrive(w http.ResponseWriter, r *http.Request, apiVersion AP
switch driveType {
case "", _spaceTypeProject:
driveType = _spaceTypeProject
case _spaceTypeProtectedProject:
driveType = _spaceTypeProtectedProject
default:
logger.Debug().Str("type", driveType).Msg("could not create drive: drives of this type cannot be created via this api")
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "drives of this type cannot be created via this api")
@@ -470,7 +468,7 @@ func (g Graph) createDrive(w http.ResponseWriter, r *http.Request, apiVersion AP
}
space := resp.GetStorageSpace()
if t := r.URL.Query().Get(TemplateParameter); t != "" && (driveType == _spaceTypeProject || driveType == _spaceTypeProtectedProject) {
if t := r.URL.Query().Get(TemplateParameter); t != "" && driveType == _spaceTypeProject {
loc := l10n.MustGetUserLocale(ctx, us.GetId().GetOpaqueId(), r.Header.Get(HeaderAcceptLanguage), g.valueService)
if err := g.applySpaceTemplate(ctx, gatewayClient, space.GetRoot(), t, loc); err != nil {
logger.Error().Err(err).Msg("could not apply template to space")
@@ -598,7 +596,7 @@ func (g Graph) updateDrive(w http.ResponseWriter, r *http.Request, apiVersion AP
for _, sp := range res.StorageSpaces {
id, _ := storagespace.ParseID(sp.GetId().GetOpaqueId())
if id.GetSpaceId() == rid.GetSpaceId() {
dt = sp.SpaceType
dt = _spaceTypeProject
}
}
}
@@ -783,25 +781,7 @@ func (g Graph) ListStorageSpacesWithFilters(ctx context.Context, filters []*stor
return nil, err
}
res, err := gatewayClient.ListStorageSpaces(ctx, lReq)
if err != nil {
return nil, err
}
if res.GetStatus().GetCode() != cs3rpc.Code_CODE_OK {
return res, nil
}
// Filter out protected spaces if MFA is not enabled
if !mfa.Has(ctx) {
var filtered []*storageprovider.StorageSpace
for _, s := range res.StorageSpaces {
if s.SpaceType != _spaceTypeProtectedPersonal && s.SpaceType != _spaceTypeProtectedProject {
filtered = append(filtered, s)
}
}
res.StorageSpaces = filtered
}
return res, nil
return res, err
}
func (g Graph) cs3StorageSpaceToDrive(ctx context.Context, baseURL *url.URL, space *storageprovider.StorageSpace, apiVersion APIVersion) (*libregraph.Drive, error) {
@@ -1036,12 +1016,9 @@ func getQuota(quota *libregraph.Quota, defaultQuota string) *storageprovider.Quo
func (g Graph) canSetSpaceQuota(ctx context.Context, _ *userv1beta1.User, typ string) (bool, error) {
permID := settingsServiceExt.SetPersonalSpaceQuotaPermission(0).Id
if typ == _spaceTypeProject || typ == _spaceTypeProtectedProject {
if typ == _spaceTypeProject {
permID = settingsServiceExt.SetProjectSpaceQuotaPermission(0).Id
}
if typ == _spaceTypeProtectedPersonal {
permID = settingsServiceExt.SetPersonalSpaceQuotaPermission(0).Id
}
_, err := g.permissionsService.GetPermissionByID(ctx, &settingssvc.GetPermissionByIDRequest{PermissionId: permID})
if err != nil {
merror := merrors.FromError(err)
+15 -113
View File
@@ -21,7 +21,6 @@ import (
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/ocis/v2/ocis-pkg/keycloak"
"github.com/owncloud/ocis/v2/ocis-pkg/mfa"
ehsvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/eventhistory/v0"
searchsvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/search/v0"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
@@ -155,135 +154,38 @@ func parseIDParam(r *http.Request, param string) (storageprovider.ResourceId, er
return id, nil
}
// QueryValidator defines a strategy for validating godata queries.
type QueryValidator interface {
Validate(query *godata.GoDataQuery) error
}
// SearchValidator validates the search query.
type SearchValidator struct {
MinLength int
}
// Validate checks if the search term is acceptable.
func (v SearchValidator) Validate(query *godata.GoDataQuery) error {
// regular users can only search for terms with a minimum length
func hasAcceptableSearch(query *godata.GoDataQuery, minSearchLength int) bool {
if query == nil || query.Search == nil {
return errors.New("search term too short")
return false
}
minSearchLength := v.MinLength
if strings.HasPrefix(query.Search.RawValue, "\"") {
// if search starts with double quotes then it must finish with double quotes
// add +2 to the minimum search length in this case
minSearchLength += 2
}
if len(query.Search.RawValue) < minSearchLength {
return errors.New("search term too short")
}
return nil
return len(query.Search.RawValue) >= minSearchLength
}
// FilterValidator validates the filter query.
type FilterValidator struct{}
// Validate checks if the filter applies forbidden elements.
func (v FilterValidator) Validate(query *godata.GoDataQuery) error {
// regular users can only filter by userType
func hasAcceptableFilter(query *godata.GoDataQuery) bool {
switch {
case query == nil || query.Filter == nil:
return nil
return true
case query.Filter.Tree.Token.Type != godata.ExpressionTokenLogical:
return errors.New("filter has forbidden elements for regular users")
return false
case query.Filter.Tree.Token.Value != "eq":
return errors.New("filter has forbidden elements for regular users")
return false
case query.Filter.Tree.Children[0].Token.Value != "userType":
return errors.New("filter has forbidden elements for regular users")
}
return nil
}
// BasicQueryValidator validates basic queries.
type BasicQueryValidator struct{}
// Validate checks if the query contains unsupported operations like apply, expand, or compute.
func (v BasicQueryValidator) Validate(query *godata.GoDataQuery) error {
if query != nil && (query.Apply != nil || query.Expand != nil || query.Compute != nil) {
return errors.New("query has forbidden elements for regular users")
}
return nil
}
// DriveTypeValidator validates if the driveType filter contains protected types.
type DriveTypeValidator struct{}
// Validate checks if the driveType filter contains protected types.
func (v DriveTypeValidator) Validate(query *godata.GoDataQuery) error {
if query == nil || query.Filter == nil {
return nil
}
if query.Filter.Tree.Token.Value == "eq" && query.Filter.Tree.Children[0].Token.Value == "driveType" {
driveType := strings.Trim(query.Filter.Tree.Children[1].Token.Value, "'")
if driveType == _spaceTypeProtectedProject || driveType == _spaceTypeProtectedPersonal {
return errors.New("mfa required for protected spaces")
}
}
return nil
}
// validateQuery validates the godata query based on provided validators.
// It handles user permissions and MFA requirements centrally.
func (g Graph) validateQuery(r *http.Request, w http.ResponseWriter, query *godata.GoDataQuery, validators ...QueryValidator) bool {
ctxHasFullPerms := g.contextUserHasFullAccountPerms(r.Context())
hasMFA := mfa.Has(r.Context())
logger := g.logger.SubloggerWithRequestID(r.Context())
for _, v := range validators {
if err := v.Validate(query); err != nil {
if !ctxHasFullPerms {
logger.Debug().Interface("query", r.URL.Query()).Msg(err.Error())
errorcode.AccessDenied.Render(w, r, http.StatusForbidden, err.Error())
return false
}
if !hasMFA {
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return false
}
}
}
return true
}
// validateQueryMFA validates the godata query based on provided validators.
// It only handles MFA requirements and does not check for user permissions.
func (g Graph) validateQueryMFA(r *http.Request, w http.ResponseWriter, query *godata.GoDataQuery, validators ...QueryValidator) bool {
hasMFA := mfa.Has(r.Context())
logger := g.logger.SubloggerWithRequestID(r.Context())
for _, v := range validators {
if err := v.Validate(query); err != nil {
if !hasMFA {
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return false
}
}
}
return true
}
// validateMFA validates the MFA requirement.
func (g Graph) validateMFA(r *http.Request, w http.ResponseWriter) bool {
hasMFA := mfa.Has(r.Context())
logger := g.logger.SubloggerWithRequestID(r.Context())
if !hasMFA {
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return false
}
return true
}
// regular users can only use basic queries without any expansions, computes or applies
func hasAcceptableQuery(query *godata.GoDataQuery) bool {
return query != nil && query.Apply == nil && query.Expand == nil && query.Compute == nil
}
-104
View File
@@ -192,63 +192,6 @@ var _ = Describe("Graph", func() {
}
`))
})
It("filters out protected spaces when not having mfa", func() {
gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Times(1).Return(&provider.ListStorageSpacesResponse{
Status: status.NewOK(ctx),
StorageSpaces: []*provider.StorageSpace{
{
Id: &provider.StorageSpaceId{OpaqueId: "p-personal"},
SpaceType: "protected-personal",
Root: &provider.ResourceId{
StorageId: "pro-1",
SpaceId: "p-personal",
OpaqueId: "p-personal",
},
Name: "Protected Personal",
},
{
Id: &provider.StorageSpaceId{OpaqueId: "p-project"},
SpaceType: "protected-project",
Root: &provider.ResourceId{
StorageId: "pro-1",
SpaceId: "p-project",
OpaqueId: "p-project",
},
Name: "Protected Project",
},
{
Id: &provider.StorageSpaceId{OpaqueId: "normal"},
SpaceType: "personal",
Root: &provider.ResourceId{
StorageId: "pro-1",
SpaceId: "normal",
OpaqueId: "normal",
},
Name: "Normal Personal",
},
},
}, nil)
gatewayClient.On("InitiateFileDownload", mock.Anything, mock.Anything).Return(&gateway.InitiateFileDownloadResponse{
Status: status.NewNotFound(ctx, "not found"),
}, nil)
gatewayClient.On("GetQuota", mock.Anything, mock.Anything).Return(&provider.GetQuotaResponse{
Status: status.NewUnimplemented(ctx, fmt.Errorf("not supported"), "not supported"),
}, nil)
r := httptest.NewRequest(http.MethodGet, "/graph/v1.0/me/drives", nil)
r = r.WithContext(ctx)
rr := httptest.NewRecorder()
svc.GetDrivesV1(rr, r)
Expect(rr.Code).To(Equal(http.StatusOK))
body, _ := io.ReadAll(rr.Body)
var response map[string][]libregraph.Drive
err := json.Unmarshal(body, &response)
Expect(err).ToNot(HaveOccurred())
Expect(len(response["value"])).To(Equal(1))
Expect(*response["value"][0].DriveType).To(Equal("personal"))
})
It("can list a spaces with sort", func() {
gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&provider.ListStorageSpacesResponse{
Status: status.NewOK(ctx),
@@ -868,53 +811,6 @@ var _ = Describe("Graph", func() {
Expect(*response.DriveAlias).To(Equal("project/testspace"))
Expect(*response.Description).To(Equal("This space is for testing"))
})
It("can create a protected-project space", func() {
gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&provider.CreateStorageSpaceResponse{
Status: status.NewOK(ctx),
StorageSpace: &provider.StorageSpace{
Id: &provider.StorageSpaceId{OpaqueId: "newID"},
Name: "Top Secret Project",
SpaceType: "protected-project",
Root: &provider.ResourceId{
StorageId: "pro-1",
SpaceId: "newID",
OpaqueId: "newID",
},
Opaque: &typesv1beta1.Opaque{
Map: map[string]*typesv1beta1.OpaqueEntry{
"description": {Decoder: "plain", Value: []byte("This space is protected")},
"spaceAlias": {Decoder: "plain", Value: []byte("protected-project/topsecretproject")},
},
},
},
}, nil)
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settingssvc.GetPermissionByIDResponse{
Permission: &v0.Permission{
Operation: v0.Permission_OPERATION_READWRITE,
Constraint: v0.Permission_CONSTRAINT_ALL,
},
}, nil)
gatewayClient.On("GetQuota", mock.Anything, mock.Anything).Return(&provider.GetQuotaResponse{
Status: status.NewOK(ctx),
TotalBytes: 500,
}, nil)
jsonBody := []byte(`{"name": "Top Secret Project", "driveType": "protected-project", "description": "This space is protected"}`)
r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/drives", bytes.NewBuffer(jsonBody)).WithContext(ctx)
rr := httptest.NewRecorder()
svc.CreateDrive(rr, r)
Expect(rr.Code).To(Equal(http.StatusCreated))
body, _ := io.ReadAll(rr.Body)
var response libregraph.Drive
err := json.Unmarshal(body, &response)
Expect(err).ToNot(HaveOccurred())
Expect(response.Name).To(Equal("Top Secret Project"))
Expect(*response.DriveType).To(Equal("protected-project"))
Expect(*response.Description).To(Equal("This space is protected"))
})
It("Incomplete space", func() {
gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&provider.CreateStorageSpaceResponse{
Status: status.NewOK(ctx),
+30 -3
View File
@@ -10,6 +10,7 @@ import (
"github.com/CiscoM31/godata"
libregraph "github.com/owncloud/libre-graph-api-go"
"github.com/owncloud/ocis/v2/ocis-pkg/mfa"
"github.com/owncloud/ocis/v2/services/graph/pkg/errorcode"
"github.com/go-chi/chi/v5"
@@ -31,9 +32,35 @@ func (g Graph) GetGroups(w http.ResponseWriter, r *http.Request) {
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, err.Error())
return
}
ctxHasFullPerms := g.contextUserHasFullAccountPerms(r.Context())
hasMFA := mfa.Has(r.Context())
if !hasAcceptableSearch(odataReq.Query, g.config.API.IdentitySearchMinLength) {
if !ctxHasFullPerms {
// for regular user the search term must have a minimum length
logger.Debug().Interface("query", r.URL.Query()).Msgf("search with less than %d chars for a regular user", g.config.API.IdentitySearchMinLength)
errorcode.AccessDenied.Render(w, r, http.StatusForbidden, "search term too short")
return
}
if !hasMFA {
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return
}
}
if !g.validateQuery(r, w, odataReq.Query, SearchValidator{MinLength: g.config.API.IdentitySearchMinLength}, BasicQueryValidator{}) {
return
if !hasAcceptableQuery(odataReq.Query) {
if !ctxHasFullPerms {
// regular users can't use filter, apply, expand and compute
logger.Debug().Interface("query", r.URL.Query()).Msg("forbidden query elements for a regular user")
errorcode.AccessDenied.Render(w, r, http.StatusForbidden, "query has forbidden elements for regular users")
return
}
if !hasMFA {
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return
}
}
groups, err := g.identityBackend.GetGroups(r.Context(), odataReq)
@@ -43,7 +70,7 @@ func (g Graph) GetGroups(w http.ResponseWriter, r *http.Request) {
return
}
// If the user isn't admin, we'll show just the minimum group attibutes
if !g.contextUserHasFullAccountPerms(r.Context()) {
if !ctxHasFullPerms {
finalGroups := make([]*libregraph.Group, len(groups))
for i, grp := range groups {
finalGroups[i] = &libregraph.Group{
+46 -4
View File
@@ -22,6 +22,7 @@ import (
"github.com/go-chi/render"
"github.com/google/uuid"
libregraph "github.com/owncloud/libre-graph-api-go"
"github.com/owncloud/ocis/v2/ocis-pkg/mfa"
settingsmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/settings/v0"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
"github.com/owncloud/ocis/v2/services/graph/pkg/errorcode"
@@ -323,8 +324,51 @@ func (g Graph) GetUsers(w http.ResponseWriter, r *http.Request) {
return
}
if !g.validateQuery(r, w, odataReq.Query, SearchValidator{MinLength: g.config.API.IdentitySearchMinLength}, FilterValidator{}, BasicQueryValidator{}) {
return
ctxHasFullPerms := g.contextUserHasFullAccountPerms(r.Context())
hasMFA := mfa.Has(r.Context())
if !hasAcceptableSearch(odataReq.Query, g.config.API.IdentitySearchMinLength) {
if !ctxHasFullPerms {
// for regular user the search term must have a minimum length
logger.Debug().Interface("query", r.URL.Query()).Msgf("search with less than %d chars for a regular user", g.config.API.IdentitySearchMinLength)
errorcode.AccessDenied.Render(w, r, http.StatusForbidden, "search term too short")
return
}
if !hasMFA {
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return
}
}
if !hasAcceptableFilter(odataReq.Query) {
if !ctxHasFullPerms {
// regular users are allowed to filter only by userType
logger.Debug().Interface("query", r.URL.Query()).Msg("forbidden filter for a regular user")
errorcode.AccessDenied.Render(w, r, http.StatusForbidden, "filter has forbidden elements for regular users")
return
}
if !hasMFA {
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return
}
}
if !hasAcceptableQuery(odataReq.Query) {
if !ctxHasFullPerms {
// regular users can't use filter, apply, expand and compute
logger.Debug().Interface("query", r.URL.Query()).Msg("forbidden query elements for a regular user")
errorcode.AccessDenied.Render(w, r, http.StatusForbidden, "query has forbidden elements for regular users")
return
}
if !hasMFA {
logger.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied")
mfa.SetRequiredStatus(w)
return
}
}
logger.Debug().Interface("query", r.URL.Query()).Msg("calling get users on backend")
@@ -391,8 +435,6 @@ func (g Graph) GetUsers(w http.ResponseWriter, r *http.Request) {
usersWithAttributes := make([]*UserWithAttributes, 0, len(users))
displayedAttributes := g.config.API.UserSearchDisplayedAttributes
ctxHasFullPerms := g.contextUserHasFullAccountPerms(r.Context())
for _, user := range users {
attributes, err := getUsersAttributes(displayedAttributes, user)
if err != nil {
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-16 00:18+0000\n"
"POT-Creation-Date: 2026-03-08 00:34+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Ivan Fustero, 2026\n"
"Language-Team: Catalan (https://app.transifex.com/owncloud-org/teams/6149/ca/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: German (https://app.transifex.com/owncloud-org/teams/6149/de/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: English (United Kingdom) (https://app.transifex.com/owncloud-org/teams/6149/en_GB/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: English (United States) (https://app.transifex.com/owncloud-org/teams/6149/en_US/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Spanish (https://app.transifex.com/owncloud-org/teams/6149/es/)\n"
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-16 00:18+0000\n"
"POT-Creation-Date: 2026-03-08 00:34+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Cesare Capoferri, 2026\n"
"Language-Team: Italian (https://app.transifex.com/owncloud-org/teams/6149/it/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Portuguese (https://app.transifex.com/owncloud-org/teams/6149/pt/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Portuguese (Brazil) (https://app.transifex.com/owncloud-org/teams/6149/pt_BR/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Russian (https://app.transifex.com/owncloud-org/teams/6149/ru/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Albanian (https://app.transifex.com/owncloud-org/teams/6149/sq/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Uyghur (https://app.transifex.com/owncloud-org/teams/6149/ug/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Ukrainian (https://app.transifex.com/owncloud-org/teams/6149/uk/)\n"
+1
View File
@@ -9,6 +9,7 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''self'''
frame-src:
+5 -36
View File
@@ -8,10 +8,10 @@ import (
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/google/uuid"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/graph/pkg/errorcode"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/rgrpc/status"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/utils"
"google.golang.org/grpc/metadata"
@@ -72,41 +72,10 @@ func (m createHome) ServeHTTP(w http.ResponseWriter, req *http.Request) {
createHomeRes, err := client.CreateHome(ctx, createHomeReq)
if err != nil {
m.logger.Err(err).Msg("error calling CreateHome")
}
switch {
case createHomeRes.GetStatus().GetCode() == rpc.Code_CODE_OK:
m.logger.Info().Interface("userID", u.GetId().GetOpaqueId()).Msg("personal space created")
case createHomeRes.GetStatus().GetCode() != rpc.Code_CODE_ALREADY_EXISTS:
m.logger.Error().Interface("userID", u.GetId().GetOpaqueId()).Interface("status", createHomeRes.GetStatus()).Msg("personal space creation failed")
}
if spaceID := u.GetId().GetOpaqueId(); spaceID != "" {
// Create the "protected-personal" space.
// Use the user ID as the space ID if it is a valid uuid or generate a new one.
// Replace last 4 chars of the space id with "0000" to make it visible.
if err := uuid.Validate(spaceID); err != nil {
spaceID = uuid.New().String()
}
spaceID = spaceID[:len(spaceID)-4] + "0000"
createProtectedSpaceReq := &provider.CreateStorageSpaceRequest{
Type: "protected-personal",
Name: "Protected Personal",
Owner: &userv1beta1.User{
Id: u.Id,
},
Opaque: utils.AppendPlainToOpaque(nil, "spaceid", spaceID),
}
cpsRes, err := client.CreateStorageSpace(ctx, createProtectedSpaceReq)
if err != nil {
m.logger.Err(err).Msg("error calling CreateStorageSpace for protected-personal")
}
switch {
case cpsRes.GetStatus().GetCode() == rpc.Code_CODE_OK:
m.logger.Info().Interface("userID", u.GetId().GetOpaqueId()).Msg("protected-personal space created")
case cpsRes.GetStatus().GetCode() != rpc.Code_CODE_ALREADY_EXISTS:
m.logger.Error().Interface("userID", u.GetId().GetOpaqueId()).Interface("status", cpsRes.GetStatus()).Msg("protected-personal space creation failed")
} else if createHomeRes.Status.Code != rpc.Code_CODE_OK {
err := status.NewErrorFromCode(createHomeRes.Status.Code, "gateway")
if createHomeRes.Status.Code != rpc.Code_CODE_ALREADY_EXISTS {
m.logger.Err(err).Msg("error when calling Createhome")
}
}
}
@@ -58,6 +58,7 @@ func Security(cfg *config.Config, cspConfig *config.CSP) func(h http.Handler) ht
ContentSecurityPolicy: cspBuilder.MustBuild(),
ContentTypeNosniff: true,
CustomFrameOptionsValue: "SAMEORIGIN",
CustomBrowserXssValue: "0",
FrameDeny: true,
ReferrerPolicy: "no-referrer",
STSSeconds: 315360000,
@@ -84,3 +84,27 @@ func TestStrictTransportSecurity_ForceOnHTTP(t *testing.T) {
expected := "max-age=315360000; includeSubDomains; preload"
assert.Equal(t, stsHeader, expected)
}
func TestXXSSProtection(t *testing.T) {
// Reference: Penetration test audit Section 2.2, Table 2 Row 3
// X-XSS-Protection header must be explicitly set to "0" to disable
// the deprecated browser XSS filter which can introduce vulnerabilities
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
cspConfig := &config.CSP{
Directives: map[string][]string{
"default-src": {"'none'"},
},
}
cfg := &config.Config{HTTP: config.HTTP{ForceStrictTransportSecurity: false}}
securityMiddleware := Security(cfg, cspConfig)
req := httptest.NewRequest("GET", "https://example.com/", nil)
rr := httptest.NewRecorder()
securityMiddleware(handler).ServeHTTP(rr, req)
xssHeader := rr.Header().Get("X-XSS-Protection")
expected := "0"
assert.Equal(t, xssHeader, expected, "X-XSS-Protection must be '0' to disable deprecated XSS filter (audit requirement)")
}
+9 -1
View File
@@ -75,7 +75,11 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
var reader io.Reader = data
if ri.Size > t.ContentExtractionSizeLimit {
reader = io.LimitReader(data, int64(t.ContentExtractionSizeLimit)) //nolint:gosec // ContentExtractionSizeLimit is a config value, never exceeds int64 max
limit := t.ContentExtractionSizeLimit
if limit > math.MaxInt64 {
limit = math.MaxInt64
}
reader = io.LimitReader(data, int64(limit)) //nolint:gosec // overflow guarded above
}
metas, err := t.tika.MetaRecursive(ctx, reader)
@@ -83,6 +87,10 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
return doc, err
}
if len(metas) == 0 {
return doc, fmt.Errorf("tika returned empty metadata for %q", ri.Name)
}
for _, meta := range metas {
if title, err := getFirstValue(meta, "title"); err == nil {
doc.Title = strings.TrimSpace(fmt.Sprintf("%s %s", doc.Title, title))
+83 -12
View File
@@ -2,7 +2,7 @@ package engine
import (
"context"
"errors"
"fmt"
"math"
"path"
"reflect"
@@ -16,6 +16,7 @@ import (
"github.com/blevesearch/bleve/v2/analysis/token/porter"
"github.com/blevesearch/bleve/v2/analysis/tokenizer/single"
"github.com/blevesearch/bleve/v2/analysis/tokenizer/unicode"
"github.com/blevesearch/bleve/v2/index/scorch/mergeplan"
"github.com/blevesearch/bleve/v2/mapping"
"github.com/blevesearch/bleve/v2/search/query"
storageProvider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
@@ -34,6 +35,8 @@ import (
searchQuery "github.com/owncloud/ocis/v2/services/search/pkg/query"
)
const lowercaseKeywordAnalyzer = "lowercaseKeyword"
// Bleve represents a search engine which utilizes bleve to search and store resources.
type Bleve struct {
indexGetter bleveEngine.IndexGetter
@@ -71,11 +74,11 @@ func (b *Bleve) Close() error {
// BuildBleveMapping builds a bleve index mapping which can be used for indexing
func BuildBleveMapping() (mapping.IndexMapping, error) {
nameMapping := bleve.NewTextFieldMapping()
nameMapping.Analyzer = "lowercaseKeyword"
nameMapping.Analyzer = lowercaseKeywordAnalyzer
lowercaseMapping := bleve.NewTextFieldMapping()
lowercaseMapping.IncludeInAll = false
lowercaseMapping.Analyzer = "lowercaseKeyword"
lowercaseMapping.Analyzer = lowercaseKeywordAnalyzer
fulltextFieldMapping := bleve.NewTextFieldMapping()
fulltextFieldMapping.Analyzer = "fulltext"
@@ -91,7 +94,7 @@ func BuildBleveMapping() (mapping.IndexMapping, error) {
photoStringMapping := bleve.NewTextFieldMapping()
photoStringMapping.Store = true
photoStringMapping.Index = true
photoStringMapping.Analyzer = keyword.Name
photoStringMapping.Analyzer = lowercaseKeywordAnalyzer
photoNumericMapping := bleve.NewNumericFieldMapping()
photoNumericMapping.Store = true
photoNumericMapping.Index = true
@@ -123,7 +126,7 @@ func BuildBleveMapping() (mapping.IndexMapping, error) {
indexMapping := bleve.NewIndexMapping()
indexMapping.DefaultAnalyzer = keyword.Name
indexMapping.DefaultMapping = docMapping
err := indexMapping.AddCustomAnalyzer("lowercaseKeyword",
err := indexMapping.AddCustomAnalyzer(lowercaseKeywordAnalyzer,
map[string]interface{}{
"type": custom.Name,
"tokenizer": single.Name,
@@ -286,6 +289,46 @@ func (b *Bleve) Upsert(id string, r Resource) error {
return bleveIndex.Index(id, r)
}
// Update retrieves an existing resource from the index, applies the given
// mutation function, and writes it back. This provides a get + mutate + set
// cycle without exposing raw resource retrieval.
//
// NOTE: this operation is not atomic. A concurrent Upsert between the get and
// set may be overwritten. Callers should be aware of potential race conditions.
//
// The mutateFn should only modify fields on the provided resource.
// For example:
//
// newTags := []string{"tag1", "tag2", "tag3"}
// mutateFn := func(r *Resource) {
// r.Tags = newTags
// }
// bleveEngine.Update("docId1", mutateFn)
//
// Returns ErrResourceNotFound if the resource is not in the index.
func (b *Bleve) Update(id string, mutateFn func(*Resource)) error {
bleveIndex, closeFn, err := b.indexGetter.GetIndex()
if err != nil {
return err
}
defer closeFn()
_, err = b.updateEntity(bleveIndex, id, mutateFn)
return err
}
// Lookup retrieves a resource by its document ID using an O(1) DocIDQuery.
// Returns ErrResourceNotFound if the resource is not in the index.
func (b *Bleve) Lookup(id string) (*Resource, error) {
bleveIndex, closeFn, err := b.indexGetter.GetIndex(bleveEngine.ReadOnly(true))
if err != nil {
return nil, err
}
defer closeFn()
return b.getResource(bleveIndex, id)
}
// Move updates the resource location and all of its necessary fields.
func (b *Bleve) Move(id string, parentid string, target string) error {
bleveIndex, closeFn, err := b.indexGetter.GetIndex()
@@ -373,6 +416,33 @@ func (b *Bleve) Purge(id string) error {
return bleveIndex.Delete(id)
}
// Optimize triggers a force merge of the bleve index segments into a single
// segment, improving query performance. This is an expensive I/O operation
// and should be called during low-usage periods (e.g., after bulk indexing).
func (b *Bleve) Optimize(ctx context.Context) error {
bleveIndex, closeFn, err := b.indexGetter.GetIndex()
if err != nil {
return err
}
defer closeFn()
internal, err := bleveIndex.Advanced()
if err != nil {
return fmt.Errorf("failed to access internal index: %w", err)
}
type forceMerger interface {
ForceMerge(ctx context.Context, mo *mergeplan.MergePlanOptions) error
}
fm, ok := internal.(forceMerger)
if !ok {
return fmt.Errorf("index implementation does not support force merge")
}
return fm.ForceMerge(ctx, nil)
}
// DocCount returns the number of resources in the index.
func (b *Bleve) DocCount() (uint64, error) {
bleveIndex, closeFn, err := b.indexGetter.GetIndex(bleveEngine.ReadOnly(true))
@@ -392,18 +462,19 @@ func (b *Bleve) getResource(bleveIndex bleve.Index, id string) (*Resource, error
return nil, err
}
if res.Hits.Len() == 0 {
return nil, errors.New("entity not found")
return nil, ErrResourceNotFound
}
fields := res.Hits[0].Fields
return &Resource{
ID: getFieldValue[string](fields, "ID"),
RootID: getFieldValue[string](fields, "RootID"),
Path: getFieldValue[string](fields, "Path"),
ParentID: getFieldValue[string](fields, "ParentID"),
Type: uint64(getFieldValue[float64](fields, "Type")),
Deleted: getFieldValue[bool](fields, "Deleted"),
ID: getFieldValue[string](fields, "ID"),
RootID: getFieldValue[string](fields, "RootID"),
Path: getFieldValue[string](fields, "Path"),
ParentID: getFieldValue[string](fields, "ParentID"),
Type: uint64(getFieldValue[float64](fields, "Type")),
Deleted: getFieldValue[bool](fields, "Deleted"),
Extracted: getFieldValue[bool](fields, "Extracted"),
Document: content.Document{
Name: getFieldValue[string](fields, "Name"),
Title: getFieldValue[string](fields, "Title"),
+20 -7
View File
@@ -2,6 +2,7 @@ package engine
import (
"context"
"errors"
"regexp"
"github.com/blevesearch/bleve/v2/search"
@@ -12,12 +13,17 @@ import (
"github.com/owncloud/ocis/v2/services/search/pkg/content"
)
// ErrResourceNotFound is returned when a resource is not present in the index.
var ErrResourceNotFound = errors.New("entity not found")
var queryEscape = regexp.MustCompile(`([` + regexp.QuoteMeta(`+=&|><!(){}[]^\"~*?:\/`) + `\-\s])`)
// Engine is the interface to the search engine
type Engine interface {
Search(ctx context.Context, req *searchService.SearchIndexRequest) (*searchService.SearchIndexResponse, error)
Upsert(id string, r Resource) error
Update(id string, mutateFn func(*Resource)) error
Lookup(id string) (*Resource, error)
Move(id string, parentid string, target string) error
Delete(id string) error
Restore(id string) error
@@ -25,17 +31,24 @@ type Engine interface {
DocCount() (uint64, error)
}
// Optimizer is an optional interface that Engine implementations may support
// to trigger index compaction. Callers should type-assert before use.
type Optimizer interface {
Optimize(ctx context.Context) error
}
// Resource is the entity that is stored in the index.
type Resource struct {
content.Document
ID string
RootID string
Path string
ParentID string
Type uint64
Deleted bool
Hidden bool
ID string
RootID string
Path string
ParentID string
Type uint64
Deleted bool
Hidden bool
Extracted bool
}
func resourceIDtoSearchID(id storageProvider.ResourceId) *searchMessage.ResourceID {
+108
View File
@@ -125,6 +125,67 @@ func (_c *Engine_DocCount_Call) RunAndReturn(run func() (uint64, error)) *Engine
return _c
}
// Lookup provides a mock function with given fields: id
func (_m *Engine) Lookup(id string) (*engine.Resource, error) {
ret := _m.Called(id)
if len(ret) == 0 {
panic("no return value specified for Lookup")
}
var r0 *engine.Resource
var r1 error
if rf, ok := ret.Get(0).(func(string) (*engine.Resource, error)); ok {
return rf(id)
}
if rf, ok := ret.Get(0).(func(string) *engine.Resource); ok {
r0 = rf(id)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*engine.Resource)
}
}
if rf, ok := ret.Get(1).(func(string) error); ok {
r1 = rf(id)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// Engine_Lookup_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Lookup'
type Engine_Lookup_Call struct {
*mock.Call
}
// Lookup is a helper method to define mock.On call
// - id string
func (_e *Engine_Expecter) Lookup(id interface{}) *Engine_Lookup_Call {
return &Engine_Lookup_Call{Call: _e.mock.On("Lookup", id)}
}
// Run sets a handler to be called when the Lookup mock is matched.
func (_c *Engine_Lookup_Call) Run(run func(id string)) *Engine_Lookup_Call {
_c.Call.Run(func(args mock.Arguments) {
run(args[0].(string))
})
return _c
}
// Return specifies the return values for the Lookup mock.
func (_c *Engine_Lookup_Call) Return(_a0 *engine.Resource, _a1 error) *Engine_Lookup_Call {
_c.Call.Return(_a0, _a1)
return _c
}
// RunAndReturn sets a handler that is called and whose return values are used as the mock's return values.
func (_c *Engine_Lookup_Call) RunAndReturn(run func(string) (*engine.Resource, error)) *Engine_Lookup_Call {
_c.Call.Return(run)
return _c
}
// Move provides a mock function with given fields: id, parentid, target
func (_m *Engine) Move(id string, parentid string, target string) error {
ret := _m.Called(id, parentid, target)
@@ -173,6 +234,53 @@ func (_c *Engine_Move_Call) RunAndReturn(run func(string, string, string) error)
return _c
}
// Update provides a mock function with given fields: id, mutateFn
func (_m *Engine) Update(id string, mutateFn func(*engine.Resource)) error {
ret := _m.Called(id, mutateFn)
if len(ret) == 0 {
panic("no return value specified for Update")
}
var r0 error
if rf, ok := ret.Get(0).(func(string, func(*engine.Resource)) error); ok {
r0 = rf(id, mutateFn)
} else {
r0 = ret.Error(0)
}
return r0
}
// Engine_Update_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Update'
type Engine_Update_Call struct {
*mock.Call
}
// Update is a helper method to define mock.On call
// - id string
// - mutateFn func(*engine.Resource)
func (_e *Engine_Expecter) Update(id interface{}, mutateFn interface{}) *Engine_Update_Call {
return &Engine_Update_Call{Call: _e.mock.On("Update", id, mutateFn)}
}
func (_c *Engine_Update_Call) Run(run func(id string, mutateFn func(*engine.Resource))) *Engine_Update_Call {
_c.Call.Run(func(args mock.Arguments) {
run(args[0].(string), args[1].(func(*engine.Resource)))
})
return _c
}
func (_c *Engine_Update_Call) Return(_a0 error) *Engine_Update_Call {
_c.Call.Return(_a0)
return _c
}
func (_c *Engine_Update_Call) RunAndReturn(run func(string, func(*engine.Resource)) error) *Engine_Update_Call {
_c.Call.Return(run)
return _c
}
// Purge provides a mock function with given fields: id
func (_m *Engine) Purge(id string) error {
ret := _m.Called(id)
+72 -25
View File
@@ -124,35 +124,20 @@ func walk(offset int, nodes []ast.Node) (bleveQuery.Query, int, error) {
next = q
}
case *ast.DateTimeNode:
q := &bleveQuery.DateRangeQuery{
Start: bleveQuery.BleveQueryTime{},
End: bleveQuery.BleveQueryTime{},
InclusiveStart: nil,
InclusiveEnd: nil,
FieldVal: getField(n.Key),
}
if n.Operator == nil {
q := dateTimeQuery(n)
if q == nil {
continue
}
switch n.Operator.Value {
case ">":
q.Start.Time = n.Value
q.InclusiveStart = &[]bool{false}[0]
case ">=":
q.Start.Time = n.Value
q.InclusiveStart = &[]bool{true}[0]
case "<":
q.End.Time = n.Value
q.InclusiveEnd = &[]bool{false}[0]
case "<=":
q.End.Time = n.Value
q.InclusiveEnd = &[]bool{true}[0]
default:
if prev == nil {
prev = q
} else {
next = q
}
case *ast.NumericNode:
q := numericQuery(n)
if q == nil {
continue
}
if prev == nil {
prev = q
} else {
@@ -370,6 +355,68 @@ func mimeType(k, v string) (bleveQuery.Query, bool) {
}
}
func dateTimeQuery(n *ast.DateTimeNode) bleveQuery.Query {
if n.Operator == nil {
return nil
}
q := &bleveQuery.DateRangeQuery{
Start: bleveQuery.BleveQueryTime{},
End: bleveQuery.BleveQueryTime{},
FieldVal: getField(n.Key),
}
switch n.Operator.Value {
case ">":
q.Start.Time = n.Value
q.InclusiveStart = &[]bool{false}[0]
case ">=":
q.Start.Time = n.Value
q.InclusiveStart = &[]bool{true}[0]
case "<":
q.End.Time = n.Value
q.InclusiveEnd = &[]bool{false}[0]
case "<=":
q.End.Time = n.Value
q.InclusiveEnd = &[]bool{true}[0]
default:
return nil
}
return q
}
func numericQuery(n *ast.NumericNode) bleveQuery.Query {
if n.Operator == nil {
return nil
}
var minVal, maxVal *float64
var minInclusive, maxInclusive *bool
val := n.Value
switch n.Operator.Value {
case ">":
minVal = &val
minInclusive = &[]bool{false}[0]
case ">=":
minVal = &val
minInclusive = &[]bool{true}[0]
case "<":
maxVal = &val
maxInclusive = &[]bool{false}[0]
case "<=":
maxVal = &val
maxInclusive = &[]bool{true}[0]
default:
return nil
}
q := bleve.NewNumericRangeInclusiveQuery(minVal, maxVal, minInclusive, maxInclusive)
q.SetField(getField(n.Key))
return q
}
func newQueryStringQueryList(k string, v ...string) []bleveQuery.Query {
list := make([]bleveQuery.Query, len(v))
for i := 0; i < len(v); i++ {
@@ -565,6 +565,107 @@ func Test_compile(t *testing.T) {
}),
wantErr: false,
},
{
name: `size>=1048576`,
args: &ast.Ast{
Nodes: []ast.Node{
&ast.NumericNode{
Key: "size",
Operator: &ast.OperatorNode{Value: ">="},
Value: 1048576,
},
},
},
want: query.NewConjunctionQuery([]query.Query{
func() query.Query {
min := 1048576.0
inclusive := true
q := query.NewNumericRangeInclusiveQuery(&min, nil, &inclusive, nil)
q.SetField("Size")
return q
}(),
}),
wantErr: false,
},
{
name: `size<=10485760`,
args: &ast.Ast{
Nodes: []ast.Node{
&ast.NumericNode{
Key: "size",
Operator: &ast.OperatorNode{Value: "<="},
Value: 10485760,
},
},
},
want: query.NewConjunctionQuery([]query.Query{
func() query.Query {
max := 10485760.0
inclusive := true
q := query.NewNumericRangeInclusiveQuery(nil, &max, nil, &inclusive)
q.SetField("Size")
return q
}(),
}),
wantErr: false,
},
{
name: `photo.iso>100 AND photo.iso<3200`,
args: &ast.Ast{
Nodes: []ast.Node{
&ast.NumericNode{
Key: "photo.iso",
Operator: &ast.OperatorNode{Value: ">"},
Value: 100,
},
&ast.OperatorNode{Value: "AND"},
&ast.NumericNode{
Key: "photo.iso",
Operator: &ast.OperatorNode{Value: "<"},
Value: 3200,
},
},
},
want: query.NewConjunctionQuery([]query.Query{
func() query.Query {
min := 100.0
inclusive := false
q := query.NewNumericRangeInclusiveQuery(&min, nil, &inclusive, nil)
q.SetField("photo.iso")
return q
}(),
func() query.Query {
max := 3200.0
inclusive := false
q := query.NewNumericRangeInclusiveQuery(nil, &max, nil, &inclusive)
q.SetField("photo.iso")
return q
}(),
}),
wantErr: false,
},
{
name: `photo.fNumber>=2.8`,
args: &ast.Ast{
Nodes: []ast.Node{
&ast.NumericNode{
Key: "photo.fNumber",
Operator: &ast.OperatorNode{Value: ">="},
Value: 2.8,
},
},
},
want: query.NewConjunctionQuery([]query.Query{
func() query.Query {
min := 2.8
inclusive := true
q := query.NewNumericRangeInclusiveQuery(&min, nil, &inclusive, nil)
q.SetField("photo.fNumber")
return q
}(),
}),
wantErr: false,
},
{
name: `photo.cameraMake:canon`,
args: &ast.Ast{
+2 -2
View File
@@ -81,9 +81,9 @@ func HandleEvents(s Searcher, bus events.Consumer, logger log.Logger, cfg *confi
case events.FileVersionRestored:
indexSpaceDebouncer.Debounce(getSpaceID(ev.Ref))
case events.TagsAdded:
s.UpsertItem(ev.Ref)
s.UpdateTags(ev.Ref)
case events.TagsRemoved:
s.UpsertItem(ev.Ref)
s.UpdateTags(ev.Ref)
case events.FileUploaded:
indexSpaceDebouncer.Debounce(getSpaceID(ev.Ref))
case events.UploadReady:
+2 -2
View File
@@ -50,8 +50,8 @@ var _ = DescribeTable("events",
Entry("ContainerCreated", []string{"IndexSpace"}, events.ContainerCreated{}, false),
Entry("FileTouched", []string{"IndexSpace"}, events.FileTouched{}, false),
Entry("FileVersionRestored", []string{"IndexSpace"}, events.FileVersionRestored{}, false),
Entry("TagsAdded", []string{"UpsertItem"}, events.TagsAdded{}, false),
Entry("TagsRemoved", []string{"UpsertItem"}, events.TagsRemoved{}, false),
Entry("TagsAdded", []string{"UpdateTags"}, events.TagsAdded{}, false),
Entry("TagsRemoved", []string{"UpdateTags"}, events.TagsRemoved{}, false),
Entry("FileUploaded", []string{"IndexSpace"}, events.FileUploaded{}, false),
Entry("UploadReady", []string{"IndexSpace"}, events.UploadReady{ExecutingUser: &userv1beta1.User{}}, true),
)
@@ -228,6 +228,39 @@ func (_c *Searcher_TrashItem_Call) RunAndReturn(run func(*providerv1beta1.Resour
return _c
}
// UpdateTags provides a mock function with given fields: ref
func (_m *Searcher) UpdateTags(ref *providerv1beta1.Reference) {
_m.Called(ref)
}
// Searcher_UpdateTags_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateTags'
type Searcher_UpdateTags_Call struct {
*mock.Call
}
// UpdateTags is a helper method to define mock.On call
// - ref *providerv1beta1.Reference
func (_e *Searcher_Expecter) UpdateTags(ref interface{}) *Searcher_UpdateTags_Call {
return &Searcher_UpdateTags_Call{Call: _e.mock.On("UpdateTags", ref)}
}
func (_c *Searcher_UpdateTags_Call) Run(run func(ref *providerv1beta1.Reference)) *Searcher_UpdateTags_Call {
_c.Call.Run(func(args mock.Arguments) {
run(args[0].(*providerv1beta1.Reference))
})
return _c
}
func (_c *Searcher_UpdateTags_Call) Return() *Searcher_UpdateTags_Call {
_c.Call.Return()
return _c
}
func (_c *Searcher_UpdateTags_Call) RunAndReturn(run func(*providerv1beta1.Reference)) *Searcher_UpdateTags_Call {
_c.Run(run)
return _c
}
// UpsertItem provides a mock function with given fields: ref
func (_m *Searcher) UpsertItem(ref *providerv1beta1.Reference) {
_m.Called(ref)
+81 -27
View File
@@ -2,6 +2,7 @@ package search
import (
"context"
"errors"
"fmt"
"path/filepath"
"slices"
@@ -21,6 +22,7 @@ import (
sdk "github.com/owncloud/reva/v2/pkg/sdk/common"
"github.com/owncloud/reva/v2/pkg/storage/utils/walker"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/tags"
"github.com/owncloud/reva/v2/pkg/utils"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/fieldmaskpb"
@@ -35,14 +37,12 @@ import (
)
const (
_spaceStateTrashed = "trashed"
_spaceTypeMountpoint = "mountpoint"
_spaceTypePersonal = "personal"
_spaceTypeProject = "project"
_spaceTypeProtectedPersonal = "protected-personal"
_spaceTypeProtectedProject = "protected-project"
_spaceTypeGrant = "grant"
_slowQueryDuration = 500 * time.Millisecond
_spaceStateTrashed = "trashed"
_spaceTypeMountpoint = "mountpoint"
_spaceTypePersonal = "personal"
_spaceTypeProject = "project"
_spaceTypeGrant = "grant"
_slowQueryDuration = 500 * time.Millisecond
)
var (
@@ -60,6 +60,7 @@ type Searcher interface {
IndexSpace(rID *provider.StorageSpaceId) error
TrashItem(rID *provider.ResourceId)
UpsertItem(ref *provider.Reference)
UpdateTags(ref *provider.Reference)
RestoreItem(ref *provider.Reference)
MoveItem(ref *provider.Reference)
}
@@ -170,10 +171,6 @@ func (s *Service) Search(ctx context.Context, req *searchsvc.SearchRequest) (*se
// We still need the mountpoint in order to map the result paths to the according share
continue
}
if space.SpaceType == _spaceTypeProtectedPersonal || space.SpaceType == _spaceTypeProtectedProject {
// Exclude protected spaces from search results
continue
}
spaces = append(spaces, space)
}
@@ -465,17 +462,22 @@ func (s *Service) IndexSpace(spaceID *provider.StorageSpaceId) error {
}
s.logger.Debug().Str("path", ref.Path).Msg("Walking tree")
searchRes, err := s.engine.Search(ownerCtx, &searchsvc.SearchIndexRequest{
Query: "id:" + storagespace.FormatResourceID(info.Id) + ` mtime>=` + utils.TSToTime(info.Mtime).Format(time.RFC3339Nano),
})
if err == nil && len(searchRes.Matches) >= 1 {
if info.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
s.logger.Debug().Str("path", ref.Path).Msg("subtree hasn't changed. Skipping.")
return filepath.SkipDir
resourceID := storagespace.FormatResourceID(info.Id)
r, err := s.engine.Lookup(resourceID)
if err == nil && r.Extracted {
fileMtime := utils.TSToTime(info.Mtime)
docMtime, parseErr := time.Parse(time.RFC3339Nano, r.Mtime)
if parseErr == nil && !docMtime.Before(fileMtime) {
if info.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
// Always descend into directories — a directory's
// mtime only reflects direct child add/remove, not
// whether all children were successfully indexed.
// With O(1) DocID lookups the cost is negligible.
return nil
}
s.logger.Debug().Str("path", ref.Path).Msg("element hasn't changed. Skipping.")
return nil
}
s.logger.Debug().Str("path", ref.Path).Msg("element hasn't changed. Skipping.")
return nil
}
s.UpsertItem(ref)
@@ -489,6 +491,13 @@ func (s *Service) IndexSpace(spaceID *provider.StorageSpaceId) error {
logDocCount(s.engine, s.logger)
if opt, ok := s.engine.(engine.Optimizer); ok {
s.logger.Info().Msg("optimizing search index after space walk")
if err := opt.Optimize(ownerCtx); err != nil {
s.logger.Warn().Err(err).Msg("index optimization failed")
}
}
return nil
}
@@ -519,6 +528,8 @@ func (s *Service) UpsertItem(ref *provider.Reference) {
}
}
resourceID := storagespace.FormatResourceID(stat.Info.Id)
doc, err := s.extractor.Extract(ctx, stat.Info)
if err != nil {
s.logger.Error().Err(err).Msg("failed to extract resource content")
@@ -526,15 +537,16 @@ func (s *Service) UpsertItem(ref *provider.Reference) {
}
r := engine.Resource{
ID: storagespace.FormatResourceID(stat.Info.Id),
ID: resourceID,
RootID: storagespace.FormatResourceID(&provider.ResourceId{
StorageId: stat.Info.Id.StorageId,
OpaqueId: stat.Info.Id.SpaceId,
SpaceId: stat.Info.Id.SpaceId,
}),
Path: utils.MakeRelativePath(path),
Type: uint64(stat.Info.Type),
Document: doc,
Path: utils.MakeRelativePath(path),
Type: uint64(stat.Info.Type),
Document: doc,
Extracted: true,
}
r.Hidden = strings.HasPrefix(r.Path, ".")
@@ -548,7 +560,13 @@ func (s *Service) UpsertItem(ref *provider.Reference) {
logDocCount(s.engine, s.logger)
}
// determine if metadata needs to be stored in storage as well
s.storeExtractedMetadata(ctx, ref, doc)
}
// storeExtractedMetadata persists Tika-extracted audio, image, location, and
// photo metadata back to the storage provider so it is available outside the
// search index.
func (s *Service) storeExtractedMetadata(ctx context.Context, ref *provider.Reference, doc content.Document) {
metadata := map[string]string{}
addAudioMetadata(metadata, doc.Audio)
addImageMetadata(metadata, doc.Image)
@@ -574,8 +592,44 @@ func (s *Service) UpsertItem(ref *provider.Reference) {
})
if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK {
s.logger.Error().Err(err).Int32("status", int32(resp.GetStatus().GetCode())).Msg("error storing metadata")
}
}
// UpdateTags updates only the tags of an already-indexed resource without
// triggering a full content re-extraction via Tika. If the resource is not
// yet in the index it falls back to a full UpsertItem.
func (s *Service) UpdateTags(ref *provider.Reference) {
_, stat, _ := s.resInfo(ref)
if stat == nil {
return
}
resourceID := storagespace.FormatResourceID(stat.Info.Id)
// Read the current tags from ArbitraryMetadata.
var newTags []string
if m := stat.Info.ArbitraryMetadata.GetMetadata(); m != nil {
if t, ok := m["tags"]; ok {
newTags = tags.New(t).AsSlice()
}
}
// Update only the tags field on the existing indexed resource.
err := s.engine.Update(resourceID, func(r *engine.Resource) {
r.Tags = newTags
})
if err == nil {
return
}
if errors.Is(err, engine.ErrResourceNotFound) {
// Resource is not yet indexed — fall back to the full extraction path.
s.logger.Debug().Str("id", resourceID).Msg("resource not in index, falling back to full upsert for tag update")
s.UpsertItem(ref)
return
}
s.logger.Error().Err(err).Str("id", resourceID).Msg("failed to update tags in index")
}
func addAudioMetadata(metadata map[string]string, audio *libregraph.Audio) {
+334 -1
View File
@@ -2,6 +2,10 @@ package search_test
import (
"context"
"errors"
"fmt"
"sync/atomic"
"time"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
@@ -162,7 +166,7 @@ var _ = Describe("Searchprovider", func() {
indexClient.On("Upsert", mock.Anything, mock.MatchedBy(func(r engine.Resource) bool {
return r.ID == "storageid$spaceid!opaqueid" && r.Path == "./foo.pdf"
})).Return(nil)
indexClient.On("Search", mock.Anything, mock.Anything).Return(&searchsvc.SearchIndexResponse{}, nil)
indexClient.On("Lookup", mock.Anything).Return(nil, engine.ErrResourceNotFound)
gatewayClient.On("Stat", mock.Anything, mock.MatchedBy(func(sreq *sprovider.StatRequest) bool {
return sreq.Ref.ResourceId.StorageId == "storageid" &&
sreq.Ref.ResourceId.OpaqueId == "spaceid" &&
@@ -199,6 +203,212 @@ var _ = Describe("Searchprovider", func() {
err := s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"})
Expect(err).ShouldNot(HaveOccurred())
})
It("descends into already-indexed directories to index unvisited children", func() {
// Simulate a large tree where all directories are already indexed
// (mtime matches) but each contains one unindexed file — e.g. after
// a Tika crash interrupted a previous reindex run. The fix ensures
// we never SkipDir for directories, so children are always visited.
//
// 10,000 directories: pessimistic-case benchmark confirming the walker
// scales linearly even when every directory is already indexed.
const numDirs = 10000
gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{
Status: status.NewOK(context.Background()),
User: user,
}, nil)
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
// The indexed mtime that the engine returns for directories.
indexedMtime := time.Unix(5000, 0).UTC().Format(time.RFC3339Nano)
// Build root: a container that lists numDirs child directories.
rootInfo := &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
Type: sprovider.ResourceType_RESOURCE_TYPE_CONTAINER,
Path: ".",
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
dirInfos := make([]*sprovider.ResourceInfo, numDirs)
for i := 0; i < numDirs; i++ {
dirInfos[i] = &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: fmt.Sprintf("dir-%d", i)},
Type: sprovider.ResourceType_RESOURCE_TYPE_CONTAINER,
Path: fmt.Sprintf("dir-%d", i),
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
}
// Pre-build file infos for each directory (map for O(1) dispatch).
fileInfoByDir := make(map[string]*sprovider.ResourceInfo, numDirs)
for i := 0; i < numDirs; i++ {
dirID := fmt.Sprintf("dir-%d", i)
fileInfoByDir[dirID] = &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: fmt.Sprintf("file-%d", i)},
ParentId: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: dirID},
Type: sprovider.ResourceType_RESOURCE_TYPE_FILE,
Path: fmt.Sprintf("file-%d.pdf", i),
Size: 1024,
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
}
// Build path-to-fileInfo map for O(1) Stat dispatch.
fileInfoByPath := make(map[string]*sprovider.ResourceInfo, numDirs)
for dirID, fi := range fileInfoByDir {
fileInfoByPath["./"+dirID+"/"+fi.Path] = fi
}
// Single Stat mock dispatching via map — avoids 10k separate matchers.
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(
func(_ context.Context, sreq *sprovider.StatRequest, _ ...grpc.CallOption) *sprovider.StatResponse {
if sreq.Ref.ResourceId != nil && sreq.Ref.ResourceId.OpaqueId == "spaceid" {
return &sprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: rootInfo,
}
}
if fi, ok := fileInfoByPath[sreq.Ref.Path]; ok {
return &sprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: fi,
}
}
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: rootInfo}
},
func(_ context.Context, _ *sprovider.StatRequest, _ ...grpc.CallOption) error {
return nil
},
)
// Single ListContainer mock dispatching via map.
gatewayClient.On("ListContainer", mock.Anything, mock.Anything).Return(
func(_ context.Context, req *sprovider.ListContainerRequest, _ ...grpc.CallOption) *sprovider.ListContainerResponse {
opaqueID := req.Ref.ResourceId.OpaqueId
if opaqueID == "spaceid" {
return &sprovider.ListContainerResponse{
Status: status.NewOK(context.Background()),
Infos: dirInfos,
}
}
if fi, ok := fileInfoByDir[opaqueID]; ok {
return &sprovider.ListContainerResponse{
Status: status.NewOK(context.Background()),
Infos: []*sprovider.ResourceInfo{fi},
}
}
return &sprovider.ListContainerResponse{
Status: status.NewOK(context.Background()),
Infos: nil,
}
},
func(_ context.Context, _ *sprovider.ListContainerRequest, _ ...grpc.CallOption) error {
return nil
},
)
// Lookup: root and directories are already indexed with matching mtime.
// Use a map for O(1) lookup instead of linear scan (matters at 10k dirs).
indexedIDs := make(map[string]bool, numDirs+1)
indexedIDs["storageid$spaceid!spaceid"] = true
for i := 0; i < numDirs; i++ {
indexedIDs[fmt.Sprintf("storageid$spaceid!dir-%d", i)] = true
}
indexedResource := &engine.Resource{Document: content.Document{Mtime: indexedMtime}, Extracted: true}
indexClient.On("Lookup", mock.MatchedBy(func(id string) bool {
return indexedIDs[id] || len(id) > 18 // dir-N or file-N IDs
})).Return(func(id string) (*engine.Resource, error) {
if indexedIDs[id] {
return indexedResource, nil
}
// Files are not indexed.
return nil, engine.ErrResourceNotFound
})
// Track Upsert calls — each unindexed file should trigger one.
var upsertCount atomic.Int32
indexClient.On("Upsert", mock.Anything, mock.Anything).Run(func(_ mock.Arguments) {
upsertCount.Add(1)
}).Return(nil)
err := s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"})
Expect(err).ShouldNot(HaveOccurred())
Expect(int(upsertCount.Load())).To(Equal(numDirs), "every unindexed file inside an already-indexed directory must be visited")
})
It("scales linearly when a single directory contains many unindexed files", func() {
// Pessimistic case for a heavy user: one directory holding N files,
// the directory itself already indexed. Runs at three scales and
// prints wall-clock durations so the reviewer can eyeball linearity.
scales := []int{100, 1000, 10000}
type result struct {
numFiles int
duration time.Duration
}
results := make([]result, 0, len(scales))
for _, numFiles := range scales {
upserts, dur, err := runSingleDirScaleTest(numFiles)
Expect(err).ShouldNot(HaveOccurred())
Expect(upserts).To(Equal(numFiles), fmt.Sprintf("all %d unindexed files must be visited", numFiles))
results = append(results, result{numFiles: numFiles, duration: dur})
}
fmt.Fprintf(GinkgoWriter, "\nScale benchmark — single dir with N unindexed files:\n")
for _, r := range results {
fmt.Fprintf(GinkgoWriter, " %6d files → %s\n", r.numFiles, r.duration)
}
})
})
Describe("UpdateTags", func() {
BeforeEach(func() {
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: &sprovider.ResourceInfo{
Id: ri.Id,
ParentId: ri.ParentId,
Path: ri.Path,
Name: "foo.pdf",
Size: ri.Size,
Mtime: ri.Mtime,
Type: sprovider.ResourceType_RESOURCE_TYPE_FILE,
ArbitraryMetadata: &sprovider.ArbitraryMetadata{
Metadata: map[string]string{"tags": "important,work"},
},
},
}, nil)
})
It("updates tags without content extraction when resource is indexed", func() {
indexClient.On("Update", "storageid$spaceid!opaqueid", mock.Anything).Return(nil)
s.UpdateTags(&sprovider.Reference{ResourceId: ri.Id})
extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything, mock.Anything)
indexClient.AssertCalled(GinkgoT(), "Update", "storageid$spaceid!opaqueid", mock.Anything)
})
It("falls back to full UpsertItem when resource is not yet indexed", func() {
indexClient.On("Update", mock.Anything, mock.Anything).Return(engine.ErrResourceNotFound)
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{Name: "foo.pdf"}, nil)
indexClient.On("Upsert", mock.Anything, mock.Anything).Return(nil)
s.UpdateTags(&sprovider.Reference{ResourceId: ri.Id})
extractor.AssertCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything, mock.Anything)
})
It("logs an error and does not fall back on non-retriable errors", func() {
indexClient.On("Update", mock.Anything, mock.Anything).Return(errors.New("connection refused"))
s.UpdateTags(&sprovider.Reference{ResourceId: ri.Id})
extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything, mock.Anything)
indexClient.AssertNotCalled(GinkgoT(), "Upsert", mock.Anything, mock.Anything)
})
})
Describe("Search", func() {
@@ -553,6 +763,129 @@ var _ = Describe("Searchprovider", func() {
})
})
// runSingleDirScaleTest creates a fresh service with mocks and runs IndexSpace
// against a tree: root → big-dir → N files. Root and big-dir are already
// indexed (mtime matches); files are not. Returns the number of Upsert calls,
// the wall-clock duration of IndexSpace, and any error.
func runSingleDirScaleTest(numFiles int) (int, time.Duration, error) {
logger := log.NewLogger()
user := &userv1beta1.User{Id: &userv1beta1.UserId{OpaqueId: "user"}}
selectorKey := fmt.Sprintf("ScaleBench-%d", numFiles)
pool.RemoveSelector(selectorKey + "com.owncloud.api.gateway")
gw := &cs3mocks.GatewayAPIClient{}
gwSelector := pool.GetSelector[gateway.GatewayAPIClient](
selectorKey,
"com.owncloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return gw
},
)
idx := &engineMocks.Engine{}
ext := &contentMocks.Extractor{}
svc := search.NewService(gwSelector, idx, ext, logger, &config.Config{})
gw.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{
Status: status.NewOK(context.Background()),
Token: "authtoken",
}, nil)
gw.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{
Status: status.NewOK(context.Background()),
User: user,
}, nil)
ext.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
idx.On("DocCount").Return(uint64(1), nil)
indexedMtime := time.Unix(5000, 0).UTC().Format(time.RFC3339Nano)
rootInfo := &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
Type: sprovider.ResourceType_RESOURCE_TYPE_CONTAINER,
Path: ".",
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
bigDirInfo := &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "big-dir"},
Type: sprovider.ResourceType_RESOURCE_TYPE_CONTAINER,
Path: "big-dir",
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
fileInfos := make([]*sprovider.ResourceInfo, numFiles)
fileInfoByPath := make(map[string]*sprovider.ResourceInfo, numFiles)
for i := range numFiles {
fi := &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: fmt.Sprintf("file-%d", i)},
ParentId: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "big-dir"},
Type: sprovider.ResourceType_RESOURCE_TYPE_FILE,
Path: fmt.Sprintf("file-%d.pdf", i),
Size: 1024,
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
fileInfos[i] = fi
fileInfoByPath["./big-dir/"+fi.Path] = fi
}
gw.On("Stat", mock.Anything, mock.Anything).Return(
func(_ context.Context, sreq *sprovider.StatRequest, _ ...grpc.CallOption) *sprovider.StatResponse {
if sreq.Ref.ResourceId != nil && sreq.Ref.ResourceId.OpaqueId == "spaceid" {
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: rootInfo}
}
if fi, ok := fileInfoByPath[sreq.Ref.Path]; ok {
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: fi}
}
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: rootInfo}
},
func(_ context.Context, _ *sprovider.StatRequest, _ ...grpc.CallOption) error { return nil },
)
gw.On("ListContainer", mock.Anything, mock.Anything).Return(
func(_ context.Context, req *sprovider.ListContainerRequest, _ ...grpc.CallOption) *sprovider.ListContainerResponse {
switch req.Ref.ResourceId.OpaqueId {
case "spaceid":
return &sprovider.ListContainerResponse{
Status: status.NewOK(context.Background()),
Infos: []*sprovider.ResourceInfo{bigDirInfo},
}
case "big-dir":
return &sprovider.ListContainerResponse{
Status: status.NewOK(context.Background()),
Infos: fileInfos,
}
default:
return &sprovider.ListContainerResponse{
Status: status.NewOK(context.Background()),
}
}
},
func(_ context.Context, _ *sprovider.ListContainerRequest, _ ...grpc.CallOption) error { return nil },
)
indexedIDs := map[string]bool{
"storageid$spaceid!spaceid": true,
"storageid$spaceid!big-dir": true,
}
indexedResource := &engine.Resource{Document: content.Document{Mtime: indexedMtime}, Extracted: true}
idx.On("Lookup", mock.Anything).Return(func(id string) (*engine.Resource, error) {
if indexedIDs[id] {
return indexedResource, nil
}
return nil, engine.ErrResourceNotFound
})
var upsertCount atomic.Int32
idx.On("Upsert", mock.Anything, mock.Anything).Run(func(_ mock.Arguments) {
upsertCount.Add(1)
}).Return(nil)
start := time.Now()
err := svc.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"})
dur := time.Since(start)
return int(upsertCount.Load()), dur, err
}
var _ = DescribeTable("Parse Scope",
func(pattern, wantSearch, wantScope string) {
gotSearch, gotScope := search.ParseScope(pattern)
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-16 00:18+0000\n"
"POT-Creation-Date: 2026-03-08 00:34+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Ivan Fustero, 2026\n"
"Language-Team: Catalan (https://app.transifex.com/owncloud-org/teams/6149/ca/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: German (https://app.transifex.com/owncloud-org/teams/6149/de/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: English (United Kingdom) (https://app.transifex.com/owncloud-org/teams/6149/en_GB/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: English (United States) (https://app.transifex.com/owncloud-org/teams/6149/en_US/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Spanish (https://app.transifex.com/owncloud-org/teams/6149/es/)\n"
@@ -12,7 +12,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-13 00:17+0000\n"
"POT-Creation-Date: 2026-03-05 14:42+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Cesare Capoferri, 2026\n"
"Language-Team: Italian (https://app.transifex.com/owncloud-org/teams/6149/it/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Portuguese (https://app.transifex.com/owncloud-org/teams/6149/pt/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Portuguese (Brazil) (https://app.transifex.com/owncloud-org/teams/6149/pt_BR/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Russian (https://app.transifex.com/owncloud-org/teams/6149/ru/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Albanian (https://app.transifex.com/owncloud-org/teams/6149/sq/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:10+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Ukrainian (https://app.transifex.com/owncloud-org/teams/6149/uk/)\n"
+86
View File
@@ -184,6 +184,92 @@ ocis storage-users uploads delete-stale-nodes --dry-run=false --verbose
```
### Check and Inspect the Blobstore
The `blobstore` command group provides tools to verify connectivity to the configured blobstore and to inspect individual blobs. Both the `ocis` and `s3ng` storage drivers are supported.
```bash
ocis storage-users blobstore <command>
```
```plaintext
COMMANDS:
check check blobstore connectivity via an upload/download/delete round-trip
get get a blob from the blobstore by ID
```
#### Check
Verifies that the blobstore is reachable and fully operational by uploading a random blob, downloading and verifying it, then deleting it again. All three steps must succeed.
```bash
ocis storage-users blobstore check [command options]
```
```
OPTIONS:
--blob-size value size of the random blob to upload, e.g. 64, 1KB, 1MB, 4MiB (default: "64")
--help, -h show help
```
**Examples:**
```bash
# Basic connectivity check using the default 64-byte payload
ocis storage-users blobstore check
# Use a larger payload to also stress-test throughput
ocis storage-users blobstore check --blob-size=4MiB
```
```plaintext
Uploading test blob: spaceID=a5c9bd5c-7348-4e9e-a462-d4d9e5287d01 blobID=3f1e5a82-b7e3-4c91-a110-1d5e2f3a4b6c
Upload: OK
Download and verify: OK
Delete: OK
Blobstore check successful.
```
#### Get
Downloads a single blob by its ID to verify it exists and is readable. Useful when investigating errors in log lines that contain a blob path such as:
```
decomposedfs: error download blob '04ba5496-...': blob path: b19ec764-.../61/03/ab/c3/-b08a-...: The specified key does not exist.
```
The blob can be identified either by passing the raw path from the log line with `--path`, or by supplying `--blob-id` and `--space-id` individually.
```bash
ocis storage-users blobstore get [command options]
```
```
OPTIONS:
--path value blobstore path as it appears in log lines; spaceID and blobID are extracted automatically.
Supports both s3ng format ("<spaceID>/<pathified_blobID>") and ocis format
("…/spaces/<pathified_spaceID>/blobs/<pathified_blobID>").
--blob-id value blob ID to download (required when --path is not set)
--space-id value space ID the blob belongs to (required when --path is not set)
--blob-size value expected blob size in bytes; only needed for the s3ng driver when the size is known
upfront. If omitted or wrong, a size mismatch triggers one automatic retry with the
actual size returned by s3ng. (default: 0)
--help, -h show help
```
**Examples:**
```bash
# Identify a blob using the path from a log line (s3ng)
ocis storage-users blobstore get --path="b19ec764-5398-458a-8ff1-1925bd906999/61/03/ab/c3/-b08a-4556-9937-2bf3065c1202"
# Identify a blob using the full filesystem path from a log line (ocis driver)
ocis storage-users blobstore get --path="/var/lib/ocis/storage/users/spaces/b1/9ec764-5398-458a-8ff1-1925bd906999/blobs/61/03/ab/c3/-b08a-4556-9937-2bf3065c1202"
# Identify a blob using explicit IDs
ocis storage-users blobstore get --space-id=b19ec764-5398-458a-8ff1-1925bd906999 --blob-id=6103abc3-b08a-4556-9937-2bf3065c1202
```
### Manage Spaces
This command set provides commands to manage spaces, including purging disabled spaces that exceed the retention period.
@@ -0,0 +1,286 @@
package command
import (
"bytes"
"crypto/rand"
"fmt"
"io"
"os"
"regexp"
"strings"
"github.com/google/uuid"
"github.com/owncloud/ocis/v2/ocis-pkg/config/configlog"
"github.com/owncloud/ocis/v2/services/storage-users/pkg/config"
"github.com/owncloud/ocis/v2/services/storage-users/pkg/config/parser"
"github.com/owncloud/reva/v2/pkg/bytesize"
ocisbs "github.com/owncloud/reva/v2/pkg/storage/fs/ocis/blobstore"
s3bs "github.com/owncloud/reva/v2/pkg/storage/fs/s3ng/blobstore"
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/node"
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/tree"
"github.com/urfave/cli/v2"
)
// Blobstore is the entry point for the blobstore command group.
func Blobstore(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "blobstore",
Usage: "manage the blobstore",
Subcommands: []*cli.Command{
BlobstoreCheck(cfg),
BlobstoreGet(cfg),
},
}
}
// BlobstoreCheck uploads random bytes to a random path, downloads and
// verifies them, then deletes them again. All three steps must succeed.
func BlobstoreCheck(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "check",
Usage: "check blobstore connectivity via an upload/download/delete round-trip",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "blob-size",
Usage: "size of the random blob to upload, e.g. 64, 1KB, 1MB, 4MiB",
Value: "64",
},
},
Before: func(c *cli.Context) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg))
},
Action: func(c *cli.Context) error {
bs, err := initBlobstore(cfg)
if err != nil {
return err
}
size, err := bytesize.Parse(c.String("blob-size"))
if err != nil {
return fmt.Errorf("invalid --blob-size %q: %w", c.String("blob-size"), err)
}
return runBlobstoreRoundTrip(bs, int(size))
},
}
}
// BlobstoreGet downloads a specific blob by its ID to verify it is readable.
func BlobstoreGet(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "get",
Usage: "get a blob from the blobstore by ID",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "path",
Usage: "blobstore path as it appears in log lines (e.g. \"<spaceID>/<pathified_blobID>\" for s3ng or \"…/spaces/<pathified_spaceID>/blobs/<pathified_blobID>\" for ocis); extracts --blob-id and --space-id automatically",
},
&cli.StringFlag{
Name: "blob-id",
Usage: "blob ID to download (required when --path is not set)",
},
&cli.StringFlag{
Name: "space-id",
Usage: "space ID the blob belongs to (required when --path is not set)",
},
&cli.Int64Flag{
Name: "blob-size",
Usage: "expected blob size in bytes; only needed for the s3ng driver when the size is known upfront. " +
"If omitted or wrong, a size mismatch will trigger one automatic retry with the actual size returned by s3ng.",
},
},
Before: func(c *cli.Context) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg))
},
Action: func(c *cli.Context) error {
bs, err := initBlobstore(cfg)
if err != nil {
return err
}
blobID, spaceID := c.String("blob-id"), c.String("space-id")
if c.IsSet("path") {
spaceID, blobID, err = parseBlobPath(c.String("path"))
if err != nil {
return err
}
}
if blobID == "" || spaceID == "" {
return fmt.Errorf("either --path or both --blob-id and --space-id must be set")
}
return downloadBlob(bs, blobID, spaceID, c.Int64("blob-size"))
},
}
}
// parseBlobPath extracts spaceID and blobID from a blobstore path as it
// appears in log lines. Two formats are supported:
//
// - S3NG: "<spaceID>/<pathified_blobID>"
// e.g. "b19ec764-5398-458a-8ff1-1925bd906999/61/03/ab/c3/-b08a-4556-9937-2bf3065c1202"
//
// - OCIS: any path containing "/spaces/<pathified_spaceID>/blobs/<pathified_blobID>"
// e.g. "/var/lib/ocis/storage/users/spaces/b1/9ec764-.../blobs/61/03/ab/c3/-b08a-..."
func parseBlobPath(path string) (spaceID, blobID string, err error) {
// OCIS paths contain both /spaces/ and /blobs/ as structural markers.
if _, rest, ok := strings.Cut(path, "/spaces/"); ok {
pathifiedSpaceID, pathifiedBlobID, ok := strings.Cut(rest, "/blobs/")
if !ok {
return "", "", fmt.Errorf("cannot parse ocis blob path %q: missing /blobs/ segment", path)
}
spaceID = depathify(pathifiedSpaceID, 1)
blobID = depathify(pathifiedBlobID, 4)
return
}
// S3NG paths: <spaceID>/<pathified_blobID>
var pathifiedBlobID string
spaceID, pathifiedBlobID, _ = strings.Cut(path, "/")
if pathifiedBlobID == "" {
return "", "", fmt.Errorf("cannot parse s3ng blob path %q: expected <spaceID>/<pathified_blobID>", path)
}
blobID = depathify(pathifiedBlobID, 4)
return
}
// depathify reverses the effect of lookup.Pathify(id, depth, 2):
// it strips the directory separators that were inserted every two characters
// up to the given depth.
// e.g. depathify("61/03/ab/c3/-b08a-4556-9937-2bf3065c1202", 4)
//
// → "6103abc3-b08a-4556-9937-2bf3065c1202"
func depathify(path string, depth int) string {
parts := strings.SplitN(path, "/", depth+1)
return strings.Join(parts, "")
}
// initBlobstore builds a tree.Blobstore from the service configuration.
// Only the "ocis" and "s3ng" drivers are supported.
func initBlobstore(cfg *config.Config) (tree.Blobstore, error) {
switch cfg.Driver {
case "ocis":
return ocisbs.New(cfg.Drivers.OCIS.Root)
case "s3ng":
return s3bs.New(
cfg.Drivers.S3NG.Endpoint,
cfg.Drivers.S3NG.Region,
cfg.Drivers.S3NG.Bucket,
cfg.Drivers.S3NG.AccessKey,
cfg.Drivers.S3NG.SecretKey,
s3bs.Options{
DisableContentSha256: cfg.Drivers.S3NG.DisableContentSha256,
DisableMultipart: cfg.Drivers.S3NG.DisableMultipart,
SendContentMd5: cfg.Drivers.S3NG.SendContentMd5,
ConcurrentStreamParts: cfg.Drivers.S3NG.ConcurrentStreamParts,
NumThreads: cfg.Drivers.S3NG.NumThreads,
PartSize: cfg.Drivers.S3NG.PartSize,
},
)
default:
return nil, fmt.Errorf("blobstore operations are not supported for driver '%s'", cfg.Driver)
}
}
// blobSizeMismatchRe matches the error produced by the s3ng blobstore when the
// retrieved object size does not match node.Blobsize, and captures the actual size.
var blobSizeMismatchRe = regexp.MustCompile(`blob has unexpected size\. \d+ bytes expected, got (\d+) bytes`)
// downloadBlob downloads a single blob identified by blobID, drains the reader
// to surface any streaming errors, then closes it.
// If the s3ng blobstore rejects the download due to a size mismatch, the actual
// size is extracted from the error and the download is retried with the correct value.
func downloadBlob(bs tree.Blobstore, blobID, spaceID string, blobSize int64) error {
n := &node.Node{
BlobID: blobID,
SpaceID: spaceID,
Blobsize: blobSize,
}
rc, err := bs.Download(n)
if err != nil {
if m := blobSizeMismatchRe.FindStringSubmatch(err.Error()); m != nil {
fmt.Printf("blob size mismatch, retrying with actual size %s bytes\n", m[1])
if _, err := fmt.Sscan(m[1], &n.Blobsize); err != nil {
return fmt.Errorf("download failed: could not parse actual blob size %q: %w", m[1], err)
}
rc, err = bs.Download(n)
}
if err != nil {
return fmt.Errorf("download failed: %w", err)
}
}
defer func() {
if cerr := rc.Close(); cerr != nil {
fmt.Fprintf(os.Stderr, "warning: failed to close blob reader for blob %s in space %s: %v\n", blobID, spaceID, cerr)
}
}()
if _, err := io.Copy(io.Discard, rc); err != nil {
return fmt.Errorf("download failed while reading: %w", err)
}
fmt.Println("Download: OK")
return nil
}
// runBlobstoreRoundTrip uploads random data, verifies it can be retrieved, and
// then removes it again. All three steps must succeed for the check to pass.
func runBlobstoreRoundTrip(bs tree.Blobstore, blobSize int) error {
// 1. Generate random bytes that serve as the test payload.
data := make([]byte, blobSize)
if _, err := rand.Read(data); err != nil {
return fmt.Errorf("failed to generate random data: %w", err)
}
// Write the payload to a temporary file. The OCIS blobstore may rename
// (move) this file into the blobstore, so os.Remove in the defer is a
// no-op for that driver – which is fine.
tmpFile, err := os.CreateTemp("", "ocis-blobstore-check-*")
if err != nil {
return fmt.Errorf("failed to create temp file: %w", err)
}
tmpPath := tmpFile.Name()
defer os.Remove(tmpPath) // best-effort cleanup
if _, err := tmpFile.Write(data); err != nil {
tmpFile.Close()
return fmt.Errorf("failed to write temp file: %w", err)
}
if err := tmpFile.Close(); err != nil {
return fmt.Errorf("failed to close temp file: %w", err)
}
// 2. Build a test node with random identifiers.
testNode := &node.Node{
SpaceID: uuid.New().String(),
BlobID: uuid.New().String(),
Blobsize: int64(len(data)),
}
fmt.Printf("Uploading test blob: spaceID=%s blobID=%s\n", testNode.SpaceID, testNode.BlobID)
// 3. Upload.
if err := bs.Upload(testNode, tmpPath); err != nil {
return fmt.Errorf("upload failed: %w", err)
}
fmt.Println("Upload: OK")
// 4. Download and verify.
rc, err := bs.Download(testNode)
if err != nil {
_ = bs.Delete(testNode)
return fmt.Errorf("download failed: %w", err)
}
downloaded, err := io.ReadAll(rc)
rc.Close()
if err != nil {
_ = bs.Delete(testNode)
return fmt.Errorf("failed to read downloaded data: %w", err)
}
if !bytes.Equal(data, downloaded) {
_ = bs.Delete(testNode)
return fmt.Errorf("data integrity check failed: downloaded content does not match uploaded content")
}
fmt.Println("Download and verify: OK")
// 5. Delete.
if err := bs.Delete(testNode); err != nil {
return fmt.Errorf("delete failed: %w", err)
}
fmt.Println("Delete: OK")
fmt.Println("Blobstore check successful.")
return nil
}
@@ -0,0 +1,104 @@
package command
import (
"testing"
)
func Test_depathify(t *testing.T) {
tests := []struct {
name string
path string
depth int
want string
}{
{
name: "blob id depth 4",
path: "61/03/ab/c3/-b08a-4556-9937-2bf3065c1202",
depth: 4,
want: "6103abc3-b08a-4556-9937-2bf3065c1202",
},
{
name: "space id depth 1",
path: "b1/9ec764-5398-458a-8ff1-1925bd906999",
depth: 1,
want: "b19ec764-5398-458a-8ff1-1925bd906999",
},
{
name: "depth 0 is a no-op",
path: "abcd-1234",
depth: 0,
want: "abcd-1234",
},
{
name: "fewer segments than depth leaves remainder intact",
path: "ab/cd",
depth: 4,
want: "abcd",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := depathify(tt.path, tt.depth)
if got != tt.want {
t.Errorf("depathify(%q, %d) = %q, want %q", tt.path, tt.depth, got, tt.want)
}
})
}
}
func Test_parseBlobPath(t *testing.T) {
tests := []struct {
name string
path string
wantSpaceID string
wantBlobID string
wantErr bool
}{
{
// s3ng: <spaceID>/<pathified_blobID>
name: "s3ng format",
path: "b19ec764-5398-458a-8ff1-1925bd906999/61/03/ab/c3/-b08a-4556-9937-2bf3065c1202",
wantSpaceID: "b19ec764-5398-458a-8ff1-1925bd906999",
wantBlobID: "6103abc3-b08a-4556-9937-2bf3065c1202",
},
{
// ocis: …/spaces/<pathified_spaceID>/blobs/<pathified_blobID>
name: "ocis filesystem format",
path: "/var/lib/ocis/storage/users/spaces/b1/9ec764-5398-458a-8ff1-1925bd906999/blobs/61/03/ab/c3/-b08a-4556-9937-2bf3065c1202",
wantSpaceID: "b19ec764-5398-458a-8ff1-1925bd906999",
wantBlobID: "6103abc3-b08a-4556-9937-2bf3065c1202",
},
{
name: "ocis format missing /blobs/ segment",
path: "/var/lib/ocis/storage/users/spaces/b1/9ec764-5398-458a-8ff1-1925bd906999/noblobs/61/03/ab/c3",
wantErr: true,
},
{
name: "s3ng format missing blob id (no slash after spaceID)",
path: "b19ec764-5398-458a-8ff1-1925bd906999",
wantErr: true,
},
{
name: "empty path",
path: "",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotSpaceID, gotBlobID, err := parseBlobPath(tt.path)
if (err != nil) != tt.wantErr {
t.Fatalf("parseBlobPath(%q) error = %v, wantErr %v", tt.path, err, tt.wantErr)
}
if err != nil {
return
}
if gotSpaceID != tt.wantSpaceID {
t.Errorf("parseBlobPath(%q) spaceID = %q, want %q", tt.path, gotSpaceID, tt.wantSpaceID)
}
if gotBlobID != tt.wantBlobID {
t.Errorf("parseBlobPath(%q) blobID = %q, want %q", tt.path, gotBlobID, tt.wantBlobID)
}
})
}
}
@@ -18,6 +18,7 @@ func GetCommands(cfg *config.Config) cli.Commands {
Uploads(cfg),
TrashBin(cfg),
Spaces(cfg),
Blobstore(cfg),
// infos about this service
Health(cfg),
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:52+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Bulgarian (https://app.transifex.com/owncloud-org/teams/6149/bg/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:52+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: Catalan (https://app.transifex.com/owncloud-org/teams/6149/ca/)\n"
@@ -11,7 +11,7 @@ msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: EMAIL\n"
"POT-Creation-Date: 2026-02-12 00:19+0000\n"
"POT-Creation-Date: 2026-03-05 00:04+0000\n"
"PO-Revision-Date: 2026-01-02 10:52+0000\n"
"Last-Translator: Martin <github@diemattels.at>, 2026\n"
"Language-Team: German (https://app.transifex.com/owncloud-org/teams/6149/de/)\n"
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff. Show more