Compare commits

..
Author SHA1 Message Date
Roman Perekhod 0151111d59 fix persanal space creating 2026-03-05 14:47:39 +01:00
Roman Perekhod b44091a077 fix responce 2026-03-04 16:20:07 +01:00
Roman Perekhod ad5268dd6f added protected-personal autoprovision
added MFA enforcement for the ocdav and arciver
2026-03-04 16:20:07 +01:00
Roman Perekhod 34f38b8f66 added protected-* spaces get and create 2026-03-04 16:20:07 +01:00
Roman Perekhod 21310ea0e8 refactor the validation 2026-03-04 16:20:07 +01:00
150 changed files with 3569 additions and 4231 deletions

No files matched your search

+214 -95
View File
@@ -33,9 +33,7 @@ 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"
# 1.4.0 is required due to minio compatibility
PLUGINS_S3 = "plugins/s3:1.4.0"
PLUGINS_S3 = "plugins/s3:1"
PLUGINS_S3_CACHE = "plugins/s3-cache:1"
REDIS = "redis:6-alpine"
SONARSOURCE_SONAR_SCANNER_CLI = "sonarsource/sonar-scanner-cli:11.0"
@@ -119,7 +117,6 @@ config = {
],
"skip": False,
"withRemotePhp": [False],
"k8s": True,
"emailNeeded": True,
"extraEnvironment": {
"EMAIL_HOST": EMAIL_SMTP_HOST,
@@ -166,7 +163,6 @@ config = {
"apiActivities",
],
"skip": False,
"k8s": True,
},
"groupAndSearch1": {
"suites": [
@@ -211,7 +207,6 @@ config = {
],
"skip": False,
"withRemotePhp": [False],
"k8s": True,
},
"sharingNgLinkShare": {
"suites": [
@@ -310,7 +305,6 @@ 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",
},
},
@@ -376,7 +370,6 @@ config = {
"coreApiWebdavMove2",
],
"skip": False,
"k8s": True,
},
"7": {
"suites": [
@@ -899,7 +892,6 @@ def uploadScanResults(ctx):
"git checkout $DRONE_COMMIT",
],
},
] + skipIfUnchanged(ctx, "unit-tests") + [
{
"name": "sync-from-cache",
"image": MINIO_MC,
@@ -1131,28 +1123,19 @@ 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],
@@ -1162,6 +1145,15 @@ 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"],
@@ -1186,18 +1178,17 @@ 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 #
@@ -1308,6 +1299,9 @@ 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 [{
@@ -1515,20 +1509,23 @@ 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"],
@@ -1541,14 +1538,13 @@ 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 #
@@ -1699,14 +1695,13 @@ 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() + \
(waitForServices("tika", ["tika:9998"]) if params["tikaNeeded"] else []) + \
(tikaService() 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"])
@@ -1850,7 +1845,7 @@ def multiServiceE2ePipeline(ctx):
restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin/ocis") + \
restoreWebCache() + \
restoreWebPnpmCache() + \
waitForServices("tika", ["tika:9998"]) + \
tikaService() + \
ocisServer(extra_server_environment = extra_server_environment, tika_enabled = params["tikaNeeded"], debug = False) + \
storage_users_services + \
[{
@@ -1884,7 +1879,6 @@ def multiServiceE2ePipeline(ctx):
},
pipelineVolumeGo,
],
"services": tikaService(),
})
return pipelines
@@ -2869,52 +2863,41 @@ def startOcisService(service = None, name = None, environment = {}, volumes = []
},
]
def ocisServerK8s(federation = False, antivirus = False, email = False, tika = False, wopi = False, auth_app = False):
def ocisServerK8s(federation = False, antivirus = False, email = False, tika = False, wopi = 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 = []
environment = {
"ENABLE_ANTIVIRUS": antivirus,
"ENABLE_EMAIL": email,
"ENABLE_TIKA": tika,
"ENABLE_WOPI": wopi,
"ENABLE_OCM": federation,
"ENABLE_AUTH_APP": auth_app,
}
steps = prepareOcisDeployment()
if antivirus:
external_servers.append(["clamav", 3310])
if tika:
external_servers.append(["tika", 9998])
steps += enableAntivirusServiceK8s()
if email:
external_servers.append([EMAIL_SMTP_HOST, EMAIL_SMTP_PORT])
steps += enableEmailServiceK8s()
if tika:
steps += enableTikaServiceK8s()
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 []) + \
setupConfigMapsK8s(name) + \
(setupConfigMapsK8s(fed_name) if federation else []) + \
setupOcisConfigMaps(name) + \
(setupOcisConfigMaps(fed_name) if federation else []) + \
expose_ext_server_step + \
deployOcisK8s(name) + \
(deployOcisK8s(fed_name) if federation else []) + \
streamOcisLogsK8s(name) + \
(streamOcisLogsK8s(fed_name) if federation else []) + \
deployOcis(name) + \
(deployOcis(fed_name) if federation else []) + \
streamK8sOcisLogs(name) + \
waitForOcis(name, url) + \
(waitForOcis(fed_name, fed_url) if federation else []) + \
ociswrapperK8s(name)
return steps
(waitForOcis(fed_name, fed_url) if federation else [])
return steps + ociswrapperK8s(name)
def redis():
return [
@@ -3608,12 +3591,30 @@ 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 [
{
@@ -3669,6 +3670,13 @@ 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():
@@ -3957,7 +3965,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 '9100-9399:30100-30399@loadbalancer' " +
"-p '80:80@loadbalancer' -p '443:443@loadbalancer' -p '8025:32025@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
@@ -4010,28 +4018,56 @@ def waitK3sCluster(name = OCIS_SERVER_NAME):
"image": K3D_IMAGE,
"user": "root",
"commands": [
"export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name,
"export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-" + OCIS_SERVER_NAME + ".yaml",
"timeout 300 bash -c 'until test -f $${KUBECONFIG}; do sleep 1; done'",
"kubectl config view",
"kubectl get pods -A",
],
}]
def prepareChartsK8s(environment = []):
def prepareOcisDeployment():
commands = [
# build ocis wrapper
"make -C %s build" % dirs["ocisWrapper"],
# get ocis charts
"[ ! -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"]),
"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",
]
return [{
"name": "prepare-ocis-deployment",
"image": OC_CI_GOLANG,
"environment": environment,
"commands": commands,
"volumes": [
{
@@ -4041,15 +4077,18 @@ def prepareChartsK8s(environment = []):
],
}]
def setupConfigMapsK8s(name = OCIS_SERVER_NAME):
def setupOcisConfigMaps(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 [{
@@ -4059,27 +4098,39 @@ def setupConfigMapsK8s(name = OCIS_SERVER_NAME):
"commands": commands,
}]
def deployOcisK8s(name = OCIS_SERVER_NAME):
def deployOcis(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": [
"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",
"commands": commands,
"volumes": [
{
"name": "gopath",
"path": "/go",
},
],
}]
def streamOcisLogsK8s(name = OCIS_SERVER_NAME):
def streamK8sOcisLogs(name = OCIS_SERVER_NAME):
return [{
"name": "%s-logs" % name,
"image": OC_CI_ALPINE,
@@ -4090,6 +4141,62 @@ def streamOcisLogsK8s(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",
@@ -4110,6 +4217,18 @@ 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):
+1 -3
View File
@@ -64,6 +64,4 @@ go.work.sum
.envrc
CLAUDE.md
.claude/
# charts
ocis-charts/
.agents/
-141
View File
@@ -69,7 +69,6 @@ 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)
@@ -77,34 +76,15 @@ 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
@@ -182,63 +162,6 @@ 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
@@ -288,70 +211,6 @@ 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,5 +3,4 @@ Enhancement: Bump Reva version
bumped reva version
https://github.com/owncloud/ocis/pull/12051
https://github.com/owncloud/ocis/pull/12087
@@ -1,13 +0,0 @@
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
@@ -1,11 +0,0 @@
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
@@ -1,24 +0,0 @@
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
@@ -1,5 +0,0 @@
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
@@ -1,26 +0,0 @@
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
@@ -1,11 +0,0 @@
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
@@ -1,5 +0,0 @@
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
@@ -1,11 +0,0 @@
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
@@ -1,11 +0,0 @@
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
@@ -1,13 +0,0 @@
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,7 +13,6 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''self'''
frame-src:
@@ -11,7 +11,6 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''none'''
frame-src:
@@ -10,7 +10,6 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''self'''
frame-src:
@@ -11,7 +11,6 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''none'''
frame-src:
@@ -9,7 +9,6 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''self'''
frame-src:
@@ -9,7 +9,6 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''self'''
frame-src:
@@ -9,7 +9,6 @@ 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-20260304131727-ce3149532498
github.com/owncloud/reva/v2 v2.0.0-20260303153746-059bcdfc4fbb
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-20260304131727-ce3149532498 h1:ozyudPff1XLWSeTDW4ajT1tCoSQf18cFQRxtLWFCNbk=
github.com/owncloud/reva/v2 v2.0.0-20260304131727-ce3149532498/go.mod h1:+rCy6oGYb2/qs5gmQa8y/pHARw634vB73MZGDY2SBIQ=
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/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,14 +60,6 @@ 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 {
@@ -89,8 +81,6 @@ 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:
@@ -107,8 +97,6 @@ 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,7 +21,6 @@ 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"),
)...,
)
}
+1 -11
View File
@@ -2,7 +2,6 @@ package kql
import (
"fmt"
"strconv"
"time"
"github.com/jinzhu/now"
@@ -26,7 +25,7 @@ func toNodes[T ast.Node](in interface{}) ([]T, error) {
return []T{v}, nil
case []T:
return v, nil
case []*ast.OperatorNode, []*ast.DateTimeNode, []*ast.NumericNode:
case []*ast.OperatorNode, []*ast.DateTimeNode:
return toNodes[T](v)
case []interface{}:
var nodes []T
@@ -71,15 +70,6 @@ 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,7 +40,6 @@ GroupNode <-
PropertyRestrictionNodes <-
YesNoPropertyRestrictionNode /
DateTimeRestrictionNode /
NumericRestrictionNode /
TextPropertyRestrictionNode
YesNoPropertyRestrictionNode <-
@@ -70,16 +69,6 @@ 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)
@@ -235,11 +224,6 @@ 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,97 +858,6 @@ 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,35 +73,6 @@ 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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 14:42+0000\n"
"POT-Creation-Date: 2026-02-13 00:17+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-03-05 14:42+0000\n"
"POT-Creation-Date: 2026-02-13 00:17+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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,6 +160,14 @@ 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-03-08 00:34+0000\n"
"POT-Creation-Date: 2026-02-16 00:18+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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"
+45 -22
View File
@@ -37,11 +37,13 @@ import (
)
const (
_spaceTypePersonal = "personal"
_spaceTypeProject = "project"
_spaceTypeVirtual = "virtual"
_spaceTypeMountpoint = "mountpoint"
_spaceStateTrashed = "trashed"
_spaceTypePersonal = "personal"
_spaceTypeProject = "project"
_spaceTypeProtectedPersonal = "protected-personal"
_spaceTypeProtectedProject = "protected-project"
_spaceTypeVirtual = "virtual"
_spaceTypeMountpoint = "mountpoint"
_spaceStateTrashed = "trashed"
_sortDescending = "desc"
)
@@ -78,7 +80,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(r, false, APIVersion_1)
spaces, errCode := g.getDrives(w, r, false, APIVersion_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -99,7 +101,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(r, false, APIVersion_1_Beta_1)
spaces, errCode := g.getDrives(w, r, false, APIVersion_1_Beta_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -133,14 +135,11 @@ 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 !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)
if !g.validateMFA(r, w) {
return
}
spaces, errCode := g.getDrives(r, true, APIVersion_1)
spaces, errCode := g.getDrives(w, r, true, APIVersion_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -160,14 +159,11 @@ 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 !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)
if !g.validateMFA(r, w) {
return
}
drives, errCode := g.getDrives(r, true, APIVersion_1_Beta_1)
drives, errCode := g.getDrives(w, r, true, APIVersion_1_Beta_1)
if errCode != nil {
errorcode.RenderError(w, r, errCode)
return
@@ -184,7 +180,7 @@ func (g Graph) GetAllDrivesV1Beta1(w http.ResponseWriter, r *http.Request) {
}
// getDrives implements the Service interface.
func (g Graph) getDrives(r *http.Request, unrestricted bool, apiVersion APIVersion) ([]*libregraph.Drive, error) {
func (g Graph) getDrives(w http.ResponseWriter, r *http.Request, unrestricted bool, apiVersion APIVersion) ([]*libregraph.Drive, error) {
logger := g.logger.SubloggerWithRequestID(r.Context())
logger.Info().
Interface("query", r.URL.Query()).
@@ -197,6 +193,10 @@ func (g Graph) getDrives(r *http.Request, unrestricted bool, apiVersion APIVersi
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,6 +409,8 @@ 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")
@@ -468,7 +470,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 {
if t := r.URL.Query().Get(TemplateParameter); t != "" && (driveType == _spaceTypeProject || driveType == _spaceTypeProtectedProject) {
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")
@@ -596,7 +598,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 = _spaceTypeProject
dt = sp.SpaceType
}
}
}
@@ -781,7 +783,25 @@ func (g Graph) ListStorageSpacesWithFilters(ctx context.Context, filters []*stor
return nil, err
}
res, err := gatewayClient.ListStorageSpaces(ctx, lReq)
return res, err
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
}
func (g Graph) cs3StorageSpaceToDrive(ctx context.Context, baseURL *url.URL, space *storageprovider.StorageSpace, apiVersion APIVersion) (*libregraph.Drive, error) {
@@ -1016,9 +1036,12 @@ 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 {
if typ == _spaceTypeProject || typ == _spaceTypeProtectedProject {
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)
+111 -13
View File
@@ -21,6 +21,7 @@ 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"
@@ -154,38 +155,135 @@ func parseIDParam(r *http.Request, param string) (storageprovider.ResourceId, er
return id, nil
}
// regular users can only search for terms with a minimum length
func hasAcceptableSearch(query *godata.GoDataQuery, minSearchLength int) bool {
// 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 {
if query == nil || query.Search == nil {
return false
return errors.New("search term too short")
}
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
}
return len(query.Search.RawValue) >= minSearchLength
if len(query.Search.RawValue) < minSearchLength {
return errors.New("search term too short")
}
return nil
}
// regular users can only filter by userType
func hasAcceptableFilter(query *godata.GoDataQuery) bool {
// FilterValidator validates the filter query.
type FilterValidator struct{}
// Validate checks if the filter applies forbidden elements.
func (v FilterValidator) Validate(query *godata.GoDataQuery) error {
switch {
case query == nil || query.Filter == nil:
return true
return nil
case query.Filter.Tree.Token.Type != godata.ExpressionTokenLogical:
return false
return errors.New("filter has forbidden elements for regular users")
case query.Filter.Tree.Token.Value != "eq":
return false
return errors.New("filter has forbidden elements for regular users")
case query.Filter.Tree.Children[0].Token.Value != "userType":
return false
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
}
// 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
// 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
}
+104
View File
@@ -192,6 +192,63 @@ 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),
@@ -811,6 +868,53 @@ 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),
+3 -30
View File
@@ -10,7 +10,6 @@ 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"
@@ -32,35 +31,9 @@ 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 !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
}
if !g.validateQuery(r, w, odataReq.Query, SearchValidator{MinLength: g.config.API.IdentitySearchMinLength}, BasicQueryValidator{}) {
return
}
groups, err := g.identityBackend.GetGroups(r.Context(), odataReq)
@@ -70,7 +43,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 !ctxHasFullPerms {
if !g.contextUserHasFullAccountPerms(r.Context()) {
finalGroups := make([]*libregraph.Group, len(groups))
for i, grp := range groups {
finalGroups[i] = &libregraph.Group{
+4 -46
View File
@@ -22,7 +22,6 @@ 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"
@@ -324,51 +323,8 @@ func (g Graph) GetUsers(w http.ResponseWriter, r *http.Request) {
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
}
if !g.validateQuery(r, w, odataReq.Query, SearchValidator{MinLength: g.config.API.IdentitySearchMinLength}, FilterValidator{}, BasicQueryValidator{}) {
return
}
logger.Debug().Interface("query", r.URL.Query()).Msg("calling get users on backend")
@@ -435,6 +391,8 @@ 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-03-08 00:34+0000\n"
"POT-Creation-Date: 2026-02-16 00:18+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-08 00:34+0000\n"
"POT-Creation-Date: 2026-02-16 00:18+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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,7 +9,6 @@ directives:
- '''none'''
font-src:
- '''self'''
- 'data:'
frame-ancestors:
- '''self'''
frame-src:
+36 -5
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,10 +72,41 @@ 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")
} 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")
}
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")
}
}
}
@@ -58,7 +58,6 @@ 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,27 +84,3 @@ 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)")
}
+1 -9
View File
@@ -75,11 +75,7 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
var reader io.Reader = data
if ri.Size > t.ContentExtractionSizeLimit {
limit := t.ContentExtractionSizeLimit
if limit > math.MaxInt64 {
limit = math.MaxInt64
}
reader = io.LimitReader(data, int64(limit)) //nolint:gosec // overflow guarded above
reader = io.LimitReader(data, int64(t.ContentExtractionSizeLimit)) //nolint:gosec // ContentExtractionSizeLimit is a config value, never exceeds int64 max
}
metas, err := t.tika.MetaRecursive(ctx, reader)
@@ -87,10 +83,6 @@ 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))
+12 -83
View File
@@ -2,7 +2,7 @@ package engine
import (
"context"
"fmt"
"errors"
"math"
"path"
"reflect"
@@ -16,7 +16,6 @@ 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"
@@ -35,8 +34,6 @@ 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
@@ -74,11 +71,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 = lowercaseKeywordAnalyzer
nameMapping.Analyzer = "lowercaseKeyword"
lowercaseMapping := bleve.NewTextFieldMapping()
lowercaseMapping.IncludeInAll = false
lowercaseMapping.Analyzer = lowercaseKeywordAnalyzer
lowercaseMapping.Analyzer = "lowercaseKeyword"
fulltextFieldMapping := bleve.NewTextFieldMapping()
fulltextFieldMapping.Analyzer = "fulltext"
@@ -94,7 +91,7 @@ func BuildBleveMapping() (mapping.IndexMapping, error) {
photoStringMapping := bleve.NewTextFieldMapping()
photoStringMapping.Store = true
photoStringMapping.Index = true
photoStringMapping.Analyzer = lowercaseKeywordAnalyzer
photoStringMapping.Analyzer = keyword.Name
photoNumericMapping := bleve.NewNumericFieldMapping()
photoNumericMapping.Store = true
photoNumericMapping.Index = true
@@ -126,7 +123,7 @@ func BuildBleveMapping() (mapping.IndexMapping, error) {
indexMapping := bleve.NewIndexMapping()
indexMapping.DefaultAnalyzer = keyword.Name
indexMapping.DefaultMapping = docMapping
err := indexMapping.AddCustomAnalyzer(lowercaseKeywordAnalyzer,
err := indexMapping.AddCustomAnalyzer("lowercaseKeyword",
map[string]interface{}{
"type": custom.Name,
"tokenizer": single.Name,
@@ -289,46 +286,6 @@ 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()
@@ -416,33 +373,6 @@ 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))
@@ -462,19 +392,18 @@ func (b *Bleve) getResource(bleveIndex bleve.Index, id string) (*Resource, error
return nil, err
}
if res.Hits.Len() == 0 {
return nil, ErrResourceNotFound
return nil, errors.New("entity not found")
}
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"),
Extracted: getFieldValue[bool](fields, "Extracted"),
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"),
Document: content.Document{
Name: getFieldValue[string](fields, "Name"),
Title: getFieldValue[string](fields, "Title"),
+7 -20
View File
@@ -2,7 +2,6 @@ package engine
import (
"context"
"errors"
"regexp"
"github.com/blevesearch/bleve/v2/search"
@@ -13,17 +12,12 @@ 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
@@ -31,24 +25,17 @@ 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
Extracted bool
ID string
RootID string
Path string
ParentID string
Type uint64
Deleted bool
Hidden bool
}
func resourceIDtoSearchID(id storageProvider.ResourceId) *searchMessage.ResourceID {
-108
View File
@@ -125,67 +125,6 @@ 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)
@@ -234,53 +173,6 @@ 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)
+25 -72
View File
@@ -124,20 +124,35 @@ func walk(offset int, nodes []ast.Node) (bleveQuery.Query, int, error) {
next = q
}
case *ast.DateTimeNode:
q := dateTimeQuery(n)
if q == nil {
q := &bleveQuery.DateRangeQuery{
Start: bleveQuery.BleveQueryTime{},
End: bleveQuery.BleveQueryTime{},
InclusiveStart: nil,
InclusiveEnd: nil,
FieldVal: getField(n.Key),
}
if n.Operator == nil {
continue
}
if prev == nil {
prev = q
} else {
next = q
}
case *ast.NumericNode:
q := numericQuery(n)
if q == nil {
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:
continue
}
if prev == nil {
prev = q
} else {
@@ -355,68 +370,6 @@ 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,107 +565,6 @@ 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.UpdateTags(ev.Ref)
s.UpsertItem(ev.Ref)
case events.TagsRemoved:
s.UpdateTags(ev.Ref)
s.UpsertItem(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{"UpdateTags"}, events.TagsAdded{}, false),
Entry("TagsRemoved", []string{"UpdateTags"}, events.TagsRemoved{}, false),
Entry("TagsAdded", []string{"UpsertItem"}, events.TagsAdded{}, false),
Entry("TagsRemoved", []string{"UpsertItem"}, events.TagsRemoved{}, false),
Entry("FileUploaded", []string{"IndexSpace"}, events.FileUploaded{}, false),
Entry("UploadReady", []string{"IndexSpace"}, events.UploadReady{ExecutingUser: &userv1beta1.User{}}, true),
)
@@ -228,39 +228,6 @@ 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)
+27 -81
View File
@@ -2,7 +2,6 @@ package search
import (
"context"
"errors"
"fmt"
"path/filepath"
"slices"
@@ -22,7 +21,6 @@ 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"
@@ -37,12 +35,14 @@ import (
)
const (
_spaceStateTrashed = "trashed"
_spaceTypeMountpoint = "mountpoint"
_spaceTypePersonal = "personal"
_spaceTypeProject = "project"
_spaceTypeGrant = "grant"
_slowQueryDuration = 500 * time.Millisecond
_spaceStateTrashed = "trashed"
_spaceTypeMountpoint = "mountpoint"
_spaceTypePersonal = "personal"
_spaceTypeProject = "project"
_spaceTypeProtectedPersonal = "protected-personal"
_spaceTypeProtectedProject = "protected-project"
_spaceTypeGrant = "grant"
_slowQueryDuration = 500 * time.Millisecond
)
var (
@@ -60,7 +60,6 @@ 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)
}
@@ -171,6 +170,10 @@ 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)
}
@@ -462,22 +465,17 @@ func (s *Service) IndexSpace(spaceID *provider.StorageSpaceId) error {
}
s.logger.Debug().Str("path", ref.Path).Msg("Walking tree")
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
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
}
s.logger.Debug().Str("path", ref.Path).Msg("element hasn't changed. Skipping.")
return nil
}
s.UpsertItem(ref)
@@ -491,13 +489,6 @@ 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
}
@@ -528,8 +519,6 @@ 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")
@@ -537,16 +526,15 @@ func (s *Service) UpsertItem(ref *provider.Reference) {
}
r := engine.Resource{
ID: resourceID,
ID: storagespace.FormatResourceID(stat.Info.Id),
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,
Extracted: true,
Path: utils.MakeRelativePath(path),
Type: uint64(stat.Info.Type),
Document: doc,
}
r.Hidden = strings.HasPrefix(r.Path, ".")
@@ -560,13 +548,7 @@ func (s *Service) UpsertItem(ref *provider.Reference) {
logDocCount(s.engine, s.logger)
}
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) {
// determine if metadata needs to be stored in storage as well
metadata := map[string]string{}
addAudioMetadata(metadata, doc.Audio)
addImageMetadata(metadata, doc.Image)
@@ -592,44 +574,8 @@ func (s *Service) storeExtractedMetadata(ctx context.Context, ref *provider.Refe
})
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) {
+1 -334
View File
@@ -2,10 +2,6 @@ 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"
@@ -166,7 +162,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("Lookup", mock.Anything).Return(nil, engine.ErrResourceNotFound)
indexClient.On("Search", mock.Anything, mock.Anything).Return(&searchsvc.SearchIndexResponse{}, nil)
gatewayClient.On("Stat", mock.Anything, mock.MatchedBy(func(sreq *sprovider.StatRequest) bool {
return sreq.Ref.ResourceId.StorageId == "storageid" &&
sreq.Ref.ResourceId.OpaqueId == "spaceid" &&
@@ -203,212 +199,6 @@ 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() {
@@ -763,129 +553,6 @@ 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-03-08 00:34+0000\n"
"POT-Creation-Date: 2026-02-16 00:18+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 14:42+0000\n"
"POT-Creation-Date: 2026-02-13 00:17+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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,92 +184,6 @@ 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.
@@ -1,286 +0,0 @@
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
}
@@ -1,104 +0,0 @@
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,7 +18,6 @@ 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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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-03-05 00:04+0000\n"
"POT-Creation-Date: 2026-02-12 00:19+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