Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0151111d59 | ||
|
|
b44091a077 | ||
|
|
ad5268dd6f | ||
|
|
34f38b8f66 | ||
|
|
21310ea0e8 | ||
|
|
a970a9d675 | ||
|
|
b9bfb96257 | ||
|
|
ded657caaf | ||
|
|
8851c17a7d | ||
|
|
e081ce390b | ||
|
|
5e508e530a | ||
|
|
efaddab8ad | ||
|
|
d9fcd92862 | ||
|
|
799ebe421f | ||
|
|
c605fa6702 | ||
|
|
e6488ea1ef | ||
|
|
8addbceed7 | ||
|
|
c84e674133 | ||
|
|
2a89fec331 | ||
|
|
d6ab9216b0 | ||
|
|
23b2082a61 | ||
|
|
1dc6fa096c | ||
|
|
7d30c8fc6e | ||
|
|
d43e23e5f0 | ||
|
|
911bada4d1 | ||
|
|
83db638a7b | ||
|
|
6973f7db93 | ||
|
|
c53a985c2c | ||
|
|
1fea569cea | ||
|
|
cc66f2a651 | ||
|
|
cf8425337c | ||
|
|
a0e7d38e84 | ||
|
|
f2b9c09cec |
No files matched your search
+391
-108
@@ -41,6 +41,9 @@ KEYCLOAK_IMAGE = "quay.io/keycloak/keycloak:26.2.5"
|
||||
POSTGRES_ALPINE_IMAGE = "postgres:alpine3.18"
|
||||
TRIVY_IMAGE = "aquasec/trivy:latest"
|
||||
K3D_IMAGE = "ghcr.io/k3d-io/k3d:5-dind"
|
||||
CODACY_COVERAGE_REPORTER = "codacy/codacy-coverage-reporter:latest"
|
||||
CS3ORG_WOPISERVER = "cs3org/wopiserver:v10.4.0"
|
||||
OC_CI_WOPI_VALIDATOR = "owncloudci/wopi-validator"
|
||||
|
||||
# the hugo version needs to be the same as in owncloud.github.io
|
||||
OC_CI_HUGO_STATIC_IMAGE = "hugomods/hugo:base-0.129.0"
|
||||
@@ -72,6 +75,10 @@ FED_OCIS_SERVER_NAME = "federation-%s" % OCIS_SERVER_NAME
|
||||
OCIS_FED_URL = "https://%s:10200" % FED_OCIS_SERVER_NAME
|
||||
OCIS_FED_DOMAIN = "%s:10200" % FED_OCIS_SERVER_NAME
|
||||
|
||||
# urls for k8s deployment
|
||||
OCIS_URL_K8S = "https://%s" % OCIS_SERVER_NAME
|
||||
OCIS_FED_URL_K8S = "https://%s" % FED_OCIS_SERVER_NAME
|
||||
|
||||
# emails
|
||||
EMAIL_PORT = "8025"
|
||||
EMAIL_SMTP_PORT = "1025"
|
||||
@@ -229,9 +236,9 @@ config = {
|
||||
"ocm": {
|
||||
"suites": [
|
||||
"apiOcm",
|
||||
"apiServiceAvailability",
|
||||
],
|
||||
"skip": False,
|
||||
"k8s": True,
|
||||
"withRemotePhp": [False],
|
||||
"federationServer": True,
|
||||
"emailNeeded": True,
|
||||
@@ -270,6 +277,7 @@ config = {
|
||||
"apiCollaboration",
|
||||
],
|
||||
"skip": False,
|
||||
"k8s": True,
|
||||
"withRemotePhp": [False],
|
||||
"collaborationServiceNeeded": True,
|
||||
"extraServerEnvironment": {
|
||||
@@ -279,6 +287,7 @@ config = {
|
||||
"cliCommands": {
|
||||
"suites": [
|
||||
"cliCommands",
|
||||
"apiServiceAvailability",
|
||||
],
|
||||
"skip": False,
|
||||
"withRemotePhp": [False],
|
||||
@@ -895,7 +904,7 @@ def uploadScanResults(ctx):
|
||||
},
|
||||
{
|
||||
"name": "codacy",
|
||||
"image": "codacy/codacy-coverage-reporter:latest",
|
||||
"image": CODACY_COVERAGE_REPORTER,
|
||||
"environment": {
|
||||
"CODACY_PROJECT_TOKEN": {
|
||||
"from_secret": "codacy_token",
|
||||
@@ -1109,36 +1118,107 @@ def localApiTestPipeline(ctx):
|
||||
for storage in params["storages"]:
|
||||
for run_with_remote_php in params["withRemotePhp"]:
|
||||
run_on_k8s = params["k8s"] and ctx.build.event == "cron"
|
||||
ocis_url = OCIS_URL
|
||||
if run_on_k8s:
|
||||
ocis_url = "https://%s" % OCIS_SERVER_NAME
|
||||
|
||||
####################
|
||||
# SETUP STEPS #
|
||||
####################
|
||||
setup_steps = skipIfUnchanged(ctx, "acceptance-tests")
|
||||
if run_on_k8s:
|
||||
setup_steps += ocisServerK8s(
|
||||
params["federationServer"],
|
||||
params["antivirusNeeded"],
|
||||
params["emailNeeded"],
|
||||
params["tikaNeeded"],
|
||||
params["collaborationServiceNeeded"],
|
||||
)
|
||||
|
||||
if params["antivirusNeeded"]:
|
||||
setup_steps += exposeAntivirusServiceK8s()
|
||||
if params["emailNeeded"]:
|
||||
setup_steps += exposeEmailServiceK8s()
|
||||
if params["collaborationServiceNeeded"]:
|
||||
setup_steps += exposeNodePortsK8s([
|
||||
["collaboration-collabora", 9300],
|
||||
["collaboration-fakeoffice", 9300],
|
||||
["collaboration-onlyoffice", 9300],
|
||||
["collaboration-fakeoffice", 9304],
|
||||
])
|
||||
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"],
|
||||
with_wrapper = True,
|
||||
tika_enabled = params["tikaNeeded"],
|
||||
volumes = [stepVolumeOcisStorage],
|
||||
)
|
||||
|
||||
if params["federationServer"]:
|
||||
setup_steps += ocisServer(
|
||||
storage,
|
||||
deploy_type = "federation",
|
||||
extra_server_environment = params["extraServerEnvironment"],
|
||||
)
|
||||
if params["collaborationServiceNeeded"]:
|
||||
setup_steps += wopiCollaborationService("fakeoffice") + \
|
||||
wopiCollaborationService("collabora") + \
|
||||
wopiCollaborationService("onlyoffice") + \
|
||||
ocisHealthCheck("wopi", ["wopi-collabora:9304", "wopi-onlyoffice:9304", "wopi-fakeoffice:9304"])
|
||||
|
||||
####################
|
||||
# SERVICES #
|
||||
####################
|
||||
services = []
|
||||
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 #
|
||||
####################
|
||||
pipeline_name = "%s-%s" % ("CLI" if name.startswith("cli") else "API", name)
|
||||
if run_with_remote_php:
|
||||
pipeline_name += "-withRemotePhp"
|
||||
if run_on_k8s:
|
||||
pipeline_name += "-k8s"
|
||||
pipeline = {
|
||||
"kind": "pipeline",
|
||||
"type": "docker",
|
||||
"name": "%s-%s%s%s" % ("CLI" if name.startswith("cli") else "API", name, "-withRemotePhp" if run_with_remote_php else "", "-k8s" if run_on_k8s else ""),
|
||||
"name": pipeline_name,
|
||||
"platform": {
|
||||
"os": "linux",
|
||||
"arch": "amd64",
|
||||
},
|
||||
"steps": skipIfUnchanged(ctx, "acceptance-tests") +
|
||||
([] if run_on_k8s else restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin")) +
|
||||
(tikaService() if params["tikaNeeded"] and not run_on_k8s else tikaServiceK8s() if params["tikaNeeded"] and run_on_k8s else []) +
|
||||
(waitForServices("online-offices", ["collabora:9980", "onlyoffice:443", "fakeoffice:8080"]) if params["collaborationServiceNeeded"] else []) +
|
||||
(waitK3sCluster() + (enableAntivirusServiceK8s() if params["antivirusNeeded"] and run_on_k8s else []) + (emailServiceK8s() if params["emailNeeded"] and run_on_k8s else []) + prepareOcisDeployment() + setupOcisConfigMaps() + deployOcis() + waitForOcis(ocis_url = ocis_url) + ociswrapper() + waitForOciswrapper() if run_on_k8s else ocisServer(storage, extra_server_environment = params["extraServerEnvironment"], with_wrapper = True, tika_enabled = params["tikaNeeded"], volumes = ([stepVolumeOcisStorage]))) +
|
||||
(waitForClamavService() if params["antivirusNeeded"] and not run_on_k8s else exposeAntivirusServiceK8s() if params["antivirusNeeded"] and run_on_k8s else []) +
|
||||
(waitForEmailService() if params["emailNeeded"] and not run_on_k8s else exposeEmailServiceK8s() if params["emailNeeded"] and run_on_k8s else []) +
|
||||
(ocisServer(storage, deploy_type = "federation", extra_server_environment = params["extraServerEnvironment"]) if params["federationServer"] else []) +
|
||||
((wopiCollaborationService("fakeoffice") + wopiCollaborationService("collabora") + wopiCollaborationService("onlyoffice")) if params["collaborationServiceNeeded"] else []) +
|
||||
(ocisHealthCheck("wopi", ["wopi-collabora:9304", "wopi-onlyoffice:9304", "wopi-fakeoffice:9304"]) if params["collaborationServiceNeeded"] else []) +
|
||||
localApiTests(name, params["suites"], storage, params["extraEnvironment"], run_with_remote_php, ocis_url = ocis_url, k8s = run_on_k8s) +
|
||||
"steps": setup_steps +
|
||||
localApiTests(
|
||||
name,
|
||||
params["suites"],
|
||||
storage,
|
||||
params["extraEnvironment"],
|
||||
run_with_remote_php,
|
||||
k8s = run_on_k8s,
|
||||
) +
|
||||
apiTestFailureLog() +
|
||||
(generateCoverageFromAPITest(ctx, name) if not run_on_k8s else []),
|
||||
"services": (k3sCluster() if run_on_k8s else []) +
|
||||
(emailService() if params["emailNeeded"] and not run_on_k8s else []) +
|
||||
(clamavService() if params["antivirusNeeded"] and not run_on_k8s else []) +
|
||||
((fakeOffice() + collaboraService() + onlyofficeService()) if params["collaborationServiceNeeded"] else []),
|
||||
"depends_on": getPipelineNames(buildOcisBinaryForTesting(ctx)),
|
||||
"services": services,
|
||||
"depends_on": [] if run_on_k8s else getPipelineNames(buildOcisBinaryForTesting(ctx)),
|
||||
"trigger": {
|
||||
"ref": [
|
||||
"refs/heads/master",
|
||||
@@ -1191,26 +1271,37 @@ def generateCoverageFromAPITest(ctx, name):
|
||||
},
|
||||
]
|
||||
|
||||
def localApiTests(name, suites, storage = "ocis", extra_environment = {}, with_remote_php = False, ocis_url = OCIS_URL, k8s = False):
|
||||
def localApiTests(name, suites, storage = "ocis", extra_environment = {}, with_remote_php = False, k8s = False):
|
||||
test_dir = "%s/tests/acceptance" % dirs["base"]
|
||||
expected_failures_file = "%s/expected-failures-localAPI-on-%s-storage.md" % (test_dir, storage.upper())
|
||||
wrapper_url = "http://%s:5200" % OCIS_SERVER_NAME
|
||||
ocis_url = OCIS_URL
|
||||
ocis_fed_url = OCIS_FED_URL
|
||||
|
||||
if k8s:
|
||||
ocis_url = OCIS_URL_K8S
|
||||
ocis_fed_url = OCIS_FED_URL_K8S
|
||||
wrapper_url = "http://ociswrapper:5200"
|
||||
|
||||
environment = {
|
||||
"TEST_SERVER_URL": ocis_url,
|
||||
"TEST_SERVER_FED_URL": OCIS_FED_URL,
|
||||
"TEST_SERVER_FED_URL": ocis_fed_url,
|
||||
"OCIS_REVA_DATA_ROOT": "%s" % (dirs["ocisRevaDataRoot"] if storage == "owncloud" else ""),
|
||||
"STORAGE_DRIVER": storage,
|
||||
"BEHAT_SUITES": ",".join(suites),
|
||||
"BEHAT_FILTER_TAGS": "~@skip&&~@skipOnGraph&&~@skipOnOcis-%s-Storage" % ("OC" if storage == "owncloud" else "OCIS"),
|
||||
"EXPECTED_FAILURES_FILE": expected_failures_file,
|
||||
"UPLOAD_DELETE_WAIT_TIME": "1" if storage == "owncloud" else 0,
|
||||
"OCIS_WRAPPER_URL": "http://ociswrapper:5200" if k8s else "http://%s:5200" % OCIS_SERVER_NAME,
|
||||
"OCIS_WRAPPER_URL": wrapper_url,
|
||||
"WITH_REMOTE_PHP": with_remote_php,
|
||||
"COLLABORATION_SERVICE_URL": "http://wopi-fakeoffice:9300",
|
||||
"COLLABORATION_SERVICE_URL": "http://ocis-server:9304" if k8s else "http://wopi-fakeoffice:9300",
|
||||
"K8S": k8s,
|
||||
}
|
||||
|
||||
for item in extra_environment:
|
||||
if item == "EMAIL_HOST" and k8s:
|
||||
environment[item] = OCIS_SERVER_NAME
|
||||
continue
|
||||
environment[item] = extra_environment[item]
|
||||
|
||||
return [{
|
||||
@@ -1283,7 +1374,7 @@ def wopiValidatorTests(ctx, storage, wopiServerType):
|
||||
wopiServer = [
|
||||
{
|
||||
"name": "wopi-fakeoffice",
|
||||
"image": "cs3org/wopiserver:v10.4.0",
|
||||
"image": CS3ORG_WOPISERVER,
|
||||
"detach": True,
|
||||
"commands": [
|
||||
"cp %s/tests/config/drone/wopiserver.conf /etc/wopi/wopiserver.conf" % (dirs["base"]),
|
||||
@@ -1302,7 +1393,7 @@ def wopiValidatorTests(ctx, storage, wopiServerType):
|
||||
for testgroup in testgroups:
|
||||
validatorTests.append({
|
||||
"name": "wopiValidatorTests-%s" % testgroup,
|
||||
"image": "owncloudci/wopi-validator",
|
||||
"image": OC_CI_WOPI_VALIDATOR,
|
||||
"commands": [
|
||||
"export WOPI_TOKEN=$(cat accesstoken)",
|
||||
"echo $WOPI_TOKEN",
|
||||
@@ -1318,7 +1409,7 @@ def wopiValidatorTests(ctx, storage, wopiServerType):
|
||||
for builtinOnlyGroup in builtinOnlyTestGroups:
|
||||
validatorTests.append({
|
||||
"name": "wopiValidatorTests-%s" % builtinOnlyGroup,
|
||||
"image": "owncloudci/wopi-validator",
|
||||
"image": OC_CI_WOPI_VALIDATOR,
|
||||
"commands": [
|
||||
"export WOPI_TOKEN=$(cat accesstoken)",
|
||||
"echo $WOPI_TOKEN",
|
||||
@@ -1412,8 +1503,52 @@ def coreApiTestPipeline(ctx):
|
||||
expected_failures_file = "%s/expected-failures-API-on-%s-storage.md" % (test_dir, storage.upper())
|
||||
run_on_k8s = params["k8s"] and ctx.build.event == "cron"
|
||||
ocis_url = OCIS_URL
|
||||
wrapper_url = "http://%s:5200" % OCIS_SERVER_NAME
|
||||
|
||||
####################
|
||||
# SETUP STEPS #
|
||||
####################
|
||||
setup_steps = skipIfUnchanged(ctx, "acceptance-tests")
|
||||
if run_on_k8s:
|
||||
ocis_url = "https://%s" % OCIS_SERVER_NAME
|
||||
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"],
|
||||
with_wrapper = True,
|
||||
tika_enabled = params["tikaNeeded"],
|
||||
volumes = ([stepVolumeOcisStorage]),
|
||||
)
|
||||
|
||||
####################
|
||||
# SERVICES #
|
||||
####################
|
||||
services = []
|
||||
if run_on_k8s:
|
||||
services += k3sCluster()
|
||||
else:
|
||||
if params["emailNeeded"]:
|
||||
services += emailService()
|
||||
if params["antivirusNeeded"]:
|
||||
services += clamavService()
|
||||
|
||||
####################
|
||||
# PIPELINE #
|
||||
####################
|
||||
pipeline = {
|
||||
"kind": "pipeline",
|
||||
"type": "docker",
|
||||
@@ -1422,12 +1557,7 @@ def coreApiTestPipeline(ctx):
|
||||
"os": "linux",
|
||||
"arch": "amd64",
|
||||
},
|
||||
"steps": skipIfUnchanged(ctx, "acceptance-tests") +
|
||||
([] if run_on_k8s else restoreBuildArtifactCache(ctx, "ocis-binary-amd64", "ocis/bin")) +
|
||||
(tikaService() if params["tikaNeeded"] else []) +
|
||||
(waitForClamavService() if params["antivirusNeeded"] else []) +
|
||||
(waitForEmailService() if params["emailNeeded"] else []) +
|
||||
(waitK3sCluster() + prepareOcisDeployment() + setupOcisConfigMaps() + deployOcis() + waitForOcis(ocis_url = ocis_url) + ociswrapper() + waitForOciswrapper() if run_on_k8s else ocisServer(storage, extra_server_environment = params["extraServerEnvironment"], with_wrapper = True, tika_enabled = params["tikaNeeded"], volumes = ([stepVolumeOcisStorage]))) +
|
||||
"steps": setup_steps +
|
||||
[
|
||||
{
|
||||
"name": "run-api-tests",
|
||||
@@ -1441,7 +1571,7 @@ def coreApiTestPipeline(ctx):
|
||||
"ACCEPTANCE_TEST_TYPE": "core-api",
|
||||
"EXPECTED_FAILURES_FILE": expected_failures_file,
|
||||
"UPLOAD_DELETE_WAIT_TIME": "1" if storage == "owncloud" else 0,
|
||||
"OCIS_WRAPPER_URL": "http://ociswrapper:5200" if run_on_k8s else "http://%s:5200" % OCIS_SERVER_NAME,
|
||||
"OCIS_WRAPPER_URL": wrapper_url,
|
||||
"WITH_REMOTE_PHP": run_with_remote_php,
|
||||
"K8S": run_on_k8s,
|
||||
},
|
||||
@@ -1454,10 +1584,8 @@ def coreApiTestPipeline(ctx):
|
||||
] +
|
||||
apiTestFailureLog() +
|
||||
([] if run_on_k8s else generateCoverageFromAPITest(ctx, name)),
|
||||
"services": (emailService() if params["emailNeeded"] else []) +
|
||||
(clamavService() if params["antivirusNeeded"] else []) +
|
||||
(k3sCluster() if run_on_k8s else []),
|
||||
"depends_on": getPipelineNames(buildOcisBinaryForTesting(ctx)),
|
||||
"services": services,
|
||||
"depends_on": [] if run_on_k8s else getPipelineNames(buildOcisBinaryForTesting(ctx)),
|
||||
"trigger": {
|
||||
"ref": [
|
||||
"refs/heads/master",
|
||||
@@ -2735,6 +2863,42 @@ def startOcisService(service = None, name = None, environment = {}, volumes = []
|
||||
},
|
||||
]
|
||||
|
||||
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
|
||||
|
||||
expose_ext_server_step = []
|
||||
external_servers = []
|
||||
|
||||
steps = prepareOcisDeployment()
|
||||
if antivirus:
|
||||
steps += enableAntivirusServiceK8s()
|
||||
if email:
|
||||
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 += waitK3sCluster(name) + \
|
||||
(waitK3sCluster(fed_name) if federation else []) + \
|
||||
setupOcisConfigMaps(name) + \
|
||||
(setupOcisConfigMaps(fed_name) if federation else []) + \
|
||||
expose_ext_server_step + \
|
||||
deployOcis(name) + \
|
||||
(deployOcis(fed_name) if federation else []) + \
|
||||
streamK8sOcisLogs(name) + \
|
||||
waitForOcis(name, url) + \
|
||||
(waitForOcis(fed_name, fed_url) if federation else [])
|
||||
|
||||
return steps + ociswrapperK8s(name)
|
||||
|
||||
def redis():
|
||||
return [
|
||||
{
|
||||
@@ -3464,10 +3628,11 @@ def fakeOffice():
|
||||
},
|
||||
]
|
||||
|
||||
def wopiCollaborationService(name):
|
||||
def wopiCollaborationService(name, ocis_url = OCIS_URL):
|
||||
service_name = "wopi-%s" % name
|
||||
|
||||
environment = {
|
||||
"OCIS_URL": ocis_url,
|
||||
"MICRO_REGISTRY": "nats-js-kv",
|
||||
"MICRO_REGISTRY_ADDRESS": "%s:9233" % OCIS_SERVER_NAME,
|
||||
"COLLABORATION_LOG_LEVEL": "debug",
|
||||
@@ -3672,7 +3837,7 @@ def collaboraService():
|
||||
"detach": True,
|
||||
"environment": {
|
||||
"DONT_GEN_SSL_CERT": "set",
|
||||
"extra_params": "--o:ssl.enable=true --o:ssl.termination=true --o:welcome.enable=false --o:net.frame_ancestors=%s" % OCIS_URL,
|
||||
"extra_params": "--o:ssl.enable=true --o:ssl.termination=true --o:welcome.enable=false --o:net.frame_ancestors=https://%s" % OCIS_SERVER_NAME,
|
||||
},
|
||||
"commands": [
|
||||
"coolconfig generate-proof-key",
|
||||
@@ -3788,42 +3953,72 @@ def trivyScan(ctx):
|
||||
},
|
||||
}
|
||||
|
||||
def k3sCluster():
|
||||
def k3sCluster(name = OCIS_SERVER_NAME, ocm = False):
|
||||
peer_name = OCIS_SERVER_NAME if name == FED_OCIS_SERVER_NAME else FED_OCIS_SERVER_NAME
|
||||
commands = []
|
||||
log_dir = "%s/logs-%s" % (dirs["base"], name)
|
||||
|
||||
commands.extend([
|
||||
"nohup dockerd-entrypoint.sh &",
|
||||
"until docker ps 2>&1 > /dev/null; do sleep 1s; done",
|
||||
# create ocis logs dir
|
||||
"mkdir -p %s && chmod 777 %s" % (log_dir, log_dir),
|
||||
# create cluster
|
||||
"k3d cluster create %s --api-port %s:33199 " % (name, name) +
|
||||
"-p '80:80@loadbalancer' -p '443:443@loadbalancer' -p '8025:32025@loadbalancer' -p '9100-9399:30100-30399@loadbalancer' " +
|
||||
"--k3s-arg '--tls-san=k3d@server:*' --k3s-arg '--disable=metrics-server@server:*' " +
|
||||
"-v %s:/logs" % log_dir,
|
||||
# wait for services to be ready
|
||||
"until kubectl get deployment coredns -n kube-system -o go-template='{{.status.availableReplicas}}' | grep -v -e '<no value>'; do sleep 1s; done",
|
||||
"until kubectl get deployment traefik -n kube-system -o go-template='{{.status.availableReplicas}}' | grep -v -e '<no value>'; do sleep 1s; done",
|
||||
"k3d kubeconfig get %s > kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % (name, name),
|
||||
"chmod 0600 kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name,
|
||||
"printf '@@@@@@@@@@@@@@@@@@@@@@@\\n@@@@ k3d is ready @@@@\\n@@@@@@@@@@@@@@@@@@@@@@@\\n'",
|
||||
# add dns rewrite rule
|
||||
"kubectl create configmap coredns-custom -n kube-system " +
|
||||
"--from-literal='rewritehost.override=rewrite name exact %s host.k3d.internal'" % name,
|
||||
"kubectl -n kube-system rollout restart deployment coredns",
|
||||
])
|
||||
|
||||
if ocm:
|
||||
commands.extend([
|
||||
# wait for peer
|
||||
"echo 'Waiting for %s to be available...'" % peer_name,
|
||||
"for i in {1..60}; do if getent hosts %s > /dev/null 2>&1; then break; fi; echo 'Waiting for %s... attempt '$i; sleep 2; done" % (peer_name, peer_name),
|
||||
# get the IP of peer
|
||||
"PEER_IP=$(getent hosts %s | awk '{ print $1 }')" % peer_name,
|
||||
"echo \"%s IP: $PEER_IP\"" % peer_name,
|
||||
# create namespace for ocis
|
||||
"kubectl create namespace ocis --dry-run=client -o yaml | kubectl apply -f -",
|
||||
# create service in the 'ocis' namespace
|
||||
"cat <<EOF | kubectl apply -f -\napiVersion: v1\nkind: Service\nmetadata:\n name: %s\n namespace: ocis\nspec:\n type: ClusterIP\n clusterIP: None\n ports:\n - port: 443\n protocol: TCP\n---\napiVersion: v1\nkind: Endpoints\nmetadata:\n name: %s\n namespace: ocis\nsubsets:\n- addresses:\n - ip: $PEER_IP\n ports:\n - port: 443\n protocol: TCP\nEOF" % (peer_name, peer_name),
|
||||
# verify
|
||||
"kubectl get svc %s -n ocis" % peer_name,
|
||||
"kubectl get endpoints %s -n ocis" % peer_name,
|
||||
])
|
||||
|
||||
commands.extend([
|
||||
"printf '@@@@@@@@@@@@@@@@@@@@@@@\\n@@@@ k3d is ready @@@@\\n@@@@@@@@@@@@@@@@@@@@@@@\\n'",
|
||||
# watch events
|
||||
"kubectl get events -Aw",
|
||||
])
|
||||
|
||||
return [{
|
||||
"name": OCIS_SERVER_NAME,
|
||||
"name": name,
|
||||
"image": K3D_IMAGE,
|
||||
"user": "root",
|
||||
"privileged": True,
|
||||
"commands": [
|
||||
"git clone --single-branch --branch main --depth 1 https://github.com/owncloud/ocis-charts.git",
|
||||
"nohup dockerd-entrypoint.sh &",
|
||||
"until docker ps 2>&1 > /dev/null; do sleep 1s; done",
|
||||
# create cluster
|
||||
"k3d cluster create drone --api-port %s:33199 " % OCIS_SERVER_NAME +
|
||||
"-p '80:80@loadbalancer' -p '443:443@loadbalancer' -p '9100-9399:30100-30399@loadbalancer' " +
|
||||
"--k3s-arg '--tls-san=k3d@server:*' --k3s-arg '--disable=metrics-server@server:*'",
|
||||
# wait for services to be ready
|
||||
"until kubectl get deployment coredns -n kube-system -o go-template='{{.status.availableReplicas}}' | grep -v -e '<no value>'; do sleep 1s; done",
|
||||
"until kubectl get deployment traefik -n kube-system -o go-template='{{.status.availableReplicas}}' | grep -v -e '<no value>'; do sleep 1s; done",
|
||||
"k3d kubeconfig get drone > kubeconfig-$${DRONE_BUILD_NUMBER}.yaml",
|
||||
"chmod 0600 kubeconfig-$${DRONE_BUILD_NUMBER}.yaml",
|
||||
"printf '@@@@@@@@@@@@@@@@@@@@@@@\n@@@@ k3d is ready @@@@\n@@@@@@@@@@@@@@@@@@@@@@@\n'",
|
||||
# add dns rewrite rule
|
||||
"kubectl create configmap coredns-custom -n kube-system " +
|
||||
"--from-literal='rewritehost.override=rewrite name exact %s host.k3d.internal'" % OCIS_SERVER_NAME,
|
||||
"kubectl -n kube-system rollout restart deployment coredns",
|
||||
# watch events
|
||||
"kubectl get events -Aw",
|
||||
],
|
||||
"commands": commands,
|
||||
}]
|
||||
|
||||
def waitK3sCluster():
|
||||
def waitK3sCluster(name = OCIS_SERVER_NAME):
|
||||
step_name = "wait-cluster-" + name
|
||||
return [{
|
||||
"name": "wait-cluster",
|
||||
"name": step_name,
|
||||
"image": K3D_IMAGE,
|
||||
"user": "root",
|
||||
"commands": [
|
||||
"export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}.yaml",
|
||||
"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",
|
||||
@@ -3832,10 +4027,23 @@ def waitK3sCluster():
|
||||
|
||||
def prepareOcisDeployment():
|
||||
commands = [
|
||||
# build ocis wrapper
|
||||
"make -C %s build" % dirs["ocisWrapper"],
|
||||
# get ocis charts
|
||||
"if [ ! -d %s/ocis-charts ]; then git clone --single-branch -b main --depth 1 https://github.com/owncloud/ocis-charts.git; fi" % dirs["base"],
|
||||
# move CI values file
|
||||
"mv %s/tests/config/drone/k8s/values.yaml %s/ocis-charts/charts/ocis/ci/deployment-values.yaml" % (dirs["base"], dirs["base"]),
|
||||
# enable authbasic service
|
||||
"cp -r %s/tests/config/drone/k8s/authbasic %s/ocis-charts/charts/ocis/templates/" % (dirs["base"], dirs["base"]),
|
||||
"cd %s/ocis-charts" % 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",
|
||||
@@ -3853,11 +4061,13 @@ def prepareOcisDeployment():
|
||||
"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": "owncloudci/golang:1.25",
|
||||
"image": OC_CI_GOLANG,
|
||||
"commands": commands,
|
||||
"volumes": [
|
||||
{
|
||||
@@ -3867,9 +4077,11 @@ def prepareOcisDeployment():
|
||||
],
|
||||
}]
|
||||
|
||||
def setupOcisConfigMaps():
|
||||
def setupOcisConfigMaps(name = OCIS_SERVER_NAME):
|
||||
step_name = "setup-configmaps-" + name
|
||||
|
||||
commands = [
|
||||
"export KUBECONFIG=%s/kubeconfig-$${DRONE_BUILD_NUMBER}.yaml" % dirs["base"],
|
||||
"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"],
|
||||
@@ -3880,21 +4092,36 @@ def setupOcisConfigMaps():
|
||||
]
|
||||
|
||||
return [{
|
||||
"name": "setup-configmaps",
|
||||
"name": step_name,
|
||||
"image": K3D_IMAGE,
|
||||
"user": "root",
|
||||
"commands": commands,
|
||||
}]
|
||||
|
||||
def deployOcis():
|
||||
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": "deploy-ocis",
|
||||
"image": "owncloudci/golang:1.25",
|
||||
"commands": [
|
||||
"export KUBECONFIG=%s/kubeconfig-$${DRONE_BUILD_NUMBER}.yaml" % dirs["base"],
|
||||
"cd %s/ocis-charts" % dirs["base"],
|
||||
"make helm-install-atomic",
|
||||
],
|
||||
"name": step_name,
|
||||
"image": OC_CI_GOLANG,
|
||||
"commands": commands,
|
||||
"volumes": [
|
||||
{
|
||||
"name": "gopath",
|
||||
@@ -3903,19 +4130,39 @@ def deployOcis():
|
||||
],
|
||||
}]
|
||||
|
||||
def streamK8sOcisLogs(name = OCIS_SERVER_NAME):
|
||||
return [{
|
||||
"name": "%s-logs" % name,
|
||||
"image": OC_CI_ALPINE,
|
||||
"detach": True,
|
||||
"commands": [
|
||||
"until test -f logs-%s/ocis.log; do sleep 10s; done" % name,
|
||||
"tail -f logs-%s/ocis.log" % 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/tests/config/drone/k8s/values.yaml" % 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 emailServiceK8s():
|
||||
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,
|
||||
@@ -3924,23 +4171,25 @@ def emailServiceK8s():
|
||||
],
|
||||
}]
|
||||
|
||||
def exposeEmailServiceK8s():
|
||||
def exposeEmailServiceK8s(name = OCIS_SERVER_NAME):
|
||||
return [{
|
||||
"name": EMAIL_SMTP_HOST,
|
||||
"image": K3D_IMAGE,
|
||||
"commands": [
|
||||
"kubectl port-forward svc/mailpit %s:%s -n ocis" % (EMAIL_PORT, EMAIL_PORT),
|
||||
"kubectl port-forward svc/mailpit 9174:9174 -n ocis",
|
||||
"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():
|
||||
def exposeAntivirusServiceK8s(name = OCIS_SERVER_NAME):
|
||||
return [{
|
||||
"name": "expose-antivirus-service",
|
||||
"image": K3D_IMAGE,
|
||||
"commands": [
|
||||
"export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}.yaml",
|
||||
"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",
|
||||
@@ -3948,36 +4197,27 @@ def exposeAntivirusServiceK8s():
|
||||
],
|
||||
}]
|
||||
|
||||
def ociswrapper():
|
||||
def ociswrapperK8s(name = OCIS_SERVER_NAME, ocis_url = OCIS_URL_K8S):
|
||||
return [{
|
||||
"name": "ociswrapper",
|
||||
"image": K3D_IMAGE,
|
||||
"user": "root",
|
||||
"commands": [
|
||||
"export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}.yaml",
|
||||
"until test -f $${KUBECONFIG}; do sleep 1s; done",
|
||||
"kubectl get pods -A",
|
||||
"kubectl get ingress -A",
|
||||
"kubectl describe pods $(kubectl get pods -n ocis -l app=antivirus -o jsonpath=\"{.items[0].metadata.name}\") -n ocis",
|
||||
"kubectl describe pods $(kubectl get pods -n ocis -l app=postprocessing -o jsonpath=\"{.items[0].metadata.name}\") -n ocis",
|
||||
"%s/bin/ociswrapper serve --url https://%s --admin-username admin --admin-password admin --skip-ocis-run" % (dirs["ocisWrapper"], OCIS_SERVER_NAME),
|
||||
],
|
||||
"detach": True,
|
||||
}]
|
||||
|
||||
def waitForOciswrapper(url = "http://ociswrapper:5200", depends_on = []):
|
||||
return [{
|
||||
"commands": [
|
||||
"export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name,
|
||||
"until test -f $${KUBECONFIG}; do sleep 1s; done",
|
||||
"%s/bin/ociswrapper serve --url %s --admin-username admin --admin-password admin --skip-ocis-run" % (dirs["ocisWrapper"], ocis_url),
|
||||
],
|
||||
}, {
|
||||
"name": "wait-for-wrapper",
|
||||
"image": OC_CI_ALPINE,
|
||||
"commands": [
|
||||
"timeout 60 bash -c 'while [ $(curl -sk " +
|
||||
"%s " % url +
|
||||
"http://ociswrapper:5200 " +
|
||||
"-w %{http_code} -o /dev/null) != 404 ]; do sleep 1; done'",
|
||||
],
|
||||
"depends_on": depends_on,
|
||||
}]
|
||||
|
||||
def tikaServiceK8s():
|
||||
def enableTikaServiceK8s():
|
||||
return [{
|
||||
"name": "tika",
|
||||
"type": "docker",
|
||||
@@ -3985,6 +4225,49 @@ def tikaServiceK8s():
|
||||
"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/tests/config/drone/k8s/values.yaml" % 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):
|
||||
deploy_name = service[0]
|
||||
service_port = str(service[1])
|
||||
node_port = service_port.replace("9", "30", 1)
|
||||
|
||||
# there can be multiple collaboration services
|
||||
if service_port == "9300" and "collaboration" in deploy_name:
|
||||
node_port = "3030%d" % idx
|
||||
service_name = "%s-%s-np" % (deploy_name, node_port)
|
||||
commands.append("kubectl -n ocis expose deployment %s --type=NodePort --port=%s --name=%s" % (deploy_name, service_port, service_name))
|
||||
commands.append("kubectl -n ocis patch svc %s -p '{\"spec\":{\"ports\":[{\"port\":%s,\"nodePort\":%s}]}}'" % (service_name, service_port, node_port))
|
||||
|
||||
return [{
|
||||
"name": "expose-nodeports",
|
||||
"image": K3D_IMAGE,
|
||||
"commands": [
|
||||
"export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name,
|
||||
"until test -f $${KUBECONFIG}; do sleep 1s; done",
|
||||
] + commands,
|
||||
}]
|
||||
|
||||
def exposeExternalServersK8s(servers = [], name = OCIS_SERVER_NAME):
|
||||
commands = []
|
||||
for server in servers:
|
||||
server_name = server[0]
|
||||
server_port = str(server[1])
|
||||
commands.append("SERVER_IP=$(getent hosts %s | awk '{print $1}')" % server_name)
|
||||
commands.append('echo -e "apiVersion: v1\nkind: Endpoints\nmetadata:\n name: %s\n namespace: ocis\n' % server_name +
|
||||
'subsets:\n- addresses:\n - ip: $SERVER_IP\n ports:\n - port: %s" | kubectl apply -f -' % server_port)
|
||||
commands.append('echo -e "apiVersion: v1\nkind: Service\nmetadata:\n name: %s\n namespace: ocis\n' % server_name +
|
||||
'spec:\n ports:\n - port: %s\n targetPort: %s" | kubectl apply -f -' % (server_port, server_port))
|
||||
|
||||
return [{
|
||||
"name": "expose-external-servers",
|
||||
"image": K3D_IMAGE,
|
||||
"commands": [
|
||||
"export KUBECONFIG=kubeconfig-$${DRONE_BUILD_NUMBER}-%s.yaml" % name,
|
||||
"until test -f $${KUBECONFIG}; do sleep 1s; done",
|
||||
] + commands,
|
||||
}]
|
||||
@@ -0,0 +1,32 @@
|
||||
name: Weekly Pipeline Report
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
pull_request:
|
||||
branches:
|
||||
- feat/ci-report-tool
|
||||
schedule:
|
||||
- cron: "0 8 * * 1" # Every Monday at 8:00 AM UTC
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
generate-report:
|
||||
name: Generate Pipeline Report
|
||||
runs-on: ubuntu-latest
|
||||
container: golang:1.25-alpine
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run CI Reporter
|
||||
working-directory: tools/ci-reporter
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# Review the pipelines in last 14 days before the dorne logs expire
|
||||
run: |
|
||||
GOWORK=off go run ./cmd/list-failed-commits \
|
||||
--github-token "$GITHUB_TOKEN" \
|
||||
--since 14d \
|
||||
--max-commits 9999999
|
||||
@@ -64,3 +64,4 @@ go.work.sum
|
||||
.envrc
|
||||
CLAUDE.md
|
||||
.claude/
|
||||
.agents/
|
||||
+63
-21
@@ -39,8 +39,8 @@
|
||||
* [Changelog for 3.0.0](#changelog-for-300-2023-06-06)
|
||||
* [Changelog for 2.0.0](#changelog-for-200-2022-11-30)
|
||||
* [Changelog for 1.20.0](#changelog-for-1200-2022-04-13)
|
||||
* [Changelog for 1.19.1](#changelog-for-1191-2022-03-29)
|
||||
* [Changelog for 1.19.0](#changelog-for-1190-2022-03-29)
|
||||
* [Changelog for 1.19.1](#changelog-for-1191-2022-03-29)
|
||||
* [Changelog for 1.18.0](#changelog-for-1180-2022-03-03)
|
||||
* [Changelog for 1.17.0](#changelog-for-1170-2022-02-16)
|
||||
* [Changelog for 1.16.0](#changelog-for-1160-2021-12-10)
|
||||
@@ -70,8 +70,11 @@ The following sections list the changes for unreleased.
|
||||
## Summary
|
||||
|
||||
* 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)
|
||||
* Bugfix - Rework monitoring in the ocis_full deployment example: [#11995](https://github.com/owncloud/ocis/pull/11995)
|
||||
* 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)
|
||||
* 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)
|
||||
@@ -91,6 +94,14 @@ The following sections list the changes for unreleased.
|
||||
https://github.com/owncloud/ocis/issues/11692
|
||||
https://github.com/owncloud/ocis/pull/12002
|
||||
|
||||
* Bugfix - Don't use hardcoded groupOfNames in group creation: [#11776](https://github.com/owncloud/ocis/pull/11776)
|
||||
|
||||
Formerly, when creating a group with a different objectClass, it will always use
|
||||
groupOfNames instead of the one provided in the config. Now, the server creates
|
||||
groups using the objectClass defined in the config.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/11776
|
||||
|
||||
* Bugfix - Translation for some email notifications: [#11979](https://github.com/owncloud/ocis/pull/11979)
|
||||
|
||||
Some email notifications showed a wrong translated message that shouldn't
|
||||
@@ -112,6 +123,37 @@ The following sections list the changes for unreleased.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/11995
|
||||
|
||||
* Bugfix - Extract metadata from oversized files and fix ISO field: [#12000](https://github.com/owncloud/ocis/pull/12000)
|
||||
|
||||
Two issues were found in the Tika content extractor:
|
||||
|
||||
1. Files exceeding `SEARCH_CONTENT_EXTRACTION_SIZE_LIMIT` (default 20MB) were
|
||||
skipped entirely — no EXIF, no photo metadata, no image dimensions were
|
||||
extracted. This particularly affected Pixel Motion Photos (`.MP.jpg`) which
|
||||
embed an MP4 video making them 3-9MB. Since EXIF metadata lives in the JPEG
|
||||
header (first few KB), a truncated stream is sufficient. The extractor now wraps
|
||||
the download in `io.LimitReader` instead of skipping Tika, sending only the
|
||||
first N bytes for metadata extraction.
|
||||
|
||||
2. The ISO speed field was read from `"Base ISO"`, a Canon-specific Tika field
|
||||
(sensor base sensitivity). Most cameras — Pixel, iPhone, Samsung — provide
|
||||
ISO via the standard `"exif:IsoSpeedRatings"` field. The extractor now checks
|
||||
`exif:IsoSpeedRatings` first and falls back to `Base ISO` for Canon
|
||||
compatibility.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12000
|
||||
|
||||
* Bugfix - Make tag unassignment idempotent and handle publish failures: [#12001](https://github.com/owncloud/ocis/pull/12001)
|
||||
|
||||
The DELETE tags endpoint now returns success when the requested tag is already
|
||||
absent from the file's metadata, instead of returning HTTP 400 with a misleading
|
||||
error message. The TagsRemoved event is always published so the search index
|
||||
stays in sync even when file metadata and the search index are out of sync. If
|
||||
event publishing fails, the metadata change is rolled back and HTTP 500 is
|
||||
returned to avoid leaving the system in an inconsistent state.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12001
|
||||
|
||||
* Bugfix - Expose the signature-auth attribute: [#12016](https://github.com/owncloud/ocis/pull/12016)
|
||||
|
||||
Expose the "oc:signature-auth" attribute for the subfolders in the public link
|
||||
@@ -12543,7 +12585,7 @@ The following sections list the changes for 2.0.0.
|
||||
|
||||
The following sections list the changes for 1.20.0.
|
||||
|
||||
[1.20.0]: https://github.com/owncloud/ocis/compare/v1.19.1...v1.20.0
|
||||
[1.20.0]: https://github.com/owncloud/ocis/compare/v1.19.0...v1.20.0
|
||||
|
||||
## Summary
|
||||
|
||||
@@ -12717,29 +12759,11 @@ The following sections list the changes for 1.20.0.
|
||||
https://github.com/owncloud/ocis/pull/3509
|
||||
https://github.com/owncloud/web/releases/tag/v5.4.0
|
||||
|
||||
# Changelog for [1.19.1] (2022-03-29)
|
||||
|
||||
The following sections list the changes for 1.19.1.
|
||||
|
||||
[1.19.1]: https://github.com/owncloud/ocis/compare/v1.19.0...v1.19.1
|
||||
|
||||
## Summary
|
||||
|
||||
* Bugfix - Return correct special item urls: [#3419](https://github.com/owncloud/ocis/pull/3419)
|
||||
|
||||
## Details
|
||||
|
||||
* Bugfix - Return correct special item urls: [#3419](https://github.com/owncloud/ocis/pull/3419)
|
||||
|
||||
URLs for Special items (space image, readme) were broken.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/3419
|
||||
|
||||
# Changelog for [1.19.0] (2022-03-29)
|
||||
|
||||
The following sections list the changes for 1.19.0.
|
||||
|
||||
[1.19.0]: https://github.com/owncloud/ocis/compare/v1.18.0...v1.19.0
|
||||
[1.19.0]: https://github.com/owncloud/ocis/compare/v1.19.1...v1.19.0
|
||||
|
||||
## Summary
|
||||
|
||||
@@ -12913,6 +12937,24 @@ The following sections list the changes for 1.19.0.
|
||||
https://github.com/owncloud/ocis/pull/3375
|
||||
https://github.com/owncloud/web/releases/tag/v5.3.0
|
||||
|
||||
# Changelog for [1.19.1] (2022-03-29)
|
||||
|
||||
The following sections list the changes for 1.19.1.
|
||||
|
||||
[1.19.1]: https://github.com/owncloud/ocis/compare/v1.18.0...v1.19.1
|
||||
|
||||
## Summary
|
||||
|
||||
* Bugfix - Return correct special item urls: [#3419](https://github.com/owncloud/ocis/pull/3419)
|
||||
|
||||
## Details
|
||||
|
||||
* Bugfix - Return correct special item urls: [#3419](https://github.com/owncloud/ocis/pull/3419)
|
||||
|
||||
URLs for Special items (space image, readme) were broken.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/3419
|
||||
|
||||
# Changelog for [1.18.0] (2022-03-03)
|
||||
|
||||
The following sections list the changes for 1.18.0.
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
Bugfix: Don't use hardcoded groupOfNames in group creation
|
||||
|
||||
Formerly, when creating a group with a different objectClass, it will always use groupOfNames instead of the one provided in the config.
|
||||
Now, the server creates groups using the objectClass defined in the config.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/11776
|
||||
@@ -0,0 +1,5 @@
|
||||
Bugfix: Make tag unassignment idempotent and handle publish failures
|
||||
|
||||
The DELETE tags endpoint now returns success when the requested tag is already absent from the file's metadata, instead of returning HTTP 400 with a misleading error message. The TagsRemoved event is always published so the search index stays in sync even when file metadata and the search index are out of sync. If event publishing fails, the metadata change is rolled back and HTTP 500 is returned to avoid leaving the system in an inconsistent state.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12001
|
||||
@@ -0,0 +1,19 @@
|
||||
Bugfix: Extract metadata from oversized files and fix ISO field
|
||||
|
||||
Two issues were found in the Tika content extractor:
|
||||
|
||||
1. Files exceeding `SEARCH_CONTENT_EXTRACTION_SIZE_LIMIT` (default 20MB)
|
||||
were skipped entirely — no EXIF, no photo metadata, no image dimensions
|
||||
were extracted. This particularly affected Pixel Motion Photos (`.MP.jpg`)
|
||||
which embed an MP4 video making them 3-9MB. Since EXIF metadata lives in
|
||||
the JPEG header (first few KB), a truncated stream is sufficient. The
|
||||
extractor now wraps the download in `io.LimitReader` instead of skipping
|
||||
Tika, sending only the first N bytes for metadata extraction.
|
||||
|
||||
2. The ISO speed field was read from `"Base ISO"`, a Canon-specific Tika
|
||||
field (sensor base sensitivity). Most cameras — Pixel, iPhone, Samsung —
|
||||
provide ISO via the standard `"exif:IsoSpeedRatings"` field. The extractor
|
||||
now checks `exif:IsoSpeedRatings` first and falls back to `Base ISO` for
|
||||
Canon compatibility.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12000
|
||||
@@ -52,6 +52,6 @@ olcObjectClasses: ( ownCloudOid:1.2.2 NAME 'ownCloudUser'
|
||||
MAY ( ocExternalIdentity $ ownCloudUserEnabled $ ownCloudUserType $ ocLastSignInTimestamp $ ownCloudMemberOf $ ownCloudGuestOf $ ownCloudRole) )
|
||||
olcObjectClasses: ( ownCloudOid:1.2.3 NAME 'ownCloudGroup'
|
||||
DESC 'ownCloud Group LDAP Schema'
|
||||
SUP ownCloud
|
||||
AUXILIARY
|
||||
SUP groupOfNames
|
||||
STRUCTURAL
|
||||
MAY ( ownCloudMemberOf ) )
|
||||
@@ -100,6 +100,8 @@ services:
|
||||
IDP_LDAP_UUID_ATTRIBUTE_TYPE: binary
|
||||
GRAPH_LDAP_SERVER_WRITE_ENABLED: "true" # assuming the external ldap is writable
|
||||
GRAPH_LDAP_REFINT_ENABLED: "true" # osixia has refint enabled.
|
||||
OCIS_LDAP_DISABLE_USER_MECHANISM: "group"
|
||||
OCIS_LDAP_DISABLED_USERS_GROUP_DN: "cn=disabled-users-ec730a6c-1b63-4b45-b83b-9e2311afdf85,ou=groups,dc=owncloud,dc=com"
|
||||
# Multi-Instance Configuration
|
||||
OCIS_MULTI_INSTANCE_ENABLED: true
|
||||
OCIS_MULTI_INSTANCE_INSTANCEID: "ec730a6c-1b63-4b45-b83b-9e2311afdf85"
|
||||
@@ -199,6 +201,8 @@ services:
|
||||
IDP_LDAP_UUID_ATTRIBUTE_TYPE: binary
|
||||
GRAPH_LDAP_SERVER_WRITE_ENABLED: "true" # assuming the external ldap is writable
|
||||
GRAPH_LDAP_REFINT_ENABLED: "true" # osixia has refint enabled.
|
||||
OCIS_LDAP_DISABLE_USER_MECHANISM: "group"
|
||||
OCIS_LDAP_DISABLED_USERS_GROUP_DN: "cn=disabled-users-8d24cb5f-6ee6-4b98-86df-c4c268dddb46,ou=groups,dc=owncloud,dc=com"
|
||||
# Multi-Instance
|
||||
OCIS_MULTI_INSTANCE_ENABLED: true
|
||||
OCIS_MULTI_INSTANCE_INSTANCEID: "8d24cb5f-6ee6-4b98-86df-c4c268dddb46"
|
||||
|
||||
@@ -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-20260223124048-61ee39d95d5f
|
||||
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
|
||||
|
||||
@@ -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-20260223124048-61ee39d95d5f h1:M935ztFcjtRbP3ns8Fgb2XL5jalNd3sXYMUXf0kAwTQ=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260223124048-61ee39d95d5f/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=
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -1307,7 +1307,7 @@ func (i *LDAP) CreateLDAPGroupByDN(dn string) error {
|
||||
ar := ldap.NewAddRequest(dn, nil)
|
||||
|
||||
attrs := map[string][]string{
|
||||
"objectClass": {"groupOfNames", "top"},
|
||||
"objectClass": {i.groupObjectClass, "top"},
|
||||
"member": {""},
|
||||
}
|
||||
|
||||
|
||||
@@ -184,9 +184,9 @@ func (i *LDAP) GetGroupMembers(ctx context.Context, groupID string, req *godata.
|
||||
}
|
||||
|
||||
// CreateGroup implements the Backend Interface for the LDAP Backend
|
||||
// It is currently restricted to managing groups based on the "groupOfNames" ObjectClass.
|
||||
// As "groupOfNames" requires a "member" Attribute to be present. Empty Groups (groups
|
||||
// without a member) a represented by adding an empty DN as the single member.
|
||||
// The implementation uses the configured groupObjectClass. Many common classes like
|
||||
// "groupOfNames" and "groupOfUniqueNames" require a "member" attribute to be present.
|
||||
// Empty Groups (groups without a member) are represented by adding an empty DN as the single member.
|
||||
func (i *LDAP) CreateGroup(ctx context.Context, group libregraph.Group) (*libregraph.Group, error) {
|
||||
logger := i.logger.SubloggerWithRequestID(ctx)
|
||||
logger.Debug().Str("backend", "ldap").Msg("create group")
|
||||
@@ -448,7 +448,7 @@ func (i *LDAP) getGroupCreateLDAPDN(group libregraph.Group) string {
|
||||
func (i *LDAP) groupToLDAPAttrValues(group libregraph.Group) (map[string][]string, error) {
|
||||
attrs := map[string][]string{
|
||||
i.groupAttributeMap.name: {group.GetDisplayName()},
|
||||
"objectClass": {"groupOfNames", "top", i.groupObjectClass},
|
||||
"objectClass": {i.groupObjectClass, "top"},
|
||||
// This is a crutch to allow groups without members for LDAP servers
|
||||
// that apply strict Schema checking. The RFCs define "member/uniqueMember"
|
||||
// as required attribute for groupOfNames/groupOfUniqueNames. So we
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/CiscoM31/godata"
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
libregraph "github.com/owncloud/libre-graph-api-go"
|
||||
"github.com/owncloud/ocis/v2/services/graph/pkg/identity/mocks"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
@@ -451,3 +452,63 @@ func TestUpdateGroupName(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupToLDAPAttrValuesUsesConfiguredObjectClass(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
groupObjectClass string
|
||||
}{
|
||||
{
|
||||
name: "default groupOfNames",
|
||||
groupObjectClass: "groupOfNames",
|
||||
},
|
||||
{
|
||||
name: "custom groupOfUniqueNames",
|
||||
groupObjectClass: "groupOfUniqueNames",
|
||||
},
|
||||
{
|
||||
name: "custom posixGroup",
|
||||
groupObjectClass: "posixGroup",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Setup config with custom groupObjectClass
|
||||
testConfig := lconfig
|
||||
testConfig.GroupObjectClass = tt.groupObjectClass
|
||||
|
||||
lm := &mocks.Client{}
|
||||
b, err := getMockedBackend(lm, testConfig, &logger)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create backend: %s", err.Error())
|
||||
}
|
||||
|
||||
// Create test group
|
||||
group := libregraph.Group{}
|
||||
displayName := "Test Group"
|
||||
group.SetDisplayName(displayName)
|
||||
|
||||
// Get LDAP attributes
|
||||
attrs, err := b.groupToLDAPAttrValues(group)
|
||||
if err != nil {
|
||||
t.Fatalf("Expected groupToLDAPAttrValues to succeed, got error: %s", err.Error())
|
||||
}
|
||||
|
||||
objectClasses, ok := attrs["objectClass"]
|
||||
if !ok {
|
||||
t.Fatal("Expected objectClass attribute to be present")
|
||||
}
|
||||
|
||||
// Check objectClass has exactly 3 elements
|
||||
if len(objectClasses) != 3 {
|
||||
t.Errorf("Expected objectClass to have exactly 3 elements, got %d: %v", len(objectClasses), objectClasses)
|
||||
}
|
||||
|
||||
// Check first element is the configured groupObjectClass (exact match)
|
||||
if objectClasses[0] != tt.groupObjectClass {
|
||||
t.Errorf("Expected first objectClass to be '%s', got '%s'", tt.groupObjectClass, objectClasses[0])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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{
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/go-chi/render"
|
||||
@@ -216,37 +218,72 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
allTags := tags.New(currentTags)
|
||||
if !allTags.Remove(unassignment.Tags...) {
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "no new tags in createtagsrequest or maximum reached")
|
||||
return
|
||||
tagsChanged := allTags.Remove(unassignment.Tags...)
|
||||
if tagsChanged {
|
||||
// Tags were present in metadata — update the file.
|
||||
resp, err := client.SetArbitraryMetadata(ctx, &provider.SetArbitraryMetadataRequest{
|
||||
Ref: &provider.Reference{ResourceId: &rid},
|
||||
ArbitraryMetadata: &provider.ArbitraryMetadata{
|
||||
Metadata: map[string]string{
|
||||
"tags": allTags.AsList(),
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK {
|
||||
g.logger.Error().Err(err).Msg("error setting tags")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := client.SetArbitraryMetadata(ctx, &provider.SetArbitraryMetadataRequest{
|
||||
Ref: &provider.Reference{ResourceId: &rid},
|
||||
ArbitraryMetadata: &provider.ArbitraryMetadata{
|
||||
Metadata: map[string]string{
|
||||
"tags": allTags.AsList(),
|
||||
},
|
||||
// Always publish the event so the search index gets updated,
|
||||
// even if the tag was already absent from file metadata.
|
||||
ev := events.TagsRemoved{
|
||||
Tags: strings.Join(unassignment.Tags, ","),
|
||||
Ref: &provider.Reference{
|
||||
ResourceId: &rid,
|
||||
Path: ".",
|
||||
},
|
||||
})
|
||||
if err != nil || resp.GetStatus().GetCode() != rpc.Code_CODE_OK {
|
||||
g.logger.Error().Err(err).Msg("error setting tags")
|
||||
SpaceOwner: sres.Info.Owner,
|
||||
Executant: revaCtx.ContextMustGetUser(ctx).Id,
|
||||
}
|
||||
if g.publishTagsRemoved(ctx, client, ev, tagsChanged, currentTags) != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if g.eventsPublisher != nil {
|
||||
ev := events.TagsRemoved{
|
||||
Tags: strings.Join(unassignment.Tags, ","),
|
||||
Ref: &provider.Reference{
|
||||
ResourceId: &rid,
|
||||
Path: ".",
|
||||
},
|
||||
SpaceOwner: sres.Info.Owner,
|
||||
Executant: revaCtx.ContextMustGetUser(r.Context()).Id,
|
||||
}
|
||||
if err := events.Publish(ctx, g.eventsPublisher, ev); err != nil {
|
||||
g.logger.Error().Err(err).Msg("Failed to publish TagsAdded event")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// publishTagsRemoved publishes a TagsRemoved event and rolls back the metadata
|
||||
// change if publishing fails. Returns nil on success or if no publisher is configured.
|
||||
func (g Graph) publishTagsRemoved(ctx context.Context, client gateway.GatewayAPIClient, ev events.TagsRemoved, tagsChanged bool, previousTags string) error {
|
||||
if g.eventsPublisher == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := events.Publish(ctx, g.eventsPublisher, ev); err != nil {
|
||||
g.logger.Error().Err(err).Msg("Failed to publish TagsRemoved event")
|
||||
|
||||
// Try to rollback the metadata change so we don't leave the
|
||||
// system in an inconsistent state (metadata updated but search
|
||||
// index not notified).
|
||||
// NOTE: this rollback is not atomic — another request could
|
||||
// modify the tags between our SetArbitraryMetadata and this
|
||||
// restore. A proper fix would require locking the resource.
|
||||
if tagsChanged {
|
||||
if _, rollbackErr := client.SetArbitraryMetadata(ctx, &provider.SetArbitraryMetadataRequest{
|
||||
Ref: ev.Ref,
|
||||
ArbitraryMetadata: &provider.ArbitraryMetadata{
|
||||
Metadata: map[string]string{
|
||||
"tags": previousTags,
|
||||
},
|
||||
},
|
||||
}); rollbackErr != nil {
|
||||
g.logger.Error().Err(rollbackErr).Msg("failed to rollback tags after publish failure")
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -169,13 +169,16 @@
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"glob": "10.5.0",
|
||||
"minimatch@>=9.0.0 <9.0.6": "9.0.6",
|
||||
"minimatch@>=9.0.0 <9.0.7": "9.0.7",
|
||||
"js-yaml": ">=4.1.1",
|
||||
"lodash": ">=4.17.23",
|
||||
"undici": ">=7.18.2",
|
||||
"vue-template-compiler": "^3.0.0",
|
||||
"brace-expansion@>=1.0.0 <=1.1.11": ">=1.1.12",
|
||||
"brace-expansion@>=2.0.0 <=2.0.1": ">=2.0.2",
|
||||
"rollup": "2.80.0",
|
||||
"serialize-javascript": "7.0.3",
|
||||
"ajv@>=6.0.0 <6.14.0": "6.14.0",
|
||||
"ajv@>=8.0.0 <8.18.0": "8.18.0"
|
||||
},
|
||||
"ignoredBuiltDependencies": [
|
||||
|
||||
Generated
+79
-84
@@ -6,13 +6,16 @@ settings:
|
||||
|
||||
overrides:
|
||||
glob: 10.5.0
|
||||
minimatch@>=9.0.0 <9.0.6: 9.0.6
|
||||
minimatch@>=9.0.0 <9.0.7: 9.0.7
|
||||
js-yaml: '>=4.1.1'
|
||||
lodash: '>=4.17.23'
|
||||
undici: '>=7.18.2'
|
||||
vue-template-compiler: ^3.0.0
|
||||
brace-expansion@>=1.0.0 <=1.1.11: '>=1.1.12'
|
||||
brace-expansion@>=2.0.0 <=2.0.1: '>=2.0.2'
|
||||
rollup: 2.80.0
|
||||
serialize-javascript: 7.0.3
|
||||
ajv@>=6.0.0 <6.14.0: 6.14.0
|
||||
ajv@>=8.0.0 <8.18.0: 8.18.0
|
||||
|
||||
importers:
|
||||
@@ -1966,7 +1969,7 @@ packages:
|
||||
peerDependencies:
|
||||
'@babel/core': ^7.0.0
|
||||
'@types/babel__core': ^7.1.9
|
||||
rollup: ^1.20.0||^2.0.0
|
||||
rollup: 2.80.0
|
||||
peerDependenciesMeta:
|
||||
'@types/babel__core':
|
||||
optional: true
|
||||
@@ -1975,7 +1978,7 @@ packages:
|
||||
resolution: {integrity: sha512-9eO5McEICxMzJpDW9OnMYSv4Sta3hmt7VtBFz5zR9273suNOydOyq/FrGeGy+KsTRFm8w0SLVhzig2ILFT63Ag==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
peerDependencies:
|
||||
rollup: ^2.78.0||^3.0.0||^4.0.0
|
||||
rollup: 2.80.0
|
||||
peerDependenciesMeta:
|
||||
rollup:
|
||||
optional: true
|
||||
@@ -1983,13 +1986,13 @@ packages:
|
||||
'@rollup/plugin-replace@2.4.2':
|
||||
resolution: {integrity: sha512-IGcu+cydlUMZ5En85jxHH4qj2hta/11BHq95iHEyb2sbgiN0eCdzvUcHw5gt9pBL5lTi4JDYJ1acCoMGpTvEZg==}
|
||||
peerDependencies:
|
||||
rollup: ^1.20.0 || ^2.0.0
|
||||
rollup: 2.80.0
|
||||
|
||||
'@rollup/plugin-terser@0.4.4':
|
||||
resolution: {integrity: sha512-XHeJC5Bgvs8LfukDwWZp7yeqin6ns8RTl2B9avbejt6tZqsqvVoWI7ZTQrcNsfKEDWBTnTxM8nMDkO2IFFbd0A==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
peerDependencies:
|
||||
rollup: ^2.0.0||^3.0.0||^4.0.0
|
||||
rollup: 2.80.0
|
||||
peerDependenciesMeta:
|
||||
rollup:
|
||||
optional: true
|
||||
@@ -1998,13 +2001,13 @@ packages:
|
||||
resolution: {integrity: sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==}
|
||||
engines: {node: '>= 8.0.0'}
|
||||
peerDependencies:
|
||||
rollup: ^1.20.0||^2.0.0
|
||||
rollup: 2.80.0
|
||||
|
||||
'@rollup/pluginutils@5.1.2':
|
||||
resolution: {integrity: sha512-/FIdS3PyZ39bjZlwqFnWqCOVnW7o963LtKMwQOD0NhQqw22gSr2YY1afu3FxRip4ZCZNsD5jq6Aaz6QV3D/Njw==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
peerDependencies:
|
||||
rollup: ^1.20.0||^2.0.0||^3.0.0||^4.0.0
|
||||
rollup: 2.80.0
|
||||
peerDependenciesMeta:
|
||||
rollup:
|
||||
optional: true
|
||||
@@ -2549,15 +2552,15 @@ packages:
|
||||
ajv-keywords@3.5.2:
|
||||
resolution: {integrity: sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==}
|
||||
peerDependencies:
|
||||
ajv: ^6.9.1
|
||||
ajv: 6.14.0
|
||||
|
||||
ajv-keywords@5.1.0:
|
||||
resolution: {integrity: sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==}
|
||||
peerDependencies:
|
||||
ajv: 8.18.0
|
||||
|
||||
ajv@6.12.6:
|
||||
resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==}
|
||||
ajv@6.14.0:
|
||||
resolution: {integrity: sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==}
|
||||
|
||||
ajv@8.18.0:
|
||||
resolution: {integrity: sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==}
|
||||
@@ -4772,15 +4775,15 @@ packages:
|
||||
peerDependencies:
|
||||
webpack: ^5.0.0
|
||||
|
||||
minimatch@3.1.4:
|
||||
resolution: {integrity: sha512-twmL+S8+7yIsE9wsqgzU3E8/LumN3M3QELrBZ20OdmQ9jB2JvW5oZtBEmft84k/Gs5CG9mqtWc6Y9vW+JEzGxw==}
|
||||
minimatch@3.1.5:
|
||||
resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==}
|
||||
|
||||
minimatch@5.1.8:
|
||||
resolution: {integrity: sha512-7RN35vit8DeBclkofOVmBY0eDAZZQd1HzmukRdSyz95CRh8FT54eqnbj0krQr3mrHR6sfRyYkyhwBWjoV5uqlQ==}
|
||||
minimatch@5.1.9:
|
||||
resolution: {integrity: sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
minimatch@9.0.6:
|
||||
resolution: {integrity: sha512-kQAVowdR33euIqeA0+VZTDqU+qo1IeVY+hrKYtZMio3Pg0P0vuh/kwRylLUddJhB6pf3q/botcOvRtx4IN1wqQ==}
|
||||
minimatch@9.0.7:
|
||||
resolution: {integrity: sha512-MOwgjc8tfrpn5QQEvjijjmDVtMw2oL88ugTevzxQnzRLm6l3fVEF2gzU0kYeYYKD8C66+IdGX6peJ4MyUlUnPg==}
|
||||
engines: {node: '>=16 || 14 >=14.17'}
|
||||
|
||||
minimist@1.2.8:
|
||||
@@ -5562,9 +5565,6 @@ packages:
|
||||
raf@3.4.1:
|
||||
resolution: {integrity: sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==}
|
||||
|
||||
randombytes@2.1.0:
|
||||
resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==}
|
||||
|
||||
react-app-polyfill@2.0.0:
|
||||
resolution: {integrity: sha512-0sF4ny9v/B7s6aoehwze9vJNWcmCemAUYBVasscVr92+UYiEqDXOxfKjXN685mDaMRNF3WdhHQs76oTODMocFA==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -5835,8 +5835,8 @@ packages:
|
||||
deprecated: Rimraf versions prior to v4 are no longer supported
|
||||
hasBin: true
|
||||
|
||||
rollup@2.79.2:
|
||||
resolution: {integrity: sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==}
|
||||
rollup@2.80.0:
|
||||
resolution: {integrity: sha512-cIFJOD1DESzpjOBl763Kp1AH7UE/0fcdHe6rZXUdQ9c50uvgigvW97u3IcSeBwOkgqL/PXPBktBCh0KEu5L8XQ==}
|
||||
engines: {node: '>=10.0.0'}
|
||||
hasBin: true
|
||||
|
||||
@@ -5945,8 +5945,9 @@ packages:
|
||||
seq@0.3.5:
|
||||
resolution: {integrity: sha512-sisY2Ln1fj43KBkRtXkesnRHYNdswIkIibvNe/0UKm2GZxjMbqmccpiatoKr/k2qX5VKiLU8xm+tz/74LAho4g==}
|
||||
|
||||
serialize-javascript@6.0.2:
|
||||
resolution: {integrity: sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==}
|
||||
serialize-javascript@7.0.3:
|
||||
resolution: {integrity: sha512-h+cZ/XXarqDgCjo+YSyQU/ulDEESGGf8AMK9pPNmhNSl/FzPl6L8pMp1leca5z6NuG6tvV/auC8/43tmovowww==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
|
||||
set-function-length@1.2.2:
|
||||
resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==}
|
||||
@@ -8203,14 +8204,14 @@ snapshots:
|
||||
|
||||
'@eslint/eslintrc@2.1.4':
|
||||
dependencies:
|
||||
ajv: 6.12.6
|
||||
ajv: 6.14.0
|
||||
debug: 4.4.3
|
||||
espree: 9.6.1
|
||||
globals: 13.24.0
|
||||
ignore: 5.3.2
|
||||
import-fresh: 3.3.1
|
||||
js-yaml: 4.1.1
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
strip-json-comments: 3.1.1
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
@@ -8275,7 +8276,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@humanwhocodes/object-schema': 2.0.3
|
||||
debug: 4.4.3
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -8696,55 +8697,55 @@ snapshots:
|
||||
|
||||
'@postalsys/gettext@4.1.1': {}
|
||||
|
||||
'@rollup/plugin-babel@5.3.1(@babel/core@7.28.6)(@types/babel__core@7.20.5)(rollup@2.79.2)':
|
||||
'@rollup/plugin-babel@5.3.1(@babel/core@7.28.6)(@types/babel__core@7.20.5)(rollup@2.80.0)':
|
||||
dependencies:
|
||||
'@babel/core': 7.28.6
|
||||
'@babel/helper-module-imports': 7.28.6
|
||||
'@rollup/pluginutils': 3.1.0(rollup@2.79.2)
|
||||
rollup: 2.79.2
|
||||
'@rollup/pluginutils': 3.1.0(rollup@2.80.0)
|
||||
rollup: 2.80.0
|
||||
optionalDependencies:
|
||||
'@types/babel__core': 7.20.5
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@rollup/plugin-node-resolve@15.3.0(rollup@2.79.2)':
|
||||
'@rollup/plugin-node-resolve@15.3.0(rollup@2.80.0)':
|
||||
dependencies:
|
||||
'@rollup/pluginutils': 5.1.2(rollup@2.79.2)
|
||||
'@rollup/pluginutils': 5.1.2(rollup@2.80.0)
|
||||
'@types/resolve': 1.20.2
|
||||
deepmerge: 4.3.1
|
||||
is-module: 1.0.0
|
||||
resolve: 1.22.11
|
||||
optionalDependencies:
|
||||
rollup: 2.79.2
|
||||
rollup: 2.80.0
|
||||
|
||||
'@rollup/plugin-replace@2.4.2(rollup@2.79.2)':
|
||||
'@rollup/plugin-replace@2.4.2(rollup@2.80.0)':
|
||||
dependencies:
|
||||
'@rollup/pluginutils': 3.1.0(rollup@2.79.2)
|
||||
'@rollup/pluginutils': 3.1.0(rollup@2.80.0)
|
||||
magic-string: 0.25.9
|
||||
rollup: 2.79.2
|
||||
rollup: 2.80.0
|
||||
|
||||
'@rollup/plugin-terser@0.4.4(rollup@2.79.2)':
|
||||
'@rollup/plugin-terser@0.4.4(rollup@2.80.0)':
|
||||
dependencies:
|
||||
serialize-javascript: 6.0.2
|
||||
serialize-javascript: 7.0.3
|
||||
smob: 1.5.0
|
||||
terser: 5.44.0
|
||||
optionalDependencies:
|
||||
rollup: 2.79.2
|
||||
rollup: 2.80.0
|
||||
|
||||
'@rollup/pluginutils@3.1.0(rollup@2.79.2)':
|
||||
'@rollup/pluginutils@3.1.0(rollup@2.80.0)':
|
||||
dependencies:
|
||||
'@types/estree': 0.0.39
|
||||
estree-walker: 1.0.1
|
||||
picomatch: 2.3.1
|
||||
rollup: 2.79.2
|
||||
rollup: 2.80.0
|
||||
|
||||
'@rollup/pluginutils@5.1.2(rollup@2.79.2)':
|
||||
'@rollup/pluginutils@5.1.2(rollup@2.80.0)':
|
||||
dependencies:
|
||||
'@types/estree': 1.0.6
|
||||
estree-walker: 2.0.2
|
||||
picomatch: 2.3.1
|
||||
optionalDependencies:
|
||||
rollup: 2.79.2
|
||||
rollup: 2.80.0
|
||||
|
||||
'@rtsao/scc@1.1.0': {}
|
||||
|
||||
@@ -9100,7 +9101,7 @@ snapshots:
|
||||
debug: 4.4.3
|
||||
globby: 11.1.0
|
||||
is-glob: 4.0.3
|
||||
minimatch: 9.0.6
|
||||
minimatch: 9.0.7
|
||||
semver: 7.7.3
|
||||
ts-api-utils: 1.4.3(typescript@5.9.3)
|
||||
optionalDependencies:
|
||||
@@ -9115,7 +9116,7 @@ snapshots:
|
||||
debug: 4.4.3
|
||||
globby: 11.1.0
|
||||
is-glob: 4.0.3
|
||||
minimatch: 9.0.6
|
||||
minimatch: 9.0.7
|
||||
semver: 7.7.3
|
||||
ts-api-utils: 1.4.3(typescript@5.9.3)
|
||||
optionalDependencies:
|
||||
@@ -9132,7 +9133,7 @@ snapshots:
|
||||
debug: 4.4.3
|
||||
fast-glob: 3.3.3
|
||||
is-glob: 4.0.3
|
||||
minimatch: 9.0.6
|
||||
minimatch: 9.0.7
|
||||
semver: 7.7.3
|
||||
ts-api-utils: 2.1.0(typescript@5.9.3)
|
||||
typescript: 5.9.3
|
||||
@@ -9369,16 +9370,16 @@ snapshots:
|
||||
optionalDependencies:
|
||||
ajv: 8.18.0
|
||||
|
||||
ajv-keywords@3.5.2(ajv@6.12.6):
|
||||
ajv-keywords@3.5.2(ajv@6.14.0):
|
||||
dependencies:
|
||||
ajv: 6.12.6
|
||||
ajv: 6.14.0
|
||||
|
||||
ajv-keywords@5.1.0(ajv@8.18.0):
|
||||
dependencies:
|
||||
ajv: 8.18.0
|
||||
fast-deep-equal: 3.1.3
|
||||
|
||||
ajv@6.12.6:
|
||||
ajv@6.14.0:
|
||||
dependencies:
|
||||
fast-deep-equal: 3.1.3
|
||||
fast-json-stable-stringify: 2.1.0
|
||||
@@ -10056,7 +10057,7 @@ snapshots:
|
||||
jest-worker: 30.2.0
|
||||
postcss: 8.5.6
|
||||
schema-utils: 4.3.3
|
||||
serialize-javascript: 6.0.2
|
||||
serialize-javascript: 7.0.3
|
||||
webpack: 5.104.1
|
||||
|
||||
css-prefers-color-scheme@10.0.0(postcss@8.5.6):
|
||||
@@ -10692,7 +10693,7 @@ snapshots:
|
||||
hasown: 2.0.2
|
||||
is-core-module: 2.16.1
|
||||
is-glob: 4.0.3
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
object.fromentries: 2.0.8
|
||||
object.groupby: 1.0.3
|
||||
object.values: 1.2.1
|
||||
@@ -10721,7 +10722,7 @@ snapshots:
|
||||
hasown: 2.0.2
|
||||
is-core-module: 2.16.1
|
||||
is-glob: 4.0.3
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
object.fromentries: 2.0.8
|
||||
object.groupby: 1.0.3
|
||||
object.values: 1.2.1
|
||||
@@ -10771,7 +10772,7 @@ snapshots:
|
||||
hasown: 2.0.2
|
||||
jsx-ast-utils: 3.3.5
|
||||
language-tags: 1.0.9
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
object.fromentries: 2.0.8
|
||||
safe-regex-test: 1.1.0
|
||||
string.prototype.includes: 2.0.1
|
||||
@@ -10792,7 +10793,7 @@ snapshots:
|
||||
estraverse: 5.3.0
|
||||
hasown: 2.0.2
|
||||
jsx-ast-utils: 3.3.5
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
object.entries: 1.1.9
|
||||
object.fromentries: 2.0.8
|
||||
object.values: 1.2.1
|
||||
@@ -10855,7 +10856,7 @@ snapshots:
|
||||
'@humanwhocodes/module-importer': 1.0.1
|
||||
'@nodelib/fs.walk': 1.2.8
|
||||
'@ungap/structured-clone': 1.3.0
|
||||
ajv: 6.12.6
|
||||
ajv: 6.14.0
|
||||
chalk: 4.1.2
|
||||
cross-spawn: 7.0.5
|
||||
debug: 4.3.5
|
||||
@@ -10880,7 +10881,7 @@ snapshots:
|
||||
json-stable-stringify-without-jsonify: 1.0.1
|
||||
levn: 0.4.1
|
||||
lodash.merge: 4.6.2
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
natural-compare: 1.4.0
|
||||
optionator: 0.9.4
|
||||
strip-ansi: 6.0.1
|
||||
@@ -10987,7 +10988,7 @@ snapshots:
|
||||
|
||||
filelist@1.0.4:
|
||||
dependencies:
|
||||
minimatch: 5.1.8
|
||||
minimatch: 5.1.9
|
||||
|
||||
filesize@8.0.7: {}
|
||||
|
||||
@@ -11051,7 +11052,7 @@ snapshots:
|
||||
fs-extra: 9.1.0
|
||||
glob: 10.5.0
|
||||
memfs: 3.5.3
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
schema-utils: 2.7.0
|
||||
semver: 7.7.3
|
||||
tapable: 1.1.3
|
||||
@@ -11212,7 +11213,7 @@ snapshots:
|
||||
dependencies:
|
||||
foreground-child: 3.3.1
|
||||
jackspeak: 3.4.3
|
||||
minimatch: 9.0.6
|
||||
minimatch: 9.0.7
|
||||
minipass: 7.1.2
|
||||
package-json-from-dist: 1.0.1
|
||||
path-scurry: 1.11.1
|
||||
@@ -11668,7 +11669,7 @@ snapshots:
|
||||
async: 3.2.5
|
||||
chalk: 4.1.2
|
||||
filelist: 1.0.4
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
|
||||
jest-changed-files@30.2.0:
|
||||
dependencies:
|
||||
@@ -12219,7 +12220,7 @@ snapshots:
|
||||
matcher-collection@2.0.1:
|
||||
dependencies:
|
||||
'@types/minimatch': 3.0.5
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
|
||||
math-intrinsics@1.1.0: {}
|
||||
|
||||
@@ -12261,15 +12262,15 @@ snapshots:
|
||||
tapable: 2.2.1
|
||||
webpack: 5.104.1
|
||||
|
||||
minimatch@3.1.4:
|
||||
minimatch@3.1.5:
|
||||
dependencies:
|
||||
brace-expansion: 5.0.3
|
||||
|
||||
minimatch@5.1.8:
|
||||
minimatch@5.1.9:
|
||||
dependencies:
|
||||
brace-expansion: 5.0.3
|
||||
|
||||
minimatch@9.0.6:
|
||||
minimatch@9.0.7:
|
||||
dependencies:
|
||||
brace-expansion: 5.0.3
|
||||
|
||||
@@ -13079,10 +13080,6 @@ snapshots:
|
||||
dependencies:
|
||||
performance-now: 2.1.0
|
||||
|
||||
randombytes@2.1.0:
|
||||
dependencies:
|
||||
safe-buffer: 5.2.1
|
||||
|
||||
react-app-polyfill@2.0.0:
|
||||
dependencies:
|
||||
core-js: 3.37.1
|
||||
@@ -13271,7 +13268,7 @@ snapshots:
|
||||
|
||||
recursive-readdir@2.2.3:
|
||||
dependencies:
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
|
||||
redent@3.0.0:
|
||||
dependencies:
|
||||
@@ -13424,7 +13421,7 @@ snapshots:
|
||||
dependencies:
|
||||
glob: 10.5.0
|
||||
|
||||
rollup@2.79.2:
|
||||
rollup@2.80.0:
|
||||
optionalDependencies:
|
||||
fsevents: 2.3.3
|
||||
|
||||
@@ -13479,14 +13476,14 @@ snapshots:
|
||||
schema-utils@2.7.0:
|
||||
dependencies:
|
||||
'@types/json-schema': 7.0.15
|
||||
ajv: 6.12.6
|
||||
ajv-keywords: 3.5.2(ajv@6.12.6)
|
||||
ajv: 6.14.0
|
||||
ajv-keywords: 3.5.2(ajv@6.14.0)
|
||||
|
||||
schema-utils@3.3.0:
|
||||
dependencies:
|
||||
'@types/json-schema': 7.0.15
|
||||
ajv: 6.12.6
|
||||
ajv-keywords: 3.5.2(ajv@6.12.6)
|
||||
ajv: 6.14.0
|
||||
ajv-keywords: 3.5.2(ajv@6.14.0)
|
||||
|
||||
schema-utils@4.2.0:
|
||||
dependencies:
|
||||
@@ -13517,9 +13514,7 @@ snapshots:
|
||||
chainsaw: 0.0.9
|
||||
hashish: 0.0.4
|
||||
|
||||
serialize-javascript@6.0.2:
|
||||
dependencies:
|
||||
randombytes: 2.1.0
|
||||
serialize-javascript@7.0.3: {}
|
||||
|
||||
set-function-length@1.2.2:
|
||||
dependencies:
|
||||
@@ -13865,7 +13860,7 @@ snapshots:
|
||||
'@jridgewell/trace-mapping': 0.3.31
|
||||
jest-worker: 27.5.1
|
||||
schema-utils: 4.3.3
|
||||
serialize-javascript: 6.0.2
|
||||
serialize-javascript: 7.0.3
|
||||
terser: 5.44.0
|
||||
webpack: 5.104.1
|
||||
|
||||
@@ -13880,7 +13875,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@istanbuljs/schema': 0.1.3
|
||||
glob: 10.5.0
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
|
||||
text-decoder@1.1.1:
|
||||
dependencies:
|
||||
@@ -14174,7 +14169,7 @@ snapshots:
|
||||
'@types/minimatch': 3.0.5
|
||||
ensure-posix-path: 1.1.1
|
||||
matcher-collection: 2.0.1
|
||||
minimatch: 3.1.4
|
||||
minimatch: 3.1.5
|
||||
|
||||
walker@1.0.8:
|
||||
dependencies:
|
||||
@@ -14326,10 +14321,10 @@ snapshots:
|
||||
'@babel/core': 7.28.6
|
||||
'@babel/preset-env': 7.28.6(@babel/core@7.28.6)
|
||||
'@babel/runtime': 7.28.6
|
||||
'@rollup/plugin-babel': 5.3.1(@babel/core@7.28.6)(@types/babel__core@7.20.5)(rollup@2.79.2)
|
||||
'@rollup/plugin-node-resolve': 15.3.0(rollup@2.79.2)
|
||||
'@rollup/plugin-replace': 2.4.2(rollup@2.79.2)
|
||||
'@rollup/plugin-terser': 0.4.4(rollup@2.79.2)
|
||||
'@rollup/plugin-babel': 5.3.1(@babel/core@7.28.6)(@types/babel__core@7.20.5)(rollup@2.80.0)
|
||||
'@rollup/plugin-node-resolve': 15.3.0(rollup@2.80.0)
|
||||
'@rollup/plugin-replace': 2.4.2(rollup@2.80.0)
|
||||
'@rollup/plugin-terser': 0.4.4(rollup@2.80.0)
|
||||
'@surma/rollup-plugin-off-main-thread': 2.2.3
|
||||
ajv: 8.18.0
|
||||
common-tags: 1.8.2
|
||||
@@ -14338,7 +14333,7 @@ snapshots:
|
||||
glob: 10.5.0
|
||||
lodash: 4.17.23
|
||||
pretty-bytes: 5.6.0
|
||||
rollup: 2.79.2
|
||||
rollup: 2.80.0
|
||||
source-map: 0.8.0-beta.0
|
||||
stringify-object: 3.3.0
|
||||
strip-comments: 2.0.1
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package content
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -62,11 +63,6 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
if ri.Size > t.ContentExtractionSizeLimit {
|
||||
t.logger.Info().Interface("ResourceID", ri.Id).Str("Name", ri.Name).Msg("file exceeds content extraction size limit. skipping.")
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
if ri.Type != provider.ResourceType_RESOURCE_TYPE_FILE {
|
||||
return doc, nil
|
||||
}
|
||||
@@ -77,7 +73,12 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
|
||||
}
|
||||
defer data.Close()
|
||||
|
||||
metas, err := t.tika.MetaRecursive(ctx, data)
|
||||
var reader io.Reader = data
|
||||
if ri.Size > t.ContentExtractionSizeLimit {
|
||||
reader = io.LimitReader(data, int64(t.ContentExtractionSizeLimit)) //nolint:gosec // ContentExtractionSizeLimit is a config value, never exceeds int64 max
|
||||
}
|
||||
|
||||
metas, err := t.tika.MetaRecursive(ctx, reader)
|
||||
if err != nil {
|
||||
return doc, err
|
||||
}
|
||||
@@ -200,8 +201,12 @@ func (t Tika) getPhoto(meta map[string][]string) *libregraph.Photo {
|
||||
}
|
||||
}
|
||||
|
||||
if v, err := getFirstValue(meta, "Base ISO"); err == nil {
|
||||
if i, err := strconv.ParseInt(v, 0, 32); err == nil {
|
||||
isoStr, err := getFirstValue(meta, "exif:IsoSpeedRatings")
|
||||
if err != nil {
|
||||
isoStr, err = getFirstValue(meta, "Base ISO")
|
||||
}
|
||||
if err == nil {
|
||||
if i, err := strconv.ParseInt(isoStr, 0, 32); err == nil {
|
||||
initPhoto()
|
||||
photo.SetIso(int32(i))
|
||||
}
|
||||
|
||||
@@ -191,7 +191,7 @@ var _ = Describe("Tika", func() {
|
||||
"exif:ExposureTime": "0.001",
|
||||
"exif:FNumber": "1.8",
|
||||
"exif:FocalLength": "50",
|
||||
"Base ISO": "100",
|
||||
"exif:IsoSpeedRatings": "100",
|
||||
"tiff:Orientation": "1",
|
||||
"exif:DateTimeOriginal": "2018-01-01T12:34:56"
|
||||
}
|
||||
@@ -216,6 +216,56 @@ var _ = Describe("Tika", func() {
|
||||
Expect(photo.TakenDateTime).To(Equal(libregraph.PtrTime(time.Date(2018, 1, 1, 12, 34, 56, 0, time.UTC))))
|
||||
})
|
||||
|
||||
It("falls back to Base ISO when exif:IsoSpeedRatings is absent", func() {
|
||||
fullResponse = `[
|
||||
{
|
||||
"tiff:Make": "Canon",
|
||||
"Base ISO": "200"
|
||||
}
|
||||
]`
|
||||
doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{
|
||||
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
|
||||
Size: 1,
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(doc.Photo).ToNot(BeNil())
|
||||
Expect(doc.Photo.Iso).To(Equal(libregraph.PtrInt32(200)))
|
||||
})
|
||||
|
||||
It("extracts metadata from oversized files using truncated stream", func() {
|
||||
fullResponse = `[
|
||||
{
|
||||
"tiff:Make": "Google",
|
||||
"tiff:Model": "Pixel 7",
|
||||
"exif:FNumber": "1.85",
|
||||
"exif:FocalLength": "6.81",
|
||||
"Base ISO": "58",
|
||||
"tiff:Orientation": "1",
|
||||
"exif:DateTimeOriginal": "2024-06-15T14:30:00",
|
||||
"tiff:ImageWidth": "4080",
|
||||
"tiff:ImageLength": "3072"
|
||||
}
|
||||
]`
|
||||
|
||||
tika.ContentExtractionSizeLimit = 10
|
||||
|
||||
doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{
|
||||
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
|
||||
Size: 8_000_000,
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(doc.Photo).ToNot(BeNil())
|
||||
Expect(doc.Photo.CameraMake).To(Equal(libregraph.PtrString("Google")))
|
||||
Expect(doc.Photo.CameraModel).To(Equal(libregraph.PtrString("Pixel 7")))
|
||||
Expect(doc.Photo.TakenDateTime).ToNot(BeNil())
|
||||
|
||||
Expect(doc.Image).ToNot(BeNil())
|
||||
Expect(doc.Image.Width).To(Equal(libregraph.PtrInt32(4080)))
|
||||
Expect(doc.Image.Height).To(Equal(libregraph.PtrInt32(3072)))
|
||||
})
|
||||
|
||||
It("removes stop words", func() {
|
||||
body = "body to test stop words!!! against almost everyone"
|
||||
language = "en"
|
||||
|
||||
@@ -35,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 (
|
||||
@@ -168,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)
|
||||
}
|
||||
|
||||
|
||||
@@ -707,7 +707,10 @@ class FeatureContext extends BehatVariablesContext {
|
||||
*/
|
||||
public function removeSchemeFromUrl(string $url): string {
|
||||
$parsedUrl = parse_url($url);
|
||||
return $parsedUrl["host"] . ":" . $parsedUrl["port"];
|
||||
if (isset($parsedUrl['port'])) {
|
||||
return $parsedUrl["host"] . ":" . $parsedUrl["port"];
|
||||
}
|
||||
return $parsedUrl["host"];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -168,7 +168,7 @@ Feature: check file info with different wopi apps
|
||||
"const": "textfile0.txt"
|
||||
},
|
||||
"PostMessageOrigin": {
|
||||
"const": "https://localhost:9200"
|
||||
"const": "%base_url%"
|
||||
},
|
||||
"DisablePrint": {
|
||||
"const": false
|
||||
@@ -566,7 +566,7 @@ Feature: check file info with different wopi apps
|
||||
"const": "textfile0.txt"
|
||||
},
|
||||
"PostMessageOrigin": {
|
||||
"const": "https://localhost:9200"
|
||||
"const": "%base_url%"
|
||||
},
|
||||
"DisablePrint": {
|
||||
"const": <disable-print>
|
||||
@@ -676,7 +676,7 @@ Feature: check file info with different wopi apps
|
||||
"const": "textfile0.txt"
|
||||
},
|
||||
"PostMessageOrigin": {
|
||||
"const": "https://localhost:9200"
|
||||
"const": "%base_url%"
|
||||
},
|
||||
"DisablePrint": {
|
||||
"const": false
|
||||
@@ -1062,7 +1062,7 @@ Feature: check file info with different wopi apps
|
||||
"const": "renamedfile.txt"
|
||||
},
|
||||
"PostMessageOrigin": {
|
||||
"const": "https://localhost:9200"
|
||||
"const": "%base_url%"
|
||||
},
|
||||
"DisablePrint": {
|
||||
"const": false
|
||||
@@ -1409,7 +1409,7 @@ Feature: check file info with different wopi apps
|
||||
"const": "text.txt"
|
||||
},
|
||||
"PostMessageOrigin": {
|
||||
"const": "https://localhost:9200"
|
||||
"const": "%base_url%"
|
||||
},
|
||||
"DisablePrint": {
|
||||
"const": false
|
||||
@@ -1795,7 +1795,7 @@ Feature: check file info with different wopi apps
|
||||
"const": "text.txt"
|
||||
},
|
||||
"PostMessageOrigin": {
|
||||
"const": "https://localhost:9200"
|
||||
"const": "%base_url%"
|
||||
},
|
||||
"DisablePrint": {
|
||||
"const": <disable-print>
|
||||
|
||||
@@ -27,7 +27,7 @@ Feature: collaboration (wopi)
|
||||
"properties": {
|
||||
"app_url": {
|
||||
"type": "string",
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}$"
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}"
|
||||
},
|
||||
"method": {
|
||||
"const": "POST"
|
||||
@@ -73,7 +73,7 @@ Feature: collaboration (wopi)
|
||||
"properties": {
|
||||
"app_url": {
|
||||
"type": "string",
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}$"
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}"
|
||||
},
|
||||
"method": {
|
||||
"const": "POST"
|
||||
@@ -115,7 +115,7 @@ Feature: collaboration (wopi)
|
||||
"properties": {
|
||||
"app_url": {
|
||||
"type": "string",
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}$"
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}"
|
||||
},
|
||||
"method": {
|
||||
"const": "POST"
|
||||
@@ -163,7 +163,7 @@ Feature: collaboration (wopi)
|
||||
"properties": {
|
||||
"app_url": {
|
||||
"type": "string",
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}$"
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}"
|
||||
},
|
||||
"method": {
|
||||
"const": "POST"
|
||||
@@ -214,7 +214,7 @@ Feature: collaboration (wopi)
|
||||
"properties": {
|
||||
"app_url": {
|
||||
"type": "string",
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}$"
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}"
|
||||
},
|
||||
"method": {
|
||||
"const": "POST"
|
||||
@@ -315,7 +315,7 @@ Feature: collaboration (wopi)
|
||||
"properties": {
|
||||
"app_url": {
|
||||
"type": "string",
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}$"
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}"
|
||||
},
|
||||
"method": {
|
||||
"const": "POST"
|
||||
@@ -366,9 +366,9 @@ Feature: collaboration (wopi)
|
||||
}
|
||||
"""
|
||||
Examples:
|
||||
| app-endpoint | url-query |
|
||||
| /app/open-with-web?file_id=<<FILEID>>&app_name=FakeOffice | app=FakeOffice& |
|
||||
| /app/open-with-web?file_id=<<FILEID>> | app=FakeOffice& |
|
||||
| app-endpoint | url-query |
|
||||
| /app/open-with-web?file_id=<<FILEID>>&app_name=FakeOffice | app=FakeOffice& |
|
||||
| /app/open-with-web?file_id=<<FILEID>> | app=(FakeOffice\|Collabora\|OnlyOffice)& |
|
||||
|
||||
|
||||
Scenario: open text file using open-with-web with app name in url query (MIME type not registered in app-registry)
|
||||
@@ -408,7 +408,7 @@ Feature: collaboration (wopi)
|
||||
"properties": {
|
||||
"uri": {
|
||||
"type": "string",
|
||||
"pattern": "%base_url%/external\\?app=FakeOffice&contextRouteName=files-spaces-personal&fileId=%uuidv4_pattern%%24%uuidv4_pattern%%21%uuidv4_pattern%$"
|
||||
"pattern": "%base_url%/external\\?app=(FakeOffice|Collabora|OnlyOffice)&contextRouteName=files-spaces-personal&fileId=%uuidv4_pattern%%24%uuidv4_pattern%%21%uuidv4_pattern%$"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -441,9 +441,9 @@ Feature: collaboration (wopi)
|
||||
}
|
||||
"""
|
||||
Examples:
|
||||
| app-endpoint | url-query |
|
||||
| /app/open-with-web?file_id=<<FILEID>>&app_name=FakeOffice | app=FakeOffice& |
|
||||
| /app/open-with-web?file_id=<<FILEID>> | app=FakeOffice& |
|
||||
| app-endpoint | url-query |
|
||||
| /app/open-with-web?file_id=<<FILEID>>&app_name=FakeOffice | app=FakeOffice& |
|
||||
| /app/open-with-web?file_id=<<FILEID>> | app=(FakeOffice\|Collabora\|OnlyOffice)& |
|
||||
|
||||
|
||||
Scenario Outline: sharee open file with .odt extension (open-with-web)
|
||||
@@ -473,9 +473,9 @@ Feature: collaboration (wopi)
|
||||
}
|
||||
"""
|
||||
Examples:
|
||||
| app-endpoint | url-query |
|
||||
| /app/open-with-web?file_id=<<FILEID>>&app_name=FakeOffice | app=FakeOffice& |
|
||||
| /app/open-with-web?file_id=<<FILEID>> | app=FakeOffice& |
|
||||
| app-endpoint | url-query |
|
||||
| /app/open-with-web?file_id=<<FILEID>>&app_name=FakeOffice | app=FakeOffice& |
|
||||
| /app/open-with-web?file_id=<<FILEID>> | app=(FakeOffice\|Collabora\|OnlyOffice)& |
|
||||
|
||||
|
||||
Scenario Outline: open file with .odt extension with different view mode (open-with-web)
|
||||
@@ -1108,7 +1108,7 @@ Feature: collaboration (wopi)
|
||||
"properties": {
|
||||
"app_url": {
|
||||
"type": "string",
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}$"
|
||||
"pattern": "^.*\\?WOPISrc=.*wopi%2Ffiles%2F[a-fA-F0-9]{64}"
|
||||
},
|
||||
"method": {
|
||||
"const": "POST"
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
{{/*
|
||||
|
||||
DO NOT RENAME THIS FILE
|
||||
|
||||
Filename: _zoverride.tpl
|
||||
|
||||
Override filename starts with 'z'
|
||||
to make sure it is loaded after all other templates.
|
||||
|
||||
Using the existing variable definitions
|
||||
which are already included in most of the templates.
|
||||
*/}}
|
||||
|
||||
{{- define "ocis.caPath" -}}
|
||||
- name: logdir
|
||||
mountPath: /logs
|
||||
{{- end -}}
|
||||
|
||||
{{- define "ocis.caVolume" -}}
|
||||
- name: logdir
|
||||
hostPath:
|
||||
path: /logs
|
||||
type: Directory
|
||||
{{- end -}}
|
||||
|
||||
{{- define "ocis.caEnv" -}}
|
||||
- name: OCIS_LOG_FILE
|
||||
value: /logs/ocis.log
|
||||
{{- end -}}
|
||||
@@ -7,7 +7,63 @@ ingress:
|
||||
enabled: true
|
||||
ingressClassName: traefik
|
||||
externalDomain: ocis-server
|
||||
extraResources: []
|
||||
extraResources:
|
||||
- |
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: ocmproviders
|
||||
namespace: {{ template "ocis.namespace" . }}
|
||||
labels:
|
||||
{{- include "ocis.labels" . | nindent 8 }}
|
||||
data:
|
||||
ocmproviders.json: |
|
||||
[
|
||||
{
|
||||
"name": "ocis",
|
||||
"full_name": "ocis server",
|
||||
"organization": "ownCloud",
|
||||
"domain": "ocis-server",
|
||||
"homepage": "https://ocis-server",
|
||||
"services": [
|
||||
{
|
||||
"endpoint": {
|
||||
"type": {
|
||||
"name": "OCM",
|
||||
"description": "ownCloud Open Cloud Mesh API"
|
||||
},
|
||||
"name": "ocis-server - OCM API",
|
||||
"path": "https://ocis-server/ocm/",
|
||||
"is_monitored": true
|
||||
},
|
||||
"api_version": "0.0.1",
|
||||
"host": "https://ocis-server"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "federation ocis",
|
||||
"full_name": "federation ocis server",
|
||||
"organization": "ownCloud",
|
||||
"domain": "federation-ocis-server",
|
||||
"homepage": "https://federation-ocis-server",
|
||||
"services": [
|
||||
{
|
||||
"endpoint": {
|
||||
"type": {
|
||||
"name": "OCM",
|
||||
"description": "federation ownCloud Open Cloud Mesh API"
|
||||
},
|
||||
"name": "federation-ocis-server - OCM API",
|
||||
"path": "https://federation-ocis-server/ocm/",
|
||||
"is_monitored": true
|
||||
},
|
||||
"api_version": "0.0.1",
|
||||
"host": "https://federation-ocis-server"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
logging:
|
||||
level: error
|
||||
@@ -34,7 +90,8 @@ features:
|
||||
policies:
|
||||
enabled: false
|
||||
ocm:
|
||||
enabled: false
|
||||
enabled: true
|
||||
providersConfigRef: "ocmproviders"
|
||||
sharing:
|
||||
passwordPolicies:
|
||||
bannedPasswords:
|
||||
@@ -46,6 +103,43 @@ features:
|
||||
quotas:
|
||||
default: "1000000000"
|
||||
max: "0"
|
||||
appsIntegration:
|
||||
enabled: false
|
||||
wopiIntegration:
|
||||
officeSuites:
|
||||
- name: "Collabora"
|
||||
uri: "https://collabora:9980"
|
||||
wopiSrc: "http://ocis-server:9300"
|
||||
product: "Collabora"
|
||||
enabled: true
|
||||
insecure: true
|
||||
disableProof: true
|
||||
secureViewEnabled: false
|
||||
disableChat: true
|
||||
ingress:
|
||||
enabled: false
|
||||
- name: "FakeOffice"
|
||||
uri: "http://fakeoffice:8080"
|
||||
wopiSrc: "http://ocis-server:9301"
|
||||
product: "FakeOffice"
|
||||
enabled: true
|
||||
insecure: true
|
||||
disableProof: true
|
||||
secureViewEnabled: false
|
||||
disableChat: true
|
||||
ingress:
|
||||
enabled: false
|
||||
- name: "OnlyOffice"
|
||||
uri: "https://onlyoffice"
|
||||
wopiSrc: "http://ocis-server:9302"
|
||||
product: "OnlyOffice"
|
||||
enabled: true
|
||||
insecure: true
|
||||
disableProof: true
|
||||
secureViewEnabled: false
|
||||
disableChat: true
|
||||
ingress:
|
||||
enabled: false
|
||||
|
||||
http:
|
||||
cors:
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
// Usage examples:
|
||||
// go run ./cmd/list-failed-commits --max-commits 20
|
||||
// go run ./cmd/list-failed-commits --max-commits 50 --out failed.json
|
||||
// go run ./cmd/list-failed-commits --github-token $GITHUB_TOKEN --max-commits 100
|
||||
// go run ./cmd/list-failed-commits --repo owncloud/ocis --branch master --max-commits 20
|
||||
// go run ./cmd/list-failed-commits --since 7d --max-commits 50
|
||||
// go run ./cmd/list-failed-commits --since 30d --out failed.json
|
||||
// go run ./cmd/list-failed-commits --since 2026-01-01 --max-commits 100
|
||||
// go run ./cmd/list-failed-commits --since 2026-02-15 --out recent.json
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/ocis/v2/tools/ci-reporter/pkg/droneextractor"
|
||||
"github.com/owncloud/ocis/v2/tools/ci-reporter/pkg/githubextractor"
|
||||
"github.com/owncloud/ocis/v2/tools/ci-reporter/pkg/util"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultRepo = "owncloud/ocis"
|
||||
defaultBranch = "master"
|
||||
requestDelay = 1 * time.Second
|
||||
defaultLimit = 20
|
||||
defaultUnlimited = 999999999
|
||||
)
|
||||
|
||||
type RunConfig struct {
|
||||
Repo string
|
||||
Branch string
|
||||
MaxCommits int
|
||||
SinceRaw string
|
||||
SinceParsed string
|
||||
OutFile string
|
||||
Token string
|
||||
Command string
|
||||
FetchFailedPipelineHistory bool
|
||||
}
|
||||
|
||||
type FailureCount struct {
|
||||
StageName string `json:"stage_name"`
|
||||
StepName string `json:"step_name"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type DateRange struct {
|
||||
StartDate string `json:"start_date"`
|
||||
EndDate string `json:"end_date"`
|
||||
}
|
||||
|
||||
type Raport struct {
|
||||
Args string `json:"args"`
|
||||
Repo string `json:"repo"`
|
||||
Branch string `json:"branch"`
|
||||
DateRange DateRange `json:"date_range"`
|
||||
TotalCommits int `json:"total_commits"`
|
||||
FailedCommits int `json:"failed_commits"`
|
||||
Percentage float64 `json:"percentage"`
|
||||
}
|
||||
|
||||
type RaportMetadata struct {
|
||||
Args string
|
||||
Repo string
|
||||
Branch string
|
||||
DateRange DateRange
|
||||
TotalCommits int
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
Raport *Raport `json:"raport"`
|
||||
Count []FailureCount `json:"count"`
|
||||
Pipelines []FailedCommit `json:"pipelines"`
|
||||
}
|
||||
|
||||
type FailedCommit struct {
|
||||
PR int `json:"pr,omitempty"`
|
||||
SHA string `json:"sha"`
|
||||
Date string `json:"date"`
|
||||
Subject string `json:"subject"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
CombinedState string `json:"combined_state"`
|
||||
FailedContexts []StatusContext `json:"failed_contexts"`
|
||||
PipelineInfo *droneextractor.PipelineInfo `json:"pipeline_info,omitempty"`
|
||||
FailedPipelineHistory []droneextractor.PipelineInfoSummary `json:"failed_pipeline_history,omitempty"`
|
||||
PrPipelineHistory []droneextractor.PipelineInfoSummary `json:"pr_pipeline_history,omitempty"`
|
||||
}
|
||||
|
||||
type StatusContext struct {
|
||||
Context string `json:"context"`
|
||||
State string `json:"state"`
|
||||
TargetURL string `json:"target_url"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
repo := flag.String("repo", defaultRepo, "GitHub repository (owner/repo)")
|
||||
branch := flag.String("branch", defaultBranch, "Branch name")
|
||||
maxCommits := flag.Int("max-commits", 0, "Maximum commits to check (default: 20 if no --since, unlimited if --since set)")
|
||||
since := flag.String("since", "", "Date filter: YYYY-MM-DD, RFC3339 timestamp, or 'Nd' for last N days (e.g., '7d', '30d')")
|
||||
outFile := flag.String("out", "", "Output file path (default: stdout)")
|
||||
githubToken := flag.String("github-token", "", "GitHub token (optional; falls back to env GITHUB_TOKEN)")
|
||||
failedPipelineHistory := flag.Bool("failed_pipeline_history", false, "if set, fetch failed_pipeline_history per commit (extra Drone API calls)")
|
||||
flag.Parse()
|
||||
|
||||
token := strings.TrimSpace(*githubToken)
|
||||
if token == "" {
|
||||
token = strings.TrimSpace(os.Getenv("GITHUB_TOKEN"))
|
||||
}
|
||||
|
||||
if token != "" {
|
||||
fmt.Fprintf(os.Stderr, "Using GitHub token\n")
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "No token provided, unauthenticated, 60 req/hr limit\n")
|
||||
}
|
||||
|
||||
command := strings.Join(os.Args[1:], " ")
|
||||
command = util.RedactGitHubToken(command)
|
||||
|
||||
parsedSince, err := util.ParseSinceFlag(*since)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error parsing --since flag: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Determine final max commits based on git-like UX:
|
||||
// - No flags: default to 20
|
||||
// - --since only: unlimited (all in range)
|
||||
// - --max-commits only: use explicit value
|
||||
// - Both: use explicit value (both filters apply)
|
||||
finalMaxCommits := *maxCommits
|
||||
if finalMaxCommits == 0 {
|
||||
if *since != "" {
|
||||
finalMaxCommits = defaultUnlimited // Unlimited when --since is used
|
||||
} else {
|
||||
finalMaxCommits = defaultLimit // Default for no flags
|
||||
}
|
||||
}
|
||||
|
||||
config := RunConfig{
|
||||
Repo: *repo,
|
||||
Branch: *branch,
|
||||
MaxCommits: finalMaxCommits,
|
||||
SinceRaw: *since,
|
||||
SinceParsed: parsedSince,
|
||||
OutFile: *outFile,
|
||||
Token: token,
|
||||
Command: command,
|
||||
FetchFailedPipelineHistory: *failedPipelineHistory,
|
||||
}
|
||||
|
||||
if err := run(config); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(cfg RunConfig) error {
|
||||
// Configure Transport to prevent stale connection reuse during long pagination
|
||||
transport := &http.Transport{
|
||||
MaxIdleConns: 10,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
DisableKeepAlives: false,
|
||||
MaxIdleConnsPerHost: 2,
|
||||
}
|
||||
client := &http.Client{
|
||||
Timeout: 60 * time.Second, // Increased for long-running pagination
|
||||
Transport: transport,
|
||||
}
|
||||
githubExtractor := githubextractor.NewExtractor(client, cfg.Token)
|
||||
droneExtractor := droneextractor.NewExtractor(client)
|
||||
|
||||
// Build scanning message
|
||||
var scanMsg string
|
||||
if cfg.SinceRaw != "" {
|
||||
scanMsg = fmt.Sprintf("Scanning commits since %s from %s/%s", cfg.SinceRaw, cfg.Repo, cfg.Branch)
|
||||
} else {
|
||||
scanMsg = fmt.Sprintf("Scanning up to %d commits from %s/%s", cfg.MaxCommits, cfg.Repo, cfg.Branch)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "%s\n", scanMsg)
|
||||
commits, err := githubExtractor.GetCommits(cfg.Repo, cfg.Branch, cfg.MaxCommits, cfg.SinceParsed)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetching commits: %w", err)
|
||||
}
|
||||
|
||||
var failedCommits []FailedCommit
|
||||
for _, commit := range commits {
|
||||
status, err := githubExtractor.GetCommitStatus(cfg.Repo, commit.SHA)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "⚠ %s: %v\n", commit.SHA[:7], err)
|
||||
time.Sleep(requestDelay)
|
||||
continue
|
||||
}
|
||||
|
||||
if status.State == "failure" || status.State == "error" {
|
||||
var failedCtxs []StatusContext
|
||||
var pipelineInfo *droneextractor.PipelineInfo
|
||||
|
||||
for _, s := range status.Statuses {
|
||||
if s.State != "success" {
|
||||
// Skip Drone entries - they'll be in pipeline_info instead
|
||||
if droneExtractor.IsDroneURL(s.TargetURL) {
|
||||
info, err := droneExtractor.Extract(s.TargetURL)
|
||||
if err == nil {
|
||||
pipelineInfo = info
|
||||
}
|
||||
// Don't add to failed_contexts to avoid redundancy
|
||||
continue
|
||||
}
|
||||
failedCtxs = append(failedCtxs, toStatusContext(s))
|
||||
}
|
||||
}
|
||||
// TODO: Refactor redundant field assignment - prPipelineHistory always assigned, failedPipelineHistory conditional
|
||||
var failedPipelineHistory []droneextractor.PipelineInfoSummary
|
||||
var prPipelineHistory []droneextractor.PipelineInfoSummary
|
||||
var prNumber int
|
||||
var headRef string
|
||||
|
||||
// Get PR for this commit (master commit -> PR ID -> PR branch)
|
||||
prs, err := githubExtractor.GetPRsForCommit(cfg.Repo, commit.SHA)
|
||||
if err == nil && len(prs) > 0 {
|
||||
prNumber = prs[0].Number
|
||||
headRef = prs[0].Head.Ref
|
||||
|
||||
// Get failed builds by PR branch (black box: all logic in droneextractor)
|
||||
failedBuilds, err := droneExtractor.GetFailedBuildsByPRBranch(droneextractor.BaseURL, cfg.Repo, headRef)
|
||||
if err == nil {
|
||||
prPipelineHistory = failedBuilds
|
||||
if cfg.FetchFailedPipelineHistory {
|
||||
failedPipelineHistory = failedBuilds
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize empty slice if flag is set but no PR/builds found
|
||||
if cfg.FetchFailedPipelineHistory && failedPipelineHistory == nil {
|
||||
failedPipelineHistory = []droneextractor.PipelineInfoSummary{}
|
||||
}
|
||||
|
||||
subject := util.ExtractSubject(commit.Commit.Message)
|
||||
failedCommits = append(failedCommits, FailedCommit{
|
||||
PR: prNumber,
|
||||
SHA: commit.SHA,
|
||||
Date: commit.Commit.Author.Date,
|
||||
Subject: subject,
|
||||
HTMLURL: commit.HTMLURL,
|
||||
CombinedState: status.State,
|
||||
FailedContexts: failedCtxs,
|
||||
PipelineInfo: pipelineInfo,
|
||||
FailedPipelineHistory: failedPipelineHistory,
|
||||
PrPipelineHistory: prPipelineHistory,
|
||||
})
|
||||
|
||||
// Single line output: ✗ sha subject -> PR #num (branch: name)
|
||||
if prNumber > 0 && headRef != "" {
|
||||
fmt.Fprintf(os.Stderr, "✗ %s %s -> PR #%d (branch: %s)\n", commit.SHA[:7], subject, prNumber, headRef)
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "✗ %s %s\n", commit.SHA[:7], subject)
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(requestDelay)
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "\nResult: %d failed / %d total\n", len(failedCommits), len(commits))
|
||||
|
||||
var minDate, maxDate string
|
||||
for _, c := range commits {
|
||||
date := c.Commit.Author.Date
|
||||
if minDate == "" || date < minDate {
|
||||
minDate = date
|
||||
}
|
||||
if maxDate == "" || date > maxDate {
|
||||
maxDate = date
|
||||
}
|
||||
}
|
||||
|
||||
metadata := RaportMetadata{
|
||||
Args: cfg.Command,
|
||||
Repo: cfg.Repo,
|
||||
Branch: cfg.Branch,
|
||||
DateRange: DateRange{StartDate: minDate, EndDate: maxDate},
|
||||
TotalCommits: len(commits),
|
||||
}
|
||||
|
||||
report := generateReport(failedCommits, metadata)
|
||||
|
||||
var w io.Writer = os.Stdout
|
||||
if cfg.OutFile != "" {
|
||||
f, err := os.Create(cfg.OutFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating output file: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
w = f
|
||||
fmt.Fprintf(os.Stderr, "Writing JSON to %s...\n", cfg.OutFile)
|
||||
}
|
||||
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(report); err != nil {
|
||||
return fmt.Errorf("encoding JSON: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func toStatusContext(ctx githubextractor.StatusContext) StatusContext {
|
||||
return StatusContext{
|
||||
Context: ctx.Context,
|
||||
State: ctx.State,
|
||||
TargetURL: ctx.TargetURL,
|
||||
Description: ctx.Description,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func generateReport(failedCommits []FailedCommit, metadata RaportMetadata) *Report {
|
||||
countMap := make(map[string]int)
|
||||
|
||||
for _, commit := range failedCommits {
|
||||
if commit.PipelineInfo == nil {
|
||||
continue
|
||||
}
|
||||
for _, stage := range commit.PipelineInfo.PipelineStages {
|
||||
for _, step := range stage.Steps {
|
||||
if step.Status == "failure" {
|
||||
key := stage.StageName + "/" + step.StepName
|
||||
countMap[key]++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var counts []FailureCount
|
||||
for key, count := range countMap {
|
||||
parts := strings.Split(key, "/")
|
||||
if len(parts) >= 2 {
|
||||
counts = append(counts, FailureCount{
|
||||
StageName: parts[0],
|
||||
StepName: strings.Join(parts[1:], "/"),
|
||||
Count: count,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
sort.Slice(counts, func(i, j int) bool {
|
||||
return counts[i].Count > counts[j].Count
|
||||
})
|
||||
|
||||
percentage := 0.0
|
||||
if metadata.TotalCommits > 0 {
|
||||
percentage = float64(len(failedCommits)) / float64(metadata.TotalCommits) * 100.0
|
||||
}
|
||||
|
||||
raport := &Raport{
|
||||
Args: metadata.Args,
|
||||
Repo: metadata.Repo,
|
||||
Branch: metadata.Branch,
|
||||
DateRange: metadata.DateRange,
|
||||
TotalCommits: metadata.TotalCommits,
|
||||
FailedCommits: len(failedCommits),
|
||||
Percentage: percentage,
|
||||
}
|
||||
|
||||
return &Report{
|
||||
Raport: raport,
|
||||
Count: counts,
|
||||
Pipelines: failedCommits,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
module github.com/owncloud/ocis/v2/tools/ci-reporter
|
||||
|
||||
go 1.24.0
|
||||
|
||||
require golang.org/x/net v0.50.0 // indirect
|
||||
@@ -0,0 +1,2 @@
|
||||
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
|
||||
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
|
||||
@@ -0,0 +1,631 @@
|
||||
package droneextractor
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
const (
|
||||
// BaseURL is the default Drone instance URL
|
||||
BaseURL = "https://drone.owncloud.com"
|
||||
)
|
||||
|
||||
type Extractor struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewExtractor(client *http.Client) *Extractor {
|
||||
return &Extractor{client: client}
|
||||
}
|
||||
|
||||
// IsDroneURL checks if a URL is a Drone CI URL
|
||||
func (e *Extractor) IsDroneURL(url string) bool {
|
||||
return strings.Contains(url, "drone.owncloud.com")
|
||||
}
|
||||
|
||||
func (e *Extractor) Extract(buildURL string) (*PipelineInfo, error) {
|
||||
apiURL := e.buildURLToAPIURL(buildURL)
|
||||
if apiURL == "" {
|
||||
return nil, fmt.Errorf("invalid build URL: %s", buildURL)
|
||||
}
|
||||
|
||||
buildData, err := e.fetchDroneAPI(apiURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching Drone API: %w", err)
|
||||
}
|
||||
|
||||
stages := e.parseStagesFromAPI(buildData, buildURL)
|
||||
|
||||
var durationMinutes float64
|
||||
if buildData.Finished > 0 && buildData.Started > 0 {
|
||||
durationMinutes = float64(buildData.Finished-buildData.Started) / 60.0
|
||||
}
|
||||
|
||||
return &PipelineInfo{
|
||||
BuildURL: buildURL,
|
||||
Started: buildData.Started,
|
||||
Finished: buildData.Finished,
|
||||
DurationMinutes: durationMinutes,
|
||||
PipelineStages: stages,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (e *Extractor) buildURLToAPIURL(buildURL string) string {
|
||||
if !strings.Contains(buildURL, "drone.owncloud.com") {
|
||||
return ""
|
||||
}
|
||||
parts := strings.Split(buildURL, "/")
|
||||
if len(parts) < 5 {
|
||||
return ""
|
||||
}
|
||||
repo := parts[3] + "/" + parts[4]
|
||||
buildNum := parts[5]
|
||||
return fmt.Sprintf("https://drone.owncloud.com/api/repos/%s/builds/%s", repo, buildNum)
|
||||
}
|
||||
|
||||
func (e *Extractor) fetchDroneAPI(url string) (*droneBuildResponse, error) {
|
||||
resp, err := e.client.Get(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var buildData droneBuildResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&buildData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &buildData, nil
|
||||
}
|
||||
|
||||
func (e *Extractor) parseStagesFromAPI(buildData *droneBuildResponse, buildURL string) []PipelineStage {
|
||||
var stages []PipelineStage
|
||||
|
||||
for _, apiStage := range buildData.Stages {
|
||||
normalizedStatus := e.normalizeStatus(apiStage.Status)
|
||||
if normalizedStatus == "success" || normalizedStatus == "skipped" {
|
||||
continue
|
||||
}
|
||||
|
||||
stage := PipelineStage{
|
||||
StageNumber: apiStage.Number,
|
||||
StageName: apiStage.Name,
|
||||
Status: normalizedStatus,
|
||||
Steps: []PipelineStep{},
|
||||
}
|
||||
|
||||
for _, apiStep := range apiStage.Steps {
|
||||
normalizedStepStatus := e.normalizeStatus(apiStep.Status)
|
||||
if normalizedStepStatus == "skipped" {
|
||||
continue
|
||||
}
|
||||
stepURL := fmt.Sprintf("%s/%d/%d", buildURL, apiStage.Number, apiStep.Number)
|
||||
step := PipelineStep{
|
||||
StepNumber: apiStep.Number,
|
||||
StepName: apiStep.Name,
|
||||
Status: normalizedStepStatus,
|
||||
URL: stepURL,
|
||||
}
|
||||
|
||||
if normalizedStepStatus == "failure" {
|
||||
logs, err := e.fetchStepLogs(stepURL, buildURL, apiStage.Number, apiStep.Number)
|
||||
if err == nil {
|
||||
lines := strings.Split(logs, "\n")
|
||||
if len(lines) > 500 && (strings.Contains(logs, "--- Failed scenarios:") || strings.Contains(logs, "Scenario:")) {
|
||||
logs = e.extractBehatFailures(logs)
|
||||
}
|
||||
step.Logs = logs
|
||||
}
|
||||
}
|
||||
|
||||
stage.Steps = append(stage.Steps, step)
|
||||
}
|
||||
|
||||
stages = append(stages, stage)
|
||||
}
|
||||
|
||||
return stages
|
||||
}
|
||||
|
||||
func (e *Extractor) normalizeStatus(status string) string {
|
||||
switch strings.ToLower(status) {
|
||||
case "success", "passed":
|
||||
return "success"
|
||||
case "failure", "failed", "error":
|
||||
return "failure"
|
||||
case "running", "pending", "started":
|
||||
return "running"
|
||||
case "skipped":
|
||||
return "skipped"
|
||||
default:
|
||||
return status
|
||||
}
|
||||
}
|
||||
|
||||
// droneBuildResponse matches the structure returned by Drone API:
|
||||
// GET /api/repos/{owner}/{repo}/builds/{buildNumber}
|
||||
// Verified against: https://drone.owncloud.com/api/repos/owncloud/ocis/builds/51629
|
||||
type droneBuildResponse struct {
|
||||
Started int64 `json:"started"`
|
||||
Finished int64 `json:"finished"`
|
||||
Stages []droneStage `json:"stages"`
|
||||
}
|
||||
|
||||
type droneStage struct {
|
||||
Number int `json:"number"` // Stage number (1, 2, 3, ...)
|
||||
Name string `json:"name"` // Stage name (e.g., "API-wopi", "coding-standard-php8.4")
|
||||
Status string `json:"status"` // "success", "failure", "running", etc.
|
||||
Steps []droneStep `json:"steps"` // Array of steps in this stage
|
||||
}
|
||||
|
||||
type droneStep struct {
|
||||
Number int `json:"number"` // Step number within stage
|
||||
Name string `json:"name"` // Step name (e.g., "clone", "test-acceptance-api")
|
||||
Status string `json:"status"` // "success", "failure", "skipped", etc.
|
||||
}
|
||||
|
||||
type droneLogEntry struct {
|
||||
Pos int `json:"pos"`
|
||||
Out string `json:"out"`
|
||||
Time int64 `json:"time"`
|
||||
}
|
||||
|
||||
type BuildInfo struct {
|
||||
BuildNumber int `json:"build_number"`
|
||||
Status string `json:"status"` // "success", "failure", "error"
|
||||
Started int64 `json:"started"`
|
||||
Finished int64 `json:"finished"`
|
||||
CommitSHA string `json:"commit_sha"`
|
||||
}
|
||||
|
||||
type droneBuildListItem struct {
|
||||
Number int `json:"number"`
|
||||
Status string `json:"status"`
|
||||
Event string `json:"event"` // "pull_request", "push", etc.
|
||||
Source string `json:"source"` // Source branch for PR builds
|
||||
Target string `json:"target"` // Target branch for PR builds
|
||||
After string `json:"after"` // Commit SHA
|
||||
Started int64 `json:"started"`
|
||||
Finished int64 `json:"finished"`
|
||||
}
|
||||
|
||||
func (e *Extractor) fetchStepLogs(stepURL, buildURL string, stageNum, stepNum int) (string, error) {
|
||||
apiLogsURL := e.buildLogsAPIURL(buildURL, stageNum, stepNum)
|
||||
if apiLogsURL != "" {
|
||||
logs, err := e.fetchLogsFromAPI(apiLogsURL)
|
||||
if err == nil {
|
||||
return logs, nil
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), "401") && !strings.Contains(err.Error(), "403") {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
return e.fetchLogsFromHTML(stepURL)
|
||||
}
|
||||
|
||||
func (e *Extractor) buildLogsAPIURL(buildURL string, stageNum, stepNum int) string {
|
||||
if !strings.Contains(buildURL, "drone.owncloud.com") {
|
||||
return ""
|
||||
}
|
||||
parts := strings.Split(buildURL, "/")
|
||||
if len(parts) < 5 {
|
||||
return ""
|
||||
}
|
||||
repo := parts[3] + "/" + parts[4]
|
||||
buildNum := parts[5]
|
||||
return fmt.Sprintf("https://drone.owncloud.com/api/repos/%s/builds/%s/logs/%d/%d", repo, buildNum, stageNum, stepNum)
|
||||
}
|
||||
|
||||
func (e *Extractor) fetchLogsFromAPI(apiURL string) (string, error) {
|
||||
resp, err := e.client.Get(apiURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var logEntries []droneLogEntry
|
||||
if err := json.NewDecoder(resp.Body).Decode(&logEntries); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var logs strings.Builder
|
||||
for _, entry := range logEntries {
|
||||
logs.WriteString(entry.Out)
|
||||
}
|
||||
|
||||
return logs.String(), nil
|
||||
}
|
||||
|
||||
func (e *Extractor) fetchLogsFromHTML(stepURL string) (string, error) {
|
||||
resp, err := e.client.Get(stepURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return e.extractLogsFromHTML(string(body))
|
||||
}
|
||||
|
||||
func (e *Extractor) extractLogsFromHTML(htmlContent string) (string, error) {
|
||||
doc, err := html.Parse(strings.NewReader(htmlContent))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var logs strings.Builder
|
||||
var extractText func(*html.Node)
|
||||
extractText = func(n *html.Node) {
|
||||
if n.Type == html.ElementNode {
|
||||
if n.Data == "pre" || n.Data == "code" {
|
||||
text := e.getTextContent(n)
|
||||
if text != "" {
|
||||
logs.WriteString(text)
|
||||
logs.WriteString("\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
extractText(c)
|
||||
}
|
||||
}
|
||||
|
||||
extractText(doc)
|
||||
return strings.TrimSpace(logs.String()), nil
|
||||
}
|
||||
|
||||
func (e *Extractor) getTextContent(n *html.Node) string {
|
||||
var text strings.Builder
|
||||
var collectText func(*html.Node)
|
||||
collectText = func(n *html.Node) {
|
||||
if n.Type == html.TextNode {
|
||||
text.WriteString(n.Data)
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
collectText(c)
|
||||
}
|
||||
}
|
||||
collectText(n)
|
||||
return text.String()
|
||||
}
|
||||
|
||||
func (e *Extractor) extractBehatFailures(logs string) string {
|
||||
var result strings.Builder
|
||||
|
||||
// ANSI red code pattern
|
||||
redCodePattern := regexp.MustCompile(`\x1b\[31m|\033\[31m|\[31m`)
|
||||
ansiStripPattern := regexp.MustCompile(`\x1b\[[0-9;]*m|\033\[[0-9;]*m`)
|
||||
|
||||
// Split by Scenario: or Scenario Outline: (case-insensitive)
|
||||
// Use regex to find all scenario starts while preserving the marker
|
||||
scenarioPattern := regexp.MustCompile(`(?i)(Scenario(?:\s+Outline)?:\s*)`)
|
||||
matches := scenarioPattern.FindAllStringIndex(logs, -1)
|
||||
|
||||
if len(matches) == 0 {
|
||||
// No scenarios found, try to extract just "--- Failed scenarios:" section
|
||||
return e.extractFailedScenariosSection(logs, ansiStripPattern)
|
||||
}
|
||||
|
||||
// Extract each scenario section
|
||||
for i, match := range matches {
|
||||
start := match[0]
|
||||
end := len(logs)
|
||||
if i+1 < len(matches) {
|
||||
end = matches[i+1][0]
|
||||
}
|
||||
|
||||
scenarioSection := logs[start:end]
|
||||
|
||||
// Check if this section contains ANSI red codes
|
||||
if redCodePattern.MatchString(scenarioSection) {
|
||||
// Strip ANSI codes and add to result
|
||||
cleaned := ansiStripPattern.ReplaceAllString(scenarioSection, "")
|
||||
if result.Len() > 0 {
|
||||
result.WriteString("\n\n")
|
||||
}
|
||||
result.WriteString(cleaned)
|
||||
}
|
||||
}
|
||||
|
||||
// Extract "--- Failed scenarios:" section
|
||||
failedScenariosSection := e.extractFailedScenariosSection(logs, ansiStripPattern)
|
||||
if failedScenariosSection != "" {
|
||||
if result.Len() > 0 {
|
||||
result.WriteString("\n\n")
|
||||
}
|
||||
result.WriteString(failedScenariosSection)
|
||||
}
|
||||
|
||||
extracted := strings.TrimSpace(result.String())
|
||||
if extracted == "" {
|
||||
// If extraction failed, return original logs
|
||||
return logs
|
||||
}
|
||||
|
||||
return extracted
|
||||
}
|
||||
|
||||
func (e *Extractor) extractFailedScenariosSection(logs string, ansiStripPattern *regexp.Regexp) string {
|
||||
failedScenariosMarker := "--- Failed scenarios:"
|
||||
if idx := strings.Index(logs, failedScenariosMarker); idx != -1 {
|
||||
failedScenariosSection := logs[idx:]
|
||||
cleaned := ansiStripPattern.ReplaceAllString(failedScenariosSection, "")
|
||||
return cleaned
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetBuildsByCommitSHA queries Drone API for all builds matching a specific commit SHA
|
||||
func (e *Extractor) GetBuildsByCommitSHA(baseURL, repo, commitSHA string) ([]BuildInfo, error) {
|
||||
var allBuilds []BuildInfo
|
||||
page := 1
|
||||
maxPages := 200 // Safety limit (25 items per page = 5000 builds max)
|
||||
|
||||
for page <= maxPages {
|
||||
url := fmt.Sprintf("%s/api/repos/%s/builds?page=%d", baseURL, repo, page)
|
||||
resp, err := e.client.Get(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching build list: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var buildList []droneBuildListItem
|
||||
if err := json.NewDecoder(resp.Body).Decode(&buildList); err != nil {
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("decoding build list: %w", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
// Stop when we get an empty page
|
||||
if len(buildList) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
// Filter builds by commit SHA
|
||||
for _, item := range buildList {
|
||||
if item.After == commitSHA {
|
||||
allBuilds = append(allBuilds, BuildInfo{
|
||||
BuildNumber: item.Number,
|
||||
Status: item.Status,
|
||||
Started: item.Started,
|
||||
Finished: item.Finished,
|
||||
CommitSHA: item.After,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
page++
|
||||
}
|
||||
|
||||
// Sort by build number (ascending = chronological)
|
||||
sort.Slice(allBuilds, func(i, j int) bool {
|
||||
return allBuilds[i].BuildNumber < allBuilds[j].BuildNumber
|
||||
})
|
||||
|
||||
return allBuilds, nil
|
||||
}
|
||||
|
||||
// GetBuildsByPRBranch queries Drone API for all builds matching PR event and source branch
|
||||
func (e *Extractor) GetBuildsByPRBranch(baseURL, repo, sourceBranch string) ([]BuildInfo, error) {
|
||||
var allBuilds []BuildInfo
|
||||
page := 1
|
||||
maxPages := 200 // Safety limit (25 items per page = 5000 builds max)
|
||||
|
||||
for page <= maxPages {
|
||||
url := fmt.Sprintf("%s/api/repos/%s/builds?page=%d", baseURL, repo, page)
|
||||
resp, err := e.client.Get(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching build list: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var buildList []droneBuildListItem
|
||||
if err := json.NewDecoder(resp.Body).Decode(&buildList); err != nil {
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("decoding build list: %w", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
// Stop when we get an empty page
|
||||
if len(buildList) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
// Filter builds by event="pull_request" and source branch
|
||||
for _, item := range buildList {
|
||||
if item.Event == "pull_request" && item.Source == sourceBranch {
|
||||
allBuilds = append(allBuilds, BuildInfo{
|
||||
BuildNumber: item.Number,
|
||||
Status: item.Status,
|
||||
Started: item.Started,
|
||||
Finished: item.Finished,
|
||||
CommitSHA: item.After,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
page++
|
||||
}
|
||||
|
||||
// Sort by build number (ascending = chronological)
|
||||
sort.Slice(allBuilds, func(i, j int) bool {
|
||||
return allBuilds[i].BuildNumber < allBuilds[j].BuildNumber
|
||||
})
|
||||
|
||||
return allBuilds, nil
|
||||
}
|
||||
|
||||
// GetBuildsByPushBranch queries Drone API for all builds matching push/cron events to a specific branch (e.g., master).
|
||||
// This is specifically for merged commits to main branches, not PR builds.
|
||||
// It includes both "push" events (actual merges) and "cron" events (scheduled/nightly builds).
|
||||
func (e *Extractor) GetBuildsByPushBranch(baseURL, repo, targetBranch string) ([]BuildInfo, error) {
|
||||
var allBuilds []BuildInfo
|
||||
page := 1
|
||||
maxPages := 200 // Safety limit (25 items per page = 5000 builds max)
|
||||
|
||||
for page <= maxPages {
|
||||
url := fmt.Sprintf("%s/api/repos/%s/builds?page=%d", baseURL, repo, page)
|
||||
resp, err := e.client.Get(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching build list: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var buildList []droneBuildListItem
|
||||
if err := json.NewDecoder(resp.Body).Decode(&buildList); err != nil {
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("decoding build list: %w", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
// Stop when we get an empty page
|
||||
if len(buildList) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
// Filter builds by event="push" or event="cron" and target branch
|
||||
// "push" = actual merges to branch
|
||||
// "cron" = scheduled/nightly builds running on the branch
|
||||
for _, item := range buildList {
|
||||
if (item.Event == "push" || item.Event == "cron") && item.Target == targetBranch {
|
||||
allBuilds = append(allBuilds, BuildInfo{
|
||||
BuildNumber: item.Number,
|
||||
Status: item.Status,
|
||||
Started: item.Started,
|
||||
Finished: item.Finished,
|
||||
CommitSHA: item.After,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
page++
|
||||
}
|
||||
|
||||
// Sort by build number (ascending = chronological)
|
||||
sort.Slice(allBuilds, func(i, j int) bool {
|
||||
return allBuilds[i].BuildNumber < allBuilds[j].BuildNumber
|
||||
})
|
||||
|
||||
return allBuilds, nil
|
||||
}
|
||||
|
||||
// extractBaseURL extracts the base URL (e.g., "https://drone.owncloud.com") from a build URL
|
||||
func extractBaseURL(buildURL string) string {
|
||||
if !strings.Contains(buildURL, "://") {
|
||||
return ""
|
||||
}
|
||||
parts := strings.Split(buildURL, "/")
|
||||
if len(parts) >= 3 {
|
||||
return parts[0] + "//" + parts[2]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// BuildInfoToPipelineSummary converts a BuildInfo to PipelineInfoSummary
|
||||
func BuildInfoToPipelineSummary(build BuildInfo, baseURL, repo string) PipelineInfoSummary {
|
||||
var durationMinutes float64
|
||||
if build.Finished > 0 && build.Started > 0 {
|
||||
durationMinutes = float64(build.Finished-build.Started) / 60.0
|
||||
}
|
||||
|
||||
// URL format: https://drone.owncloud.com/owncloud/ocis/{buildNumber}
|
||||
// repo format: "owncloud/ocis"
|
||||
buildURL := fmt.Sprintf("%s/%s/%d", baseURL, repo, build.BuildNumber)
|
||||
|
||||
return PipelineInfoSummary{
|
||||
BuildURL: buildURL,
|
||||
Started: build.Started,
|
||||
Finished: build.Finished,
|
||||
DurationMinutes: durationMinutes,
|
||||
Status: build.Status,
|
||||
}
|
||||
}
|
||||
|
||||
// BuildInfoToPipelineSummaryWithStages converts a BuildInfo to PipelineInfoSummary with failed stages
|
||||
// by fetching full pipeline details from the build URL
|
||||
func (e *Extractor) BuildInfoToPipelineSummaryWithStages(build BuildInfo, baseURL, repo string) PipelineInfoSummary {
|
||||
summary := BuildInfoToPipelineSummary(build, baseURL, repo)
|
||||
|
||||
// Fetch full pipeline info to extract failed stages
|
||||
pipelineInfo, err := e.Extract(summary.BuildURL)
|
||||
if err == nil && pipelineInfo != nil {
|
||||
var failedStages []FailedStage
|
||||
for _, stage := range pipelineInfo.PipelineStages {
|
||||
if stage.Status == "failure" || stage.Status == "error" {
|
||||
failedStages = append(failedStages, FailedStage{
|
||||
StageNumber: stage.StageNumber,
|
||||
StageName: stage.StageName,
|
||||
Status: stage.Status,
|
||||
})
|
||||
}
|
||||
}
|
||||
summary.FailedStages = failedStages
|
||||
}
|
||||
|
||||
return summary
|
||||
}
|
||||
|
||||
// IsFailedBuild checks if a build status indicates failure
|
||||
func IsFailedBuild(status string) bool {
|
||||
normalized := strings.ToLower(status)
|
||||
return normalized == "failure" || normalized == "failed" || normalized == "error"
|
||||
}
|
||||
|
||||
// GetFailedBuildsByPRBranch returns failed builds for a PR branch with pipeline summaries
|
||||
func (e *Extractor) GetFailedBuildsByPRBranch(baseURL, repo, sourceBranch string) ([]PipelineInfoSummary, error) {
|
||||
builds, err := e.GetBuildsByPRBranch(baseURL, repo, sourceBranch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var failedSummaries []PipelineInfoSummary
|
||||
for _, build := range builds {
|
||||
if IsFailedBuild(build.Status) {
|
||||
summary := e.BuildInfoToPipelineSummaryWithStages(build, baseURL, repo)
|
||||
failedSummaries = append(failedSummaries, summary)
|
||||
// Rate limiting delay for API calls in BuildInfoToPipelineSummaryWithStages
|
||||
}
|
||||
}
|
||||
|
||||
return failedSummaries, nil
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package droneextractor
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/ocis/v2/tools/ci-reporter/pkg/githubextractor"
|
||||
)
|
||||
|
||||
const requestDelay = 1 * time.Second
|
||||
|
||||
// FetchPRBuilds fetches all Drone builds for a PR by querying:
|
||||
// 1. Builds by PR branch (handles force-pushes)
|
||||
// 2. Builds by individual commit SHAs (fallback for merged/deleted branches)
|
||||
//
|
||||
// Returns a map of commit SHA -> builds
|
||||
func FetchPRBuilds(
|
||||
extractor *Extractor,
|
||||
baseURL string,
|
||||
repo string,
|
||||
prBranch string,
|
||||
commits []githubextractor.PRCommit,
|
||||
logWriter io.Writer,
|
||||
) (map[string][]BuildInfo, error) {
|
||||
buildsByCommit := make(map[string][]BuildInfo)
|
||||
|
||||
// Query builds by PR branch (handles force-pushes)
|
||||
if logWriter != nil {
|
||||
fmt.Fprintf(logWriter, "Fetching Drone builds for PR (by event and branch)...\n")
|
||||
}
|
||||
prBuilds, err := extractor.GetBuildsByPRBranch(baseURL, repo, prBranch)
|
||||
if err != nil {
|
||||
if logWriter != nil {
|
||||
fmt.Fprintf(logWriter, "⚠ Failed to get builds by branch: %v\n", err)
|
||||
}
|
||||
} else {
|
||||
if logWriter != nil {
|
||||
fmt.Fprintf(logWriter, "Found %d builds for PR branch %s\n", len(prBuilds), prBranch)
|
||||
}
|
||||
// Group builds by commit SHA
|
||||
for _, build := range prBuilds {
|
||||
buildsByCommit[build.CommitSHA] = append(buildsByCommit[build.CommitSHA], build)
|
||||
}
|
||||
}
|
||||
|
||||
// Also query by current commit SHAs (for completeness)
|
||||
if logWriter != nil {
|
||||
fmt.Fprintf(logWriter, "Fetching Drone builds for current commits...\n")
|
||||
}
|
||||
for i, commit := range commits {
|
||||
if _, exists := buildsByCommit[commit.SHA]; exists {
|
||||
if logWriter != nil {
|
||||
fmt.Fprintf(logWriter, " [%d/%d] %s: already found via PR query\n", i+1, len(commits), commit.SHA[:7])
|
||||
}
|
||||
continue
|
||||
}
|
||||
if logWriter != nil {
|
||||
fmt.Fprintf(logWriter, " [%d/%d] Fetching builds for %s...\n", i+1, len(commits), commit.SHA[:7])
|
||||
}
|
||||
builds, err := extractor.GetBuildsByCommitSHA(baseURL, repo, commit.SHA)
|
||||
if err != nil {
|
||||
if logWriter != nil {
|
||||
fmt.Fprintf(logWriter, " ⚠ Failed to get builds: %v\n", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(builds) > 0 {
|
||||
buildsByCommit[commit.SHA] = append(buildsByCommit[commit.SHA], builds...)
|
||||
if logWriter != nil {
|
||||
fmt.Fprintf(logWriter, " Found %d builds\n", len(builds))
|
||||
}
|
||||
}
|
||||
time.Sleep(requestDelay)
|
||||
}
|
||||
|
||||
return buildsByCommit, nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package droneextractor
|
||||
|
||||
type PipelineInfo struct {
|
||||
BuildURL string `json:"build_url"`
|
||||
Started int64 `json:"started,omitempty"` // Unix timestamp
|
||||
Finished int64 `json:"finished,omitempty"` // Unix timestamp
|
||||
DurationMinutes float64 `json:"duration_minutes,omitempty"` // Calculated: (finished - started) / 60
|
||||
PipelineStages []PipelineStage `json:"pipeline_stages"`
|
||||
}
|
||||
|
||||
type PipelineStage struct {
|
||||
StageNumber int `json:"stage_number"`
|
||||
StageName string `json:"stage_name,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Steps []PipelineStep `json:"steps"`
|
||||
}
|
||||
|
||||
type PipelineStep struct {
|
||||
StepNumber int `json:"step_number"`
|
||||
StepName string `json:"step_name"`
|
||||
Status string `json:"status"` // "success", "failure", "error", "running", etc.
|
||||
URL string `json:"url,omitempty"`
|
||||
Logs string `json:"logs,omitempty"` // Console logs content
|
||||
}
|
||||
|
||||
type PipelineInfoSummary struct {
|
||||
BuildURL string `json:"build_url"`
|
||||
Started int64 `json:"started,omitempty"`
|
||||
Finished int64 `json:"finished,omitempty"`
|
||||
DurationMinutes float64 `json:"duration_minutes,omitempty"`
|
||||
Status string `json:"status,omitempty"` // Overall build status
|
||||
FailedStages []FailedStage `json:"failed_stages,omitempty"`
|
||||
}
|
||||
|
||||
type FailedStage struct {
|
||||
StageNumber int `json:"stage_number"`
|
||||
StageName string `json:"stage_name"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
package githubextractor
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
apiBase = "https://api.github.com"
|
||||
requestDelay = 1 * time.Second
|
||||
retryDelay = 2 * time.Second
|
||||
maxRetries = 3
|
||||
)
|
||||
|
||||
type Extractor struct {
|
||||
client *http.Client
|
||||
token string
|
||||
}
|
||||
|
||||
func NewExtractor(client *http.Client, token string) *Extractor {
|
||||
return &Extractor{
|
||||
client: client,
|
||||
token: token,
|
||||
}
|
||||
}
|
||||
|
||||
type PRInfo struct {
|
||||
Number int `json:"number"`
|
||||
Head struct {
|
||||
Ref string `json:"ref"`
|
||||
SHA string `json:"sha"`
|
||||
} `json:"head"`
|
||||
Base struct {
|
||||
Ref string `json:"ref"`
|
||||
} `json:"base"`
|
||||
}
|
||||
|
||||
type PRCommit struct {
|
||||
SHA string `json:"sha"`
|
||||
Commit struct {
|
||||
Author struct {
|
||||
Date string `json:"date"`
|
||||
} `json:"author"`
|
||||
Message string `json:"message"`
|
||||
} `json:"commit"`
|
||||
}
|
||||
|
||||
type CommitListItem struct {
|
||||
SHA string `json:"sha"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
Commit struct {
|
||||
Author struct {
|
||||
Date string `json:"date"`
|
||||
} `json:"author"`
|
||||
Message string `json:"message"`
|
||||
} `json:"commit"`
|
||||
}
|
||||
|
||||
type CombinedStatus struct {
|
||||
State string `json:"state"`
|
||||
Statuses []StatusContext `json:"statuses"`
|
||||
}
|
||||
|
||||
type StatusContext struct {
|
||||
Context string `json:"context"`
|
||||
State string `json:"state"`
|
||||
TargetURL string `json:"target_url"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
func (e *Extractor) GetPRInfo(repo string, prNumber int) (*PRInfo, error) {
|
||||
url := fmt.Sprintf("%s/repos/%s/pulls/%d", apiBase, repo, prNumber)
|
||||
var prInfo PRInfo
|
||||
return &prInfo, e.get(url, &prInfo)
|
||||
}
|
||||
|
||||
func (e *Extractor) GetPRCommits(repo string, prNumber int) ([]PRCommit, error) {
|
||||
url := fmt.Sprintf("%s/repos/%s/pulls/%d/commits", apiBase, repo, prNumber)
|
||||
var commits []PRCommit
|
||||
return commits, e.get(url, &commits)
|
||||
}
|
||||
|
||||
func (e *Extractor) GetCommits(repo, branch string, maxCommits int, since string) ([]CommitListItem, error) {
|
||||
var commits []CommitListItem
|
||||
page := 1
|
||||
|
||||
for len(commits) < maxCommits {
|
||||
url := fmt.Sprintf("%s/repos/%s/commits?sha=%s&per_page=100&page=%d", apiBase, repo, branch, page)
|
||||
if since != "" {
|
||||
url += "&since=" + since
|
||||
}
|
||||
|
||||
resp, err := e.request(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("API error %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var pageCommits []CommitListItem
|
||||
if err := json.NewDecoder(resp.Body).Decode(&pageCommits); err != nil {
|
||||
resp.Body.Close()
|
||||
return nil, err
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if len(pageCommits) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
commits = append(commits, pageCommits...)
|
||||
if len(commits) >= maxCommits {
|
||||
commits = commits[:maxCommits]
|
||||
break
|
||||
}
|
||||
|
||||
page++
|
||||
time.Sleep(requestDelay)
|
||||
}
|
||||
|
||||
return commits, nil
|
||||
}
|
||||
|
||||
func (e *Extractor) GetCommitStatus(repo, sha string) (*CombinedStatus, error) {
|
||||
url := fmt.Sprintf("%s/repos/%s/commits/%s/status", apiBase, repo, sha)
|
||||
var status CombinedStatus
|
||||
return &status, e.get(url, &status)
|
||||
}
|
||||
|
||||
// GetPRsForCommit returns PRs associated with a commit (e.g. merged PR that introduced the commit).
|
||||
// See https://docs.github.com/en/rest/commits/commits#list-pull-requests-associated-with-a-commit
|
||||
func (e *Extractor) GetPRsForCommit(repo, commitSHA string) ([]PRInfo, error) {
|
||||
url := fmt.Sprintf("%s/repos/%s/commits/%s/pulls", apiBase, repo, commitSHA)
|
||||
var prs []PRInfo
|
||||
return prs, e.get(url, &prs)
|
||||
}
|
||||
|
||||
func isRetryableNetworkError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
s := strings.ToLower(err.Error())
|
||||
return strings.Contains(s, "broken pipe") ||
|
||||
strings.Contains(s, "connection reset") ||
|
||||
strings.Contains(s, "connection refused") ||
|
||||
strings.Contains(s, "EOF")
|
||||
}
|
||||
|
||||
// get makes an HTTP GET request, decodes JSON response, and handles rate limiting
|
||||
func (e *Extractor) get(url string, result any) error {
|
||||
resp, err := e.request(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("API error %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
time.Sleep(requestDelay)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Extractor) request(url string) (*http.Response, error) {
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < maxRetries; attempt++ {
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/vnd.github.v3+json")
|
||||
if e.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+e.token)
|
||||
}
|
||||
resp, err := e.client.Do(req)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
if isRetryableNetworkError(err) && attempt < maxRetries-1 {
|
||||
time.Sleep(retryDelay)
|
||||
continue
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
// Pipeline represents a single Drone pipeline run
|
||||
type Pipeline struct {
|
||||
ID int `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Started int64 `json:"started"`
|
||||
Finished int64 `json:"finished"`
|
||||
Duration float64 `json:"duration_minutes"`
|
||||
Trigger string `json:"trigger"`
|
||||
}
|
||||
|
||||
// OriginalCommit represents an individual commit from the PR branch before squashing
|
||||
type OriginalCommit struct {
|
||||
SHA string `json:"sha"`
|
||||
Title string `json:"title"`
|
||||
Pipelines []Pipeline `json:"pipelines,omitempty"`
|
||||
}
|
||||
|
||||
// ExtractedCommit represents a commit with PR information
|
||||
type ExtractedCommit struct {
|
||||
PR int `json:"pr"`
|
||||
SHA string `json:"sha"`
|
||||
Date string `json:"date"`
|
||||
Title string `json:"title"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
Pipelines []Pipeline `json:"pipelines,omitempty"`
|
||||
OriginalCommits []OriginalCommit `json:"original_commits,omitempty"`
|
||||
}
|
||||
|
||||
// ExtractedData represents the output structure
|
||||
type ExtractedData struct {
|
||||
Commits []ExtractedCommit `json:"commits"`
|
||||
}
|
||||
|
||||
// extractSubject extracts the first line of the commit message
|
||||
func extractSubject(message string) string {
|
||||
if idx := strings.Index(message, "\n"); idx >= 0 {
|
||||
return strings.TrimSpace(message[:idx])
|
||||
}
|
||||
return strings.TrimSpace(message)
|
||||
}
|
||||
|
||||
// ExtractCommitData fetches commits and extracts them into structured format
|
||||
func (e *Extractor) ExtractCommitData(repo, branch string, maxCommits int, since string) (*ExtractedData, error) {
|
||||
commits, err := e.GetCommits(repo, branch, maxCommits, since)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching commits: %w", err)
|
||||
}
|
||||
|
||||
extractedCommits := make([]ExtractedCommit, 0, len(commits))
|
||||
originalCommitSHAs := make(map[string]bool) // Track SHAs that appear as original commits
|
||||
|
||||
for _, commit := range commits {
|
||||
title := extractSubject(commit.Commit.Message)
|
||||
|
||||
// Fetch PR information from GitHub API
|
||||
prNumber := 0
|
||||
var originalCommits []OriginalCommit
|
||||
prs, err := e.GetPRsForCommit(repo, commit.SHA)
|
||||
if err == nil && len(prs) > 0 {
|
||||
// Use the first PR number if multiple PRs are associated
|
||||
prNumber = prs[0].Number
|
||||
|
||||
// Fetch original commits from the PR before squashing
|
||||
prCommits, err := e.GetPRCommits(repo, prNumber)
|
||||
if err == nil && len(prCommits) > 0 {
|
||||
originalCommits = make([]OriginalCommit, 0, len(prCommits))
|
||||
for _, prCommit := range prCommits {
|
||||
// Skip if this is the same commit (don't self-reference)
|
||||
if prCommit.SHA == commit.SHA {
|
||||
continue
|
||||
}
|
||||
originalCommits = append(originalCommits, OriginalCommit{
|
||||
SHA: prCommit.SHA,
|
||||
Title: extractSubject(prCommit.Commit.Message),
|
||||
})
|
||||
// Track this SHA as an original commit
|
||||
originalCommitSHAs[prCommit.SHA] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extractedCommits = append(extractedCommits, ExtractedCommit{
|
||||
PR: prNumber,
|
||||
SHA: commit.SHA,
|
||||
Date: commit.Commit.Author.Date,
|
||||
Title: title,
|
||||
HTMLURL: commit.HTMLURL,
|
||||
OriginalCommits: originalCommits,
|
||||
})
|
||||
}
|
||||
|
||||
// Filter out commits that are already listed as original commits in merge commits
|
||||
// These are PR commits that appear in master history but should only show under the merge commit
|
||||
filteredCommits := make([]ExtractedCommit, 0, len(extractedCommits))
|
||||
for _, commit := range extractedCommits {
|
||||
// Keep the commit ONLY if it's NOT in the originalCommitSHAs set
|
||||
// If a commit appears in any other commit's original_commits, it should not be a top-level entry
|
||||
if !originalCommitSHAs[commit.SHA] {
|
||||
filteredCommits = append(filteredCommits, commit)
|
||||
}
|
||||
}
|
||||
|
||||
return &ExtractedData{
|
||||
Commits: filteredCommits,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ParseSinceFlag parses a date/time string in multiple formats:
|
||||
// - YYYY-MM-DD: absolute date (e.g., "2026-02-15")
|
||||
// - RFC3339: timestamp (e.g., "2026-02-15T10:30:00Z")
|
||||
// - Nd: relative days (e.g., "7d", "30d")
|
||||
//
|
||||
// Returns the parsed time in RFC3339 format.
|
||||
func ParseSinceFlag(since string) (string, error) {
|
||||
if since == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// Try parsing as YYYY-MM-DD
|
||||
if t, err := time.Parse("2006-01-02", since); err == nil {
|
||||
return t.Format(time.RFC3339), nil
|
||||
}
|
||||
|
||||
// Try parsing as RFC3339 (backward compatibility)
|
||||
if t, err := time.Parse(time.RFC3339, since); err == nil {
|
||||
return t.Format(time.RFC3339), nil
|
||||
}
|
||||
|
||||
// Try parsing as relative days format (e.g., "7d", "30d")
|
||||
if strings.HasSuffix(since, "d") {
|
||||
daysStr := strings.TrimSuffix(since, "d")
|
||||
days, err := time.ParseDuration(daysStr + "h")
|
||||
if err == nil {
|
||||
// Convert days to hours (Nd = N*24h)
|
||||
hours := days.Hours()
|
||||
t := time.Now().Add(-time.Duration(hours*24) * time.Hour)
|
||||
return t.Format(time.RFC3339), nil
|
||||
}
|
||||
// Try parsing as integer
|
||||
var numDays int
|
||||
if _, err := fmt.Sscanf(daysStr, "%d", &numDays); err == nil {
|
||||
t := time.Now().AddDate(0, 0, -numDays)
|
||||
return t.Format(time.RFC3339), nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("invalid format: use YYYY-MM-DD, RFC3339, or 'Nd' (e.g., '7d')")
|
||||
}
|
||||
|
||||
// ExtractSubject extracts the first line (subject) from a commit message.
|
||||
func ExtractSubject(message string) string {
|
||||
lines := strings.Split(message, "\n")
|
||||
return strings.TrimSpace(lines[0])
|
||||
}
|
||||
|
||||
// RedactGitHubToken redacts GitHub tokens from command strings for safe logging.
|
||||
// Matches --github-token=<token> or --github-token <token> patterns.
|
||||
func RedactGitHubToken(command string) string {
|
||||
// Match --github-token=<token>
|
||||
pattern1 := regexp.MustCompile(`--github-token=[^\s]+`)
|
||||
command = pattern1.ReplaceAllString(command, "--github-token=***")
|
||||
|
||||
// Match --github-token <token>
|
||||
pattern2 := regexp.MustCompile(`--github-token\s+[^\s]+`)
|
||||
command = pattern2.ReplaceAllString(command, "--github-token ***")
|
||||
|
||||
return command
|
||||
}
|
||||
Generated
Vendored
+8
@@ -105,6 +105,10 @@ func (c *cachedSpacesAPIClient) CreateStorageSpace(ctx context.Context, in *prov
|
||||
if key != "" {
|
||||
s := &provider.CreateStorageSpaceResponse{}
|
||||
if err := c.createPersonalSpaceCache.PullFromCache(key, s); err == nil {
|
||||
if s.Status == nil {
|
||||
s.Status = &rpc.Status{}
|
||||
}
|
||||
s.Status.Code = rpc.Code_CODE_ALREADY_EXISTS
|
||||
return s, nil
|
||||
}
|
||||
}
|
||||
@@ -163,6 +167,10 @@ func (c *cachedAPIClient) CreateHome(ctx context.Context, in *provider.CreateHom
|
||||
if key != "" {
|
||||
s := &provider.CreateHomeResponse{}
|
||||
if err := c.createPersonalSpaceCache.PullFromCache(key, s); err == nil {
|
||||
if s.Status == nil {
|
||||
s.Status = &rpc.Status{}
|
||||
}
|
||||
s.Status.Code = rpc.Code_CODE_ALREADY_EXISTS
|
||||
return s, nil
|
||||
}
|
||||
}
|
||||
|
||||
Generated
Vendored
+2
-2
@@ -33,6 +33,7 @@ import (
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/conversions"
|
||||
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
@@ -47,7 +48,6 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/storage/fs/registry"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
@@ -519,7 +519,7 @@ func (s *Service) CreateStorageSpace(ctx context.Context, req *provider.CreateSt
|
||||
// if trying to create a user home fall back to CreateHome
|
||||
if u, ok := ctxpkg.ContextGetUser(ctx); ok && req.Type == "personal" && utils.UserEqual(req.GetOwner().Id, u.Id) {
|
||||
if err := s.Storage.CreateHome(ctx); err != nil {
|
||||
st = status.NewInternal(ctx, "error creating home")
|
||||
st = status.NewStatusFromErrType(ctx, "error creating home", err)
|
||||
} else {
|
||||
st = status.NewOK(ctx)
|
||||
// TODO we cannot return a space, but the gateway currently does not expect one...
|
||||
|
||||
+50
-2
@@ -31,6 +31,8 @@ import (
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
|
||||
"github.com/gdexlab/go-render/render"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/owncloud/reva/v2/internal/http/services/archiver/manager"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
@@ -40,11 +42,17 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/downloader"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/walker"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/gdexlab/go-render/render"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
const (
|
||||
mfaHeader = "X-Multi-Factor-Authentication"
|
||||
mfaRequiredHeader = "X-Ocis-Mfa-Required"
|
||||
|
||||
_spaceTypeProtectedPersonal = "protected-personal"
|
||||
_spaceTypeProtectedProject = "protected-project"
|
||||
)
|
||||
|
||||
type svc struct {
|
||||
config *Config
|
||||
gatewaySelector pool.Selectable[gateway.GatewayAPIClient]
|
||||
@@ -251,6 +259,38 @@ func (s *svc) Handler() http.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
// MFA check
|
||||
gatewayClient, err := s.gatewaySelector.Next()
|
||||
if err != nil {
|
||||
s.log.Error().Err(err).Msg("failed to get gateway client")
|
||||
s.writeHTTPError(rw, err)
|
||||
return
|
||||
}
|
||||
for _, resource := range resources {
|
||||
res, err := gatewayClient.Stat(ctx, &provider.StatRequest{
|
||||
Ref: &provider.Reference{
|
||||
ResourceId: resource,
|
||||
Path: ".",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
s.log.Error().Err(err).Interface("resource", resource).Msg("failed to stat resource")
|
||||
s.writeHTTPError(rw, err)
|
||||
return
|
||||
}
|
||||
if res.Status.Code != rpc.Code_CODE_OK {
|
||||
s.log.Error().Interface("resource", resource).Str("status", res.Status.Message).Msg("failed to stat resource")
|
||||
s.writeHTTPError(rw, errors.New(res.Status.Message))
|
||||
return
|
||||
}
|
||||
if isProtectedSpaceType(res.Info.GetSpace().GetSpaceType()) && !isMfaSet(r) {
|
||||
s.log.Debug().Interface("resource", resource).Str("spacetype", res.Info.GetSpace().GetSpaceType()).Msg("MFA required for protected space")
|
||||
rw.Header().Set(mfaRequiredHeader, "true")
|
||||
rw.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
archName := s.config.Name
|
||||
if format == "tar" {
|
||||
archName += ".tar"
|
||||
@@ -291,3 +331,11 @@ func (s *svc) Close() error {
|
||||
func (s *svc) Unprotected() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func isMfaSet(r *http.Request) bool {
|
||||
return r.Header.Get(mfaHeader) == "true"
|
||||
}
|
||||
|
||||
func isProtectedSpaceType(spaceType string) bool {
|
||||
return spaceType == _spaceTypeProtectedPersonal || spaceType == _spaceTypeProtectedProject
|
||||
}
|
||||
+7
@@ -671,6 +671,13 @@ func (s *svc) prepareCopy(ctx context.Context, w http.ResponseWriter, r *http.Re
|
||||
return nil
|
||||
}
|
||||
|
||||
// Disallow copying from poctected space to unprotected space
|
||||
if isUnprotectedSpaceType(dstStatRes.GetInfo().GetSpace().GetSpaceType()) && isProtectedSpaceType(srcStatRes.GetInfo().GetSpace().GetSpaceType()) {
|
||||
log.Error().Msg("the unprotected destination is disallowed")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return nil
|
||||
}
|
||||
|
||||
successCode := http.StatusCreated // 201 if new resource was created, see https://tools.ietf.org/html/rfc4918#section-9.8.5
|
||||
if dstStatRes.Status.Code == rpc.Code_CODE_OK {
|
||||
successCode = http.StatusNoContent // 204 if target already existed, see https://tools.ietf.org/html/rfc4918#section-9.8.5
|
||||
|
||||
+25
@@ -50,6 +50,17 @@ const (
|
||||
|
||||
// WwwAuthenticate captures the Www-Authenticate header string.
|
||||
WwwAuthenticate = "Www-Authenticate"
|
||||
|
||||
// mfaHeader is the header used to forward the MFA authentication status.
|
||||
mfaHeader = "X-Multi-Factor-Authentication"
|
||||
|
||||
// mfaRequiredHeader is the response header indicating that MFA step-up authentication is required.
|
||||
mfaRequiredHeader = "X-Ocis-Mfa-Required"
|
||||
|
||||
_spaceTypePersonal = "personal"
|
||||
_spaceTypeProject = "project"
|
||||
_spaceTypeProtectedPersonal = "protected-personal"
|
||||
_spaceTypeProtectedProject = "protected-project"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -455,3 +466,17 @@ func handleOCMAuth(ctx context.Context, c gatewayv1beta1.GatewayAPIClient, ocmsh
|
||||
ClientSecret: sharedSecret,
|
||||
})
|
||||
}
|
||||
|
||||
func isMfaSet(r *http.Request) bool {
|
||||
return r.Header.Get(mfaHeader) == "true"
|
||||
}
|
||||
|
||||
// isUnprotectedSpaceType returns true if the space type is unprotected.
|
||||
func isUnprotectedSpaceType(spaceType string) bool {
|
||||
return spaceType == _spaceTypePersonal || spaceType == _spaceTypeProject
|
||||
}
|
||||
|
||||
// isProtectedSpaceType returns true if the space type requires MFA authentication.
|
||||
func isProtectedSpaceType(spaceType string) bool {
|
||||
return spaceType == _spaceTypeProtectedPersonal || spaceType == _spaceTypeProtectedProject
|
||||
}
|
||||
+8
@@ -79,6 +79,14 @@ func (s *svc) handleGet(ctx context.Context, w http.ResponseWriter, r *http.Requ
|
||||
return
|
||||
}
|
||||
|
||||
// MFA enforcement.
|
||||
if isProtectedSpaceType(sRes.GetInfo().GetSpace().GetSpaceType()) && !isMfaSet(r) {
|
||||
log.Debug().Interface("ref", ref).Str("spacetype", sRes.GetInfo().GetSpace().GetSpaceType()).Msg("MFA required for protected space")
|
||||
w.Header().Set(mfaRequiredHeader, "true")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
if sRes.Info.Type != provider.ResourceType_RESOURCE_TYPE_FILE {
|
||||
w.Header().Set("Content-Length", "0")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
Generated
Vendored
+21
-3
@@ -23,11 +23,13 @@ import (
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/config"
|
||||
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/errors"
|
||||
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/net"
|
||||
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/propfind"
|
||||
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/spacelookup"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/rhttp/router"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
@@ -53,8 +55,8 @@ func (h *SpacesHandler) init(c *config.Config) error {
|
||||
func (h *SpacesHandler) Handler(s *svc, trashbinHandler *TrashbinHandler) http.Handler {
|
||||
config := s.Config()
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// ctx := r.Context()
|
||||
// log := appctx.GetLogger(ctx)
|
||||
ctx := r.Context()
|
||||
log := appctx.GetLogger(ctx)
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
s.handleOptions(w, r)
|
||||
@@ -76,6 +78,22 @@ func (h *SpacesHandler) Handler(s *svc, trashbinHandler *TrashbinHandler) http.H
|
||||
|
||||
spaceID := segment
|
||||
|
||||
// MFA enforcement: look up the space type and require MFA for protected spaces.
|
||||
if client, err := s.gatewaySelector.Next(); err == nil {
|
||||
space, st, err := spacelookup.LookUpStorageSpaceByID(ctx, client, spaceID)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("spaceid", spaceID).Msg("error looking up space for MFA check")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if st.GetCode() == rpc.Code_CODE_OK && isProtectedSpaceType(space.GetSpaceType()) && !isMfaSet(r) {
|
||||
log.Debug().Str("spaceid", spaceID).Str("spacetype", space.GetSpaceType()).Msg("MFA required for protected space")
|
||||
w.Header().Set(mfaRequiredHeader, "true")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// TODO initialize status with http.StatusBadRequest
|
||||
// TODO initialize err with errors.ErrUnsupportedMethod
|
||||
var status int // status 0 means the handler already sent the response
|
||||
@@ -124,7 +142,7 @@ func (h *SpacesHandler) Handler(s *svc, trashbinHandler *TrashbinHandler) http.H
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
appctx.GetLogger(r.Context()).Error().Err(err).Msg(err.Error())
|
||||
log.Error().Err(err).Msg(err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+9
-7
@@ -34,6 +34,7 @@ import (
|
||||
providerpb "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
registrypb "github.com/cs3org/go-cs3apis/cs3/storage/registry/v1beta1"
|
||||
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
@@ -44,7 +45,6 @@ import (
|
||||
pkgregistry "github.com/owncloud/reva/v2/pkg/storage/registry/registry"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
@@ -101,12 +101,14 @@ func (c *config) init() {
|
||||
c.Providers = map[string]*Provider{
|
||||
sharedconf.GetGatewaySVC(""): {
|
||||
Spaces: map[string]*spaceConfig{
|
||||
"personal": {MountPoint: "/users", PathTemplate: "/users/{{.Space.Owner.Id.OpaqueId}}"},
|
||||
"project": {MountPoint: "/projects", PathTemplate: "/projects/{{.Space.Name}}"},
|
||||
"virtual": {MountPoint: "/users/{{.CurrentUser.Id.OpaqueId}}/Shares"},
|
||||
"grant": {MountPoint: "."},
|
||||
"mountpoint": {MountPoint: "/users/{{.CurrentUser.Id.OpaqueId}}/Shares", PathTemplate: "/users/{{.CurrentUser.Id.OpaqueId}}/Shares/{{.Space.Name}}"},
|
||||
"public": {MountPoint: "/public"},
|
||||
"personal": {MountPoint: "/users", PathTemplate: "/users/{{.Space.Owner.Id.OpaqueId}}"},
|
||||
"project": {MountPoint: "/projects", PathTemplate: "/projects/{{.Space.Name}}"},
|
||||
"protected-personal": {MountPoint: "/protected-users", PathTemplate: "/protected-users/{{.Space.Owner.Id.OpaqueId}}"},
|
||||
"protected-project": {MountPoint: "/protected-projects", PathTemplate: "/protected-projects/{{.Space.Name}}"},
|
||||
"virtual": {MountPoint: "/users/{{.CurrentUser.Id.OpaqueId}}/Shares"},
|
||||
"grant": {MountPoint: "."},
|
||||
"mountpoint": {MountPoint: "/users/{{.CurrentUser.Id.OpaqueId}}/Shares", PathTemplate: "/users/{{.CurrentUser.Id.OpaqueId}}/Shares/{{.Space.Name}}"},
|
||||
"public": {MountPoint: "/public"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
Generated
Vendored
+6
-4
@@ -25,8 +25,10 @@ func init() {
|
||||
}
|
||||
|
||||
const (
|
||||
_spaceTypePersonal = "personal"
|
||||
_spaceTypeProject = "project"
|
||||
_spaceTypePersonal = "personal"
|
||||
_spaceTypeProject = "project"
|
||||
_spaceTypeProtectedPersonal = "protected-personal"
|
||||
_spaceTypeProtectedProject = "protected-project"
|
||||
)
|
||||
|
||||
// PermissionsChecker defines an interface for checking permissions on a Node
|
||||
@@ -75,9 +77,9 @@ func (p Permissions) SetSpaceQuota(ctx context.Context, spaceid string, spaceTyp
|
||||
switch spaceType {
|
||||
default:
|
||||
return false // only quotas of personal and project space may be changed
|
||||
case _spaceTypePersonal:
|
||||
case _spaceTypePersonal, _spaceTypeProtectedPersonal:
|
||||
return p.checkPermission(ctx, "Drives.ReadWritePersonalQuota", spaceRef(spaceid))
|
||||
case _spaceTypeProject:
|
||||
case _spaceTypeProject, _spaceTypeProtectedProject:
|
||||
return p.checkPermission(ctx, "Drives.ReadWriteProjectQuota", spaceRef(spaceid))
|
||||
}
|
||||
}
|
||||
|
||||
+16
-12
@@ -56,11 +56,13 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
_spaceTypePersonal = "personal"
|
||||
_spaceTypeProject = "project"
|
||||
spaceTypeShare = "share"
|
||||
spaceTypeAny = "*"
|
||||
spaceIDAny = "*"
|
||||
_spaceTypePersonal = "personal"
|
||||
_spaceTypeProject = "project"
|
||||
_spaceTypeProtectedPersonal = "protected-personal"
|
||||
_spaceTypeProtectedProject = "protected-project"
|
||||
spaceTypeShare = "share"
|
||||
spaceTypeAny = "*"
|
||||
spaceIDAny = "*"
|
||||
|
||||
quotaUnrestricted = 0
|
||||
)
|
||||
@@ -82,7 +84,7 @@ func (fs *Decomposedfs) CreateStorageSpace(ctx context.Context, req *provider.Cr
|
||||
// Check if space already exists
|
||||
rootPath := ""
|
||||
switch req.Type {
|
||||
case _spaceTypePersonal:
|
||||
case _spaceTypePersonal, _spaceTypeProtectedPersonal:
|
||||
if fs.o.PersonalSpacePathTemplate != "" {
|
||||
rootPath = filepath.Join(fs.o.Root, templates.WithUser(u, fs.o.PersonalSpacePathTemplate))
|
||||
}
|
||||
@@ -102,7 +104,7 @@ func (fs *Decomposedfs) CreateStorageSpace(ctx context.Context, req *provider.Cr
|
||||
if alias == "" {
|
||||
alias = templates.WithSpacePropertiesAndUser(u, req.Type, req.Name, spaceID, fs.o.GeneralSpaceAliasTemplate)
|
||||
}
|
||||
if req.Type == _spaceTypePersonal {
|
||||
if req.Type == _spaceTypePersonal || req.Type == _spaceTypeProtectedPersonal {
|
||||
alias = templates.WithSpacePropertiesAndUser(u, req.Type, req.Name, spaceID, fs.o.PersonalSpaceAliasTemplate)
|
||||
}
|
||||
|
||||
@@ -199,7 +201,7 @@ func (fs *Decomposedfs) CreateStorageSpace(ctx context.Context, req *provider.Cr
|
||||
|
||||
ctx = storageprovider.WithSpaceType(ctx, req.Type)
|
||||
|
||||
if req.Type != _spaceTypePersonal {
|
||||
if req.Type != _spaceTypePersonal && req.Type != _spaceTypeProtectedPersonal {
|
||||
if err := fs.AddGrant(ctx, &provider.Reference{
|
||||
ResourceId: &provider.ResourceId{
|
||||
SpaceId: spaceID,
|
||||
@@ -375,9 +377,11 @@ func (fs *Decomposedfs) ListStorageSpaces(ctx context.Context, filter []*provide
|
||||
if _, ok := spaceTypes[spaceTypeAny]; ok {
|
||||
// TODO do not hardcode dirs
|
||||
spaceTypes = map[string]struct{}{
|
||||
"personal": {},
|
||||
"project": {},
|
||||
"share": {},
|
||||
"personal": {},
|
||||
"project": {},
|
||||
"share": {},
|
||||
"protected-personal": {},
|
||||
"protected-project": {},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1164,7 +1168,7 @@ func (fs *Decomposedfs) getSpaceRoot(spaceID string) string {
|
||||
// - a project space can always be enabled/disabled/deleted by its manager (i.e. users have the "remove" grant)
|
||||
func canDeleteSpace(ctx context.Context, spaceID string, typ string, purge bool, n *node.Node, p permissions.Permissions) error {
|
||||
// delete-all-home spaces allows to disable and delete a personal space
|
||||
if typ == "personal" {
|
||||
if typ == _spaceTypePersonal || typ == _spaceTypeProtectedPersonal {
|
||||
if p.DeleteAllHomeSpaces(ctx) {
|
||||
return nil
|
||||
}
|
||||
|
||||
Vendored
+1
-1
@@ -1316,7 +1316,7 @@ github.com/orcaman/concurrent-map
|
||||
# github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
|
||||
## explicit; go 1.18
|
||||
github.com/owncloud/libre-graph-api-go
|
||||
# github.com/owncloud/reva/v2 v2.0.0-20260223124048-61ee39d95d5f
|
||||
# github.com/owncloud/reva/v2 v2.0.0-20260303153746-059bcdfc4fbb
|
||||
## explicit; go 1.24.0
|
||||
github.com/owncloud/reva/v2/cmd/revad/internal/grace
|
||||
github.com/owncloud/reva/v2/cmd/revad/runtime
|
||||
|
||||
Reference in new issue
Block a user