From 39e3d33820418bc1dd7ca4c1f867222f53b4f3d3 Mon Sep 17 00:00:00 2001 From: Roman Perekhod Date: Fri, 15 May 2026 16:53:05 +0200 Subject: [PATCH] [full-ci] feat: ocisdev-533 graph (#12108) * feat: Implemet the vault-storage feat: Separate the storage-users and graph to handle feat: move the space create cache configurate the vault srorage Postprocessing hide the assignment of the MountID to VaultStorageProviderID behind a flag to avoid the ID mismatch configurate the proxy to create the vault home space update the filter Make the graph able to handle vault prefix. no extra service needed apply the vault filter to sharedbyme and sharedwithme added vault-storage docker use squashed reva fix the finishUpload event restict webdav copy/move from the vault feat: provide the mfa to webdav and grpc feat: refactoring: provide the mfa to webdav and grpc mfa collaboration fix GetRootDriveChildren and more fix: send the MFA header in HTTP clients from the collaboration service provide the default storage user vault configuration update create_home middleware Update deployments/examples/ocis_full/vault-storage.yml Co-authored-by: Martin Update services/gateway/pkg/config/config.go Co-authored-by: Martin Update services/graph/pkg/config/config.go Co-authored-by: Martin Update services/graph/pkg/config/config.go Co-authored-by: Martin Update services/storage-users/pkg/config/config.go Co-authored-by: Martin Update services/proxy/pkg/config/config.go Co-authored-by: Martin Update services/storage-users/pkg/config/config.go Co-authored-by: Martin Update deployments/examples/ocis_full/vault-storage.yml Co-authored-by: Martin bump reva deduplicate the requireMFA middeware on vault routes. fix AppendPlainToOpaque. added the changlog and comments * feat: add the vault mode search * Update changelog/unreleased/enhancement-vault-storage.md Co-authored-by: Martin * update the readme. the reva vault storage provider configuration disabled by default * feat: [OCISDEV-531] add vault capabilities to the OCS capabilities endpoint * the port range allocated. the configuration updated. --------- Co-authored-by: Martin --- .gitignore | 1 + .make/go.mk | 2 - changelog/unreleased/bump-reva.md | 2 +- .../enhancement-vault-capabilities.md | 10 + .../unreleased/enhancement-vault-storage.md | 15 + deployments/examples/ocis_full/.env | 7 +- .../examples/ocis_full/vault-storage.yml | 40 +++ docs/services/general-info/port-ranges.md | 2 +- ocis-pkg/mfa/mfa.go | 7 +- .../pkg/connector/contentconnector.go | 2 + .../pkg/middleware/wopicontext.go | 4 + .../pkg/service/grpc/v0/service.go | 6 + services/frontend/pkg/config/config.go | 2 + services/frontend/pkg/revaconfig/config.go | 3 + services/gateway/pkg/config/config.go | 3 + .../pkg/config/defaults/defaultconfig.go | 1 + services/gateway/pkg/revaconfig/config.go | 21 +- services/graph/pkg/config/config.go | 3 + .../pkg/config/defaults/defaultconfig.go | 9 +- services/graph/pkg/middleware/auth.go | 4 + services/graph/pkg/middleware/mfa.go | 23 ++ services/graph/pkg/middleware/vault.go | 30 ++ services/graph/pkg/service/v0/driveitems.go | 19 +- .../graph/pkg/service/v0/driveitems_test.go | 38 ++ services/graph/pkg/service/v0/drives.go | 27 +- services/graph/pkg/service/v0/graph_test.go | 6 +- services/graph/pkg/service/v0/service.go | 23 +- services/graph/pkg/service/v0/sharedbyme.go | 12 +- services/graph/pkg/service/v0/sharedwithme.go | 19 + .../graph/pkg/service/v0/spacetemplates.go | 7 +- .../policies/pkg/service/event/service.go | 1 + .../pkg/postprocessing/postprocessing.go | 1 + services/proxy/pkg/command/server.go | 3 +- services/proxy/pkg/config/config.go | 1 + .../pkg/config/defaults/defaultconfig.go | 4 + services/proxy/pkg/middleware/create_home.go | 56 ++- services/proxy/pkg/middleware/mfa.go | 70 +++- services/proxy/pkg/middleware/options.go | 20 ++ services/search/pkg/search/search.go | 12 + services/search/pkg/search/service.go | 53 ++- services/search/pkg/search/service_test.go | 328 ++++++++++++++++++ .../search/pkg/service/grpc/v0/service.go | 13 +- services/storage-users/README.md | 84 +++++ services/storage-users/pkg/config/config.go | 3 + .../pkg/config/defaults/defaultconfig.go | 6 + .../storage-users/pkg/revaconfig/config.go | 16 +- .../storage-users/pkg/revaconfig/drivers.go | 7 +- .../thumbnails/pkg/service/grpc/v0/service.go | 21 +- .../thumbnails/pkg/thumbnail/imgsource/cs3.go | 11 + services/webdav/pkg/service/v0/search.go | 6 + services/webdav/pkg/service/v0/service.go | 24 +- 51 files changed, 1016 insertions(+), 72 deletions(-) create mode 100644 changelog/unreleased/enhancement-vault-capabilities.md create mode 100644 changelog/unreleased/enhancement-vault-storage.md create mode 100644 deployments/examples/ocis_full/vault-storage.yml create mode 100644 services/graph/pkg/middleware/mfa.go create mode 100644 services/graph/pkg/middleware/vault.go diff --git a/.gitignore b/.gitignore index cacae4f6d18..363ceb23317 100644 --- a/.gitignore +++ b/.gitignore @@ -62,4 +62,5 @@ go.work.sum .envrc CLAUDE.md .claude/ +GEMINI.md .agents/ \ No newline at end of file diff --git a/.make/go.mk b/.make/go.mk index 7000c56e383..a16d58c4f21 100644 --- a/.make/go.mk +++ b/.make/go.mk @@ -118,7 +118,6 @@ debug-linux-docker-amd64: release-dirs -gcflags="all=-N -l" \ -tags 'netgo $(TAGS)' \ -buildmode=exe \ - -trimpath \ -ldflags '-extldflags "-static" $(DEBUG_LDFLAGS) $(DOCKER_LDFLAGS)' \ -o '$(DIST)/binaries/$(EXECUTABLE)-linux-amd64' \ ./cmd/$(NAME) @@ -130,7 +129,6 @@ debug-linux-docker-arm64: release-dirs -gcflags="all=-N -l" \ -tags 'netgo $(TAGS)' \ -buildmode=exe \ - -trimpath \ -ldflags '-extldflags "-static" $(DEBUG_LDFLAGS) $(DOCKER_LDFLAGS)' \ -o '$(DIST)/binaries/$(EXECUTABLE)-linux-arm64' \ ./cmd/$(NAME) diff --git a/changelog/unreleased/bump-reva.md b/changelog/unreleased/bump-reva.md index 4a674dbafb5..fd8d075cba1 100644 --- a/changelog/unreleased/bump-reva.md +++ b/changelog/unreleased/bump-reva.md @@ -5,4 +5,4 @@ bumped reva version https://github.com/owncloud/ocis/pull/12051 https://github.com/owncloud/ocis/pull/12087 https://github.com/owncloud/ocis/pull/12137 -https://github.com/owncloud/ocis/pull/12315 +https://github.com/owncloud/ocis/pull/12302 diff --git a/changelog/unreleased/enhancement-vault-capabilities.md b/changelog/unreleased/enhancement-vault-capabilities.md new file mode 100644 index 00000000000..f38ea346acd --- /dev/null +++ b/changelog/unreleased/enhancement-vault-capabilities.md @@ -0,0 +1,10 @@ +Enhancement: Add vault capabilities to the OCS capabilities endpoint + +Added `OCIS_ENABLE_VAULT_MODE` / `FRONTEND_ENABLE_VAULT_MODE` config option to +the frontend service. When enabled, the OCS capabilities endpoint advertises +`vault.enabled = true`. Clients can request vault-specific capabilities via +`/ocs/v2.php/cloud/capabilities?vault=true`, which returns a response with +public sharing and federation sharing disabled. + +https://github.com/owncloud/ocis/pull/12283 +https://github.com/owncloud/reva/pull/584 diff --git a/changelog/unreleased/enhancement-vault-storage.md b/changelog/unreleased/enhancement-vault-storage.md new file mode 100644 index 00000000000..70f732a4b6c --- /dev/null +++ b/changelog/unreleased/enhancement-vault-storage.md @@ -0,0 +1,15 @@ +Enhancement: Add vault storage with MFA-protected access + +Added a dedicated vault storage that can be protected with MFA. A separate +`storage-users` service instance configured in vault mode runs and serves +`/vault/users` and `/vault/projects` mount points with a dedicated +`VaultStorageProviderID`. The `graph` service gained a new vault mode +(`OCIS_ENABLE_VAULT_MODE`) that serves the vault API under the `/vault` +prefix. The storage registry now routes vault-specific requests exclusively to +the vault storage provider, preventing accidental access to vault spaces when +no explicit storage ID is provided. + +MFA status is propagated through gRPC metadata +and forwarded in HTTP headers for WOPI/collaboration flows. + +https://github.com/owncloud/ocis/pull/12108 diff --git a/deployments/examples/ocis_full/.env b/deployments/examples/ocis_full/.env index 93b7507f75e..07966521851 100644 --- a/deployments/examples/ocis_full/.env +++ b/deployments/examples/ocis_full/.env @@ -185,6 +185,11 @@ KEYCLOAK_TRACING= # Note: the leading colon is required to enable the service. #KEYCLOAK=:keycloak.yml +### oCIS Vault Storage Settings ### +# Enable the oCIS vault storage +# Note: the leading colon is required to enable the service. +#VAULT_STORAGE=:vault-storage.yml + ## Default Enabled Services ## @@ -296,4 +301,4 @@ MAIL_SERVER_DOCKER_TAG=v1.29.3 # This MUST be the last line as it assembles the supplemental compose files to be used. # ALL supplemental configs must be added here, whether commented or not. # Each var must either be empty or contain :path/file.yml -COMPOSE_FILE=docker-compose.yml${OCIS:-}${TIKA:-}${S3NG:-}${S3NG_MINIO:-}${COLLABORA:-}${IMPORTER:-}${CLAMAV:-}${ONLYOFFICE:-}${EXTENSIONS:-}${UNZIP:-}${DRAWIO:-}${JSONVIEWER:-}${PROGRESSBARS:-}${EXTERNALSITES:-}${PHOTOADDON:-}${ADVANCEDSEARCH:-}${MAIL_SERVER:-}${MONITORING:-}${KEYCLOAK:-} +COMPOSE_FILE=docker-compose.yml${OCIS:-}${TIKA:-}${S3NG:-}${S3NG_MINIO:-}${COLLABORA:-}${IMPORTER:-}${CLAMAV:-}${ONLYOFFICE:-}${EXTENSIONS:-}${UNZIP:-}${DRAWIO:-}${JSONVIEWER:-}${PROGRESSBARS:-}${EXTERNALSITES:-}${PHOTOADDON:-}${ADVANCEDSEARCH:-}${MAIL_SERVER:-}${MONITORING:-}${KEYCLOAK:-}${VAULT_STORAGE:-} diff --git a/deployments/examples/ocis_full/vault-storage.yml b/deployments/examples/ocis_full/vault-storage.yml new file mode 100644 index 00000000000..c79b16b4d03 --- /dev/null +++ b/deployments/examples/ocis_full/vault-storage.yml @@ -0,0 +1,40 @@ +services: + ocis: + environment: + OCIS_MFA_ENABLED: true + NATS_NATS_HOST: 0.0.0.0 + SETTINGS_GRPC_ADDR: ocis:9191 + OCIS_ENABLE_VAULT_MODE: true + + storage-users-vault: + image: ${OCIS_DOCKER_IMAGE}:${OCIS_DOCKER_TAG} + networks: + ocis-net: + depends_on: + ocis: + condition: service_started + command: ["storage-users", "server"] + environment: + OCIS_LOG_LEVEL: ${LOG_LEVEL:-info} + OCIS_LOG_COLOR: "${LOG_PRETTY:-false}" + OCIS_LOG_PRETTY: "${LOG_PRETTY:-false}" + OCIS_GATEWAY_GRPC_ADDR: ocis:9142 + OCIS_EVENTS_ENDPOINT: ocis:9233 + OCIS_CACHE_STORE_NODES: ocis:9233 + MICRO_REGISTRY_ADDRESS: ocis:9233 + # configure vault mode for the storage users service + STORAGE_USERS_ENABLE_VAULT_MODE: true + STORAGE_USERS_SERVICE_NAME: storage-users-vault + STORAGE_USERS_GRPC_ADDR: storage-users-vault:9285 + STORAGE_USERS_HTTP_ADDR: storage-users-vault:9286 + STORAGE_USERS_DATA_SERVER_URL: http://storage-users-vault:9286/data + STORAGE_USERS_DEBUG_ADDR: storage-users-vault:9287 + STORAGE_USERS_OCIS_ROOT: /var/lib/ocis/storage/users-vault + STORAGE_USERS_EVENTS_CONSUMER_GROUP: vault-dcfs + volumes: + # configure the .env file to use own paths instead of docker internal volumes + - ${OCIS_CONFIG_DIR:-ocis-config}:/etc/ocis + - ${OCIS_DATA_DIR:-ocis-data}:/var/lib/ocis + logging: + driver: ${LOG_DRIVER:-local} + restart: always diff --git a/docs/services/general-info/port-ranges.md b/docs/services/general-info/port-ranges.md index 2e94a82b8e3..aa2d6a1f863 100644 --- a/docs/services/general-info/port-ranges.md +++ b/docs/services/general-info/port-ranges.md @@ -68,7 +68,7 @@ We also suggest using the last port in your extensions' range as a debug/metrics | 9270-9274 | [eventhistory]({{< ref "../eventhistory/_index.md" >}}) | | 9275-9279 | [webfinger]({{< ref "../webfinger/_index.md" >}}) | | 9280-9284 | [ocm]({{< ref "../ocm/_index.md" >}}) | -| 9285-9289 | FREE | +| 9285-9289 | [storage-users (vault)]({{< ref "../storage-users/_index.md" >}}) | | 9290-9294 | FREE | | 9295-9299 | FREE | | 9300-9304 | [collaboration]({{< ref "../collaboration/_index.md" >}}) | diff --git a/ocis-pkg/mfa/mfa.go b/ocis-pkg/mfa/mfa.go index e75a46002a7..f2016d50b3d 100644 --- a/ocis-pkg/mfa/mfa.go +++ b/ocis-pkg/mfa/mfa.go @@ -7,7 +7,7 @@ import ( "net/http" ) -// MFAHeader is the header to be used across grpc and http services +// MFAHeader is the header to be used across http services // to forward the access token. const MFAHeader = "X-Multi-Factor-Authentication" @@ -57,3 +57,8 @@ func SetHeader(r *http.Request, mfa bool) { r.Header.Set(MFAHeader, "false") } + +// IsMFAHeaderTrue checks if the MFA header is set to "true". +func IsMFAHeaderTrue(r *http.Request) bool { + return r.Header.Get(MFAHeader) == "true" +} diff --git a/services/collaboration/pkg/connector/contentconnector.go b/services/collaboration/pkg/connector/contentconnector.go index 88751e4f314..dcf3f25a781 100644 --- a/services/collaboration/pkg/connector/contentconnector.go +++ b/services/collaboration/pkg/connector/contentconnector.go @@ -15,6 +15,7 @@ import ( rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" providerv1beta1 "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" + "github.com/owncloud/ocis/v2/ocis-pkg/mfa" "github.com/owncloud/ocis/v2/ocis-pkg/tracing" "github.com/owncloud/ocis/v2/services/collaboration/pkg/config" "github.com/owncloud/ocis/v2/services/collaboration/pkg/middleware" @@ -71,6 +72,7 @@ func newHttpRequest(ctx context.Context, wopiContext middleware.WopiContext, met } else { httpReq.Header.Add("X-Access-Token", wopiContext.AccessToken) } + mfa.SetHeader(httpReq, wopiContext.HasMFA) return httpReq, nil } diff --git a/services/collaboration/pkg/middleware/wopicontext.go b/services/collaboration/pkg/middleware/wopicontext.go index 0d137eb8d73..18948dc8feb 100644 --- a/services/collaboration/pkg/middleware/wopicontext.go +++ b/services/collaboration/pkg/middleware/wopicontext.go @@ -36,6 +36,7 @@ type WopiContext struct { FileReference *providerv1beta1.Reference TemplateReference *providerv1beta1.Reference ViewMode appproviderv1beta1.ViewMode + HasMFA bool } // WopiContextAuthMiddleware will prepare an HTTP handler to be used as @@ -133,6 +134,9 @@ func WopiContextAuthMiddleware(cfg *config.Config, st microstore.Store, next htt ctx = ctxpkg.ContextSetUser(ctx, user) ctx = ctxpkg.ContextSetScopes(ctx, scopes) + // Propagate MFA status embedded in the WOPI token to outgoing gRPC metadata. + ctx = ctxpkg.AppendMFAToOutgoingContext(ctx, claims.WopiContext.HasMFA) + // include additional info in the context's logger wopiLogger = wopiLogger.With(). Str("FileReference", claims.WopiContext.FileReference.String()). diff --git a/services/collaboration/pkg/service/grpc/v0/service.go b/services/collaboration/pkg/service/grpc/v0/service.go index 0d0fd3172cb..9ec51677369 100644 --- a/services/collaboration/pkg/service/grpc/v0/service.go +++ b/services/collaboration/pkg/service/grpc/v0/service.go @@ -5,6 +5,7 @@ import ( "errors" "net/url" "path" + "slices" "strconv" "strings" @@ -13,10 +14,12 @@ import ( userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" providerv1beta1 "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" + ctxpkg "github.com/owncloud/reva/v2/pkg/ctx" "github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool" "github.com/owncloud/reva/v2/pkg/storagespace" "github.com/owncloud/reva/v2/pkg/utils" microstore "go-micro.dev/v4/store" + "google.golang.org/grpc/metadata" "github.com/owncloud/ocis/v2/ocis-pkg/log" "github.com/owncloud/ocis/v2/services/collaboration/pkg/config" @@ -121,11 +124,14 @@ func (s *Service) OpenInApp( } // create the wopiContext and generate the token + mfav := metadata.ValueFromIncomingContext(ctx, ctxpkg.MFAOutgoingHeader) + hasMFA := slices.Contains(mfav, "true") wopiContext := middleware.WopiContext{ AccessToken: req.GetAccessToken(), // it will be encrypted ViewOnlyToken: utils.ReadPlainFromOpaque(req.GetOpaque(), "viewOnlyToken"), FileReference: &providerFileRef, ViewMode: req.GetViewMode(), + HasMFA: hasMFA, } if templateID := utils.ReadPlainFromOpaque(req.GetOpaque(), "template"); templateID != "" { diff --git a/services/frontend/pkg/config/config.go b/services/frontend/pkg/config/config.go index 681f0a5b933..ad7382a86d8 100644 --- a/services/frontend/pkg/config/config.go +++ b/services/frontend/pkg/config/config.go @@ -66,6 +66,8 @@ type Config struct { MultiFactorAuthentication MFAConfig `yaml:"mfa"` + EnableVaultMode bool `yaml:"enable_vault_mode" env:"OCIS_ENABLE_VAULT_MODE;FRONTEND_ENABLE_VAULT_MODE" desc:"Enable vault mode. When enabled, the capabilities endpoint will report vault as enabled and the capabilities?vault=true endpoint will return capabilities with public sharing and federation disabled." introductionVersion:"Deledda"` + Context context.Context `yaml:"-"` } diff --git a/services/frontend/pkg/revaconfig/config.go b/services/frontend/pkg/revaconfig/config.go index 0a8de7dbf90..c09e176ddc8 100644 --- a/services/frontend/pkg/revaconfig/config.go +++ b/services/frontend/pkg/revaconfig/config.go @@ -351,6 +351,9 @@ func FrontendConfigFromStruct(cfg *config.Config, logger log.Logger) (map[string "levelnames": cfg.MultiFactorAuthentication.AuthLevelNames, }, }, + "vault": map[string]interface{}{ + "enabled": cfg.EnableVaultMode, + }, }, "version": map[string]interface{}{ "product": "Infinite Scale", diff --git a/services/gateway/pkg/config/config.go b/services/gateway/pkg/config/config.go index 92f44c19f4e..e869310f0d1 100644 --- a/services/gateway/pkg/config/config.go +++ b/services/gateway/pkg/config/config.go @@ -42,10 +42,13 @@ type Config struct { AuthServiceEndpoint string `yaml:"auth_service_endpoint" env:"GATEWAY_AUTH_SERVICE_ENDPOINT" desc:"The endpoint of the auth-service service. Can take a service name or a gRPC URI with the dns, kubernetes or unix protocol." introductionVersion:"7.0.0"` StoragePublicLinkEndpoint string `yaml:"storage_public_link_endpoint" env:"GATEWAY_STORAGE_PUBLIC_LINK_ENDPOINT" desc:"The endpoint of the storage-publiclink service. Can take a service name or a gRPC URI with the dns, kubernetes or unix protocol." introductionVersion:"7.0.0"` StorageUsersEndpoint string `yaml:"storage_users_endpoint" env:"GATEWAY_STORAGE_USERS_ENDPOINT" desc:"The endpoint of the storage-users service. Can take a service name or a gRPC URI with the dns, kubernetes or unix protocol." introductionVersion:"7.0.0"` + StorageUsersVaultEndpoint string `yaml:"storage_users_vault_endpoint" env:"GATEWAY_STORAGE_USERS_VAULT_ENDPOINT" desc:"The endpoint of the storage-users-vault service. The storage-users-vault is an additional storage-users service that runs in vault mode. It can take a service name or a gRPC URI with the dns, kubernetes or unix protocol." introductionVersion:"Deledda"` StorageSharesEndpoint string `yaml:"storage_shares_endpoint" env:"GATEWAY_STORAGE_SHARES_ENDPOINT" desc:"The endpoint of the storage-shares service. Can take a service name or a gRPC URI with the dns, kubernetes or unix protocol." introductionVersion:"7.0.0"` AppRegistryEndpoint string `yaml:"app_registry_endpoint" env:"GATEWAY_APP_REGISTRY_ENDPOINT" desc:"The endpoint of the app-registry service. Can take a service name or a gRPC URI with the dns, kubernetes or unix protocol." introductionVersion:"7.0.0"` OCMEndpoint string `yaml:"ocm_endpoint" env:"GATEWAY_OCM_ENDPOINT" desc:"The endpoint of the ocm service. Can take a service name or a gRPC URI with the dns, kubernetes or unix protocol." introductionVersion:"7.0.0"` + EnableVaultMode bool `yaml:"enable_vault_mode" env:"OCIS_ENABLE_VAULT_MODE;GATEWAY_ENABLE_VAULT_MODE" desc:"Set this to true to enable the default rule for vault storage provider configuration. Only applicable if the storage-users-vault service, a specially configured storage-users service, is configured." introductionVersion:"Deledda"` + StorageRegistry StorageRegistry `yaml:"storage_registry"` // TODO: should we even support switching this? Context context.Context `yaml:"-"` diff --git a/services/gateway/pkg/config/defaults/defaultconfig.go b/services/gateway/pkg/config/defaults/defaultconfig.go index 4bab0339312..2a2911c5dce 100644 --- a/services/gateway/pkg/config/defaults/defaultconfig.go +++ b/services/gateway/pkg/config/defaults/defaultconfig.go @@ -58,6 +58,7 @@ func DefaultConfig() *config.Config { StoragePublicLinkEndpoint: "com.owncloud.api.storage-publiclink", StorageSharesEndpoint: "com.owncloud.api.storage-shares", StorageUsersEndpoint: "com.owncloud.api.storage-users", + StorageUsersVaultEndpoint: "com.owncloud.api.storage-users-vault", UsersEndpoint: "com.owncloud.api.users", OCMEndpoint: "com.owncloud.api.ocm", diff --git a/services/gateway/pkg/revaconfig/config.go b/services/gateway/pkg/revaconfig/config.go index 44dcda07348..0a7d90a8fdd 100644 --- a/services/gateway/pkg/revaconfig/config.go +++ b/services/gateway/pkg/revaconfig/config.go @@ -138,7 +138,7 @@ func spacesProviders(cfg *config.Config, logger log.Logger) map[string]map[strin return rules } // generate rules based on default config - return map[string]map[string]interface{}{ + rules := map[string]map[string]interface{}{ cfg.StorageUsersEndpoint: { "providerid": cfg.StorageRegistry.StorageUsersMountID, "spaces": map[string]interface{}{ @@ -198,4 +198,23 @@ func spacesProviders(cfg *config.Config, logger log.Logger) map[string]map[strin }, // medatada storage not part of the global namespace } + // enable the default rule for vault storage provider configuration + if cfg.EnableVaultMode { + rules[cfg.StorageUsersVaultEndpoint] = map[string]interface{}{ + "providerid": utils.VaultStorageProviderID, + "spaces": map[string]interface{}{ + "personal": map[string]interface{}{ + // The mount point must have the "vault/" prefix to be picked up by the vault storage provider + "mount_point": "/vault/users", + "path_template": "/vault/users/{{.Space.Owner.Id.OpaqueId}}", + }, + "project": map[string]interface{}{ + // The mount point must have the "vault/" prefix to be picked up by the vault storage provider + "mount_point": "/vault/projects", + "path_template": "/vault/projects/{{.Space.Name}}", + }, + }, + } + } + return rules } diff --git a/services/graph/pkg/config/config.go b/services/graph/pkg/config/config.go index cd42dc59fb9..eb46544e2a0 100644 --- a/services/graph/pkg/config/config.go +++ b/services/graph/pkg/config/config.go @@ -39,6 +39,8 @@ type Config struct { Validation Validation `yaml:"validation"` + EnableVaultMode bool `yaml:"enable_vault_mode" env:"OCIS_ENABLE_VAULT_MODE;GRAPH_ENABLE_VAULT_MODE" desc:"Enable vault mode in addition to the regular graph service. This only applies when the additional storage-users-vault service is running, which is a special configured storage-users service." introductionVersion:"Deledda"` + Context context.Context `yaml:"-"` } @@ -50,6 +52,7 @@ type Spaces struct { UsersCacheTTL int `yaml:"users_cache_ttl" env:"GRAPH_SPACES_USERS_CACHE_TTL" desc:"Max TTL in seconds for the spaces users cache." introductionVersion:"pre5.0"` GroupsCacheTTL int `yaml:"groups_cache_ttl" env:"GRAPH_SPACES_GROUPS_CACHE_TTL" desc:"Max TTL in seconds for the spaces groups cache." introductionVersion:"pre5.0"` StorageUsersAddress string `yaml:"storage_users_address" env:"GRAPH_SPACES_STORAGE_USERS_ADDRESS" desc:"The address of the storage-users service." introductionVersion:"5.0"` + StorageUsersVaultAddress string `yaml:"storage_users_vault_address" env:"GRAPH_SPACES_STORAGE_USERS_VAULT_ADDRESS" desc:"The address of the storage-users-vault service, a special configured storage-users service. Applicable only when 'GRAPH_ENABLE_VAULT_MODE' is enabled." introductionVersion:"Deledda"` DefaultLanguage string `yaml:"default_language" env:"OCIS_DEFAULT_LANGUAGE" desc:"The default language used by services and the WebUI. If not defined, English will be used as default. See the documentation for more details." introductionVersion:"5.0"` TranslationPath string `yaml:"translation_path" env:"OCIS_TRANSLATION_PATH;GRAPH_TRANSLATION_PATH" desc:"(optional) Set this to a path with custom translations to overwrite the builtin translations. Note that file and folder naming rules apply, see the documentation for more details." introductionVersion:"7.0.0"` } diff --git a/services/graph/pkg/config/defaults/defaultconfig.go b/services/graph/pkg/config/defaults/defaultconfig.go index de736db6883..10c9a056a64 100644 --- a/services/graph/pkg/config/defaults/defaultconfig.go +++ b/services/graph/pkg/config/defaults/defaultconfig.go @@ -69,10 +69,11 @@ func DefaultConfig() *config.Config { }, Reva: shared.DefaultRevaConfig(), Spaces: config.Spaces{ - StorageUsersAddress: "com.owncloud.api.storage-users", - WebDavBase: "https://localhost:9200", - WebDavPath: "/dav/spaces/", - DefaultQuota: "1000000000", + StorageUsersAddress: "com.owncloud.api.storage-users", + StorageUsersVaultAddress: "com.owncloud.api.storage-users-vault", + WebDavBase: "https://localhost:9200", + WebDavPath: "/dav/spaces/", + DefaultQuota: "1000000000", // 1 minute ExtendedSpacePropertiesCacheTTL: 60, // 1 minute diff --git a/services/graph/pkg/middleware/auth.go b/services/graph/pkg/middleware/auth.go index 3e382ec8d17..6eaf2348f27 100644 --- a/services/graph/pkg/middleware/auth.go +++ b/services/graph/pkg/middleware/auth.go @@ -93,6 +93,10 @@ func Auth(opts ...account.Option) func(http.Handler) http.Handler { ctx = metadata.AppendToOutgoingContext(ctx, ctxpkg.InitiatorHeader, initiatorID) } + // Propagate MFA status to outgoing gRPC metadata so that services protected + // by the mfa interceptor (e.g. storage-users-vault) can enforce MFA at the gRPC layer. + ctx = ctxpkg.AppendMFAToOutgoingContext(ctx, mfa.Has(ctx)) + next.ServeHTTP(w, r.WithContext(ctx)) }) } diff --git a/services/graph/pkg/middleware/mfa.go b/services/graph/pkg/middleware/mfa.go new file mode 100644 index 00000000000..33c1206e09b --- /dev/null +++ b/services/graph/pkg/middleware/mfa.go @@ -0,0 +1,23 @@ +package middleware + +import ( + "net/http" + + "github.com/owncloud/ocis/v2/ocis-pkg/log" + "github.com/owncloud/ocis/v2/ocis-pkg/mfa" +) + +// RequireMFA middleware is used to require the user in context to have MFA satisfied +func RequireMFA(logger log.Logger) func(next http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !mfa.Has(r.Context()) { + l := logger.SubloggerWithRequestID(r.Context()) + l.Error().Str("path", r.URL.Path).Msg("MFA required but not satisfied") + mfa.SetRequiredStatus(w) + return + } + next.ServeHTTP(w, r) + }) + } +} diff --git a/services/graph/pkg/middleware/vault.go b/services/graph/pkg/middleware/vault.go new file mode 100644 index 00000000000..687cd8b8b53 --- /dev/null +++ b/services/graph/pkg/middleware/vault.go @@ -0,0 +1,30 @@ +package middleware + +import ( + "context" + "net/http" +) + +type key int + +const vaultModeKey key = iota + +// SetVaultMode sets the vault mode in the context. +func SetVaultMode(ctx context.Context, enabled bool) context.Context { + return context.WithValue(ctx, vaultModeKey, enabled) +} + +// IsVaultMode checks if the vault mode is enabled in the context. +func IsVaultMode(ctx context.Context) bool { + val, ok := ctx.Value(vaultModeKey).(bool) + return val && ok +} + +// VaultModeMiddleware is a middleware that sets the vault mode in the context. +func VaultModeMiddleware() func(next http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next.ServeHTTP(w, r.WithContext(SetVaultMode(r.Context(), true))) + }) + } +} diff --git a/services/graph/pkg/service/v0/driveitems.go b/services/graph/pkg/service/v0/driveitems.go index 2a134500cab..73b101b52a4 100644 --- a/services/graph/pkg/service/v0/driveitems.go +++ b/services/graph/pkg/service/v0/driveitems.go @@ -30,6 +30,7 @@ import ( "github.com/owncloud/ocis/v2/ocis-pkg/log" "github.com/owncloud/ocis/v2/services/graph/pkg/errorcode" + "github.com/owncloud/ocis/v2/services/graph/pkg/middleware" ) // CreateUploadSession create an upload session to allow your app to upload files up to the maximum file size. @@ -154,13 +155,19 @@ func (g Graph) GetRootDriveChildren(w http.ResponseWriter, r *http.Request) { currentUser := revactx.ContextMustGetUser(r.Context()) // do we need to list all or only the personal drive - filters := []*storageprovider.ListStorageSpacesRequest_Filter{} - filters = append(filters, listStorageSpacesUserFilter(currentUser.GetId().GetOpaqueId())) - filters = append(filters, listStorageSpacesTypeFilter("personal")) + listReq := &storageprovider.ListStorageSpacesRequest{ + Filters: []*storageprovider.ListStorageSpacesRequest_Filter{ + listStorageSpacesUserFilter(currentUser.GetId().GetOpaqueId()), + listStorageSpacesTypeFilter("personal"), + }, + } - res, err := gatewayClient.ListStorageSpaces(ctx, &storageprovider.ListStorageSpacesRequest{ - Filters: filters, - }) + // force vault storage space if vault mode is enabled + if middleware.IsVaultMode(ctx) { + listReq.Opaque = utils.AppendPlainToOpaque(listReq.Opaque, "storage_id", utils.VaultStorageProviderID) + } + + res, err := gatewayClient.ListStorageSpaces(ctx, listReq) switch { case err != nil: g.logger.Error().Err(err).Msg("error making ListStorageSpaces grpc call") diff --git a/services/graph/pkg/service/v0/driveitems_test.go b/services/graph/pkg/service/v0/driveitems_test.go index 4cbe4769097..07168dee2a3 100644 --- a/services/graph/pkg/service/v0/driveitems_test.go +++ b/services/graph/pkg/service/v0/driveitems_test.go @@ -30,6 +30,7 @@ import ( "github.com/owncloud/ocis/v2/services/graph/pkg/config" "github.com/owncloud/ocis/v2/services/graph/pkg/config/defaults" identitymocks "github.com/owncloud/ocis/v2/services/graph/pkg/identity/mocks" + graphmw "github.com/owncloud/ocis/v2/services/graph/pkg/middleware" service "github.com/owncloud/ocis/v2/services/graph/pkg/service/v0" ) @@ -197,6 +198,43 @@ var _ = Describe("Driveitems", func() { }) }) + Describe("GetRootDriveChildren vault mode filter", func() { + It("does not set storage_id opaque in normal mode", func() { + var captured *provider.ListStorageSpacesRequest + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.MatchedBy(func(req *provider.ListStorageSpacesRequest) bool { + captured = req + return true + })).Return(&provider.ListStorageSpacesResponse{ + Status: status.NewNotFound(ctx, "not found"), + }, nil).Once() + + r := httptest.NewRequest(http.MethodGet, "/graph/v1.0/me/drive/root/children", nil) + r = r.WithContext(revactx.ContextSetUser(ctx, currentUser)) + svc.GetRootDriveChildren(rr, r) + + Expect(captured).ToNot(BeNil()) + Expect(captured.GetOpaque().GetMap()).ToNot(HaveKey("storage_id")) + }) + + It("sets storage_id opaque to VaultStorageProviderID in vault mode", func() { + var captured *provider.ListStorageSpacesRequest + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.MatchedBy(func(req *provider.ListStorageSpacesRequest) bool { + captured = req + return true + })).Return(&provider.ListStorageSpacesResponse{ + Status: status.NewNotFound(ctx, "not found"), + }, nil).Once() + + r := httptest.NewRequest(http.MethodGet, "/vault/graph/v1.0/me/drive/root/children", nil) + r = r.WithContext(graphmw.SetVaultMode(revactx.ContextSetUser(ctx, currentUser), true)) + svc.GetRootDriveChildren(rr, r) + + Expect(captured).ToNot(BeNil()) + Expect(captured.GetOpaque().GetMap()).To(HaveKey("storage_id")) + Expect(string(captured.GetOpaque().GetMap()["storage_id"].Value)).To(Equal(utils.VaultStorageProviderID)) + }) + }) + Describe("GetDriveItemChildren", func() { It("handles ListContainer not found", func() { gatewayClient.On("ListContainer", mock.Anything, mock.Anything).Return(&provider.ListContainerResponse{ diff --git a/services/graph/pkg/service/v0/drives.go b/services/graph/pkg/service/v0/drives.go index c4657b32054..d80d5a11fa5 100644 --- a/services/graph/pkg/service/v0/drives.go +++ b/services/graph/pkg/service/v0/drives.go @@ -29,10 +29,10 @@ import ( "google.golang.org/protobuf/proto" "github.com/owncloud/ocis/v2/ocis-pkg/l10n" - "github.com/owncloud/ocis/v2/ocis-pkg/mfa" v0 "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" + "github.com/owncloud/ocis/v2/services/graph/pkg/middleware" settingsServiceExt "github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults" ) @@ -133,13 +133,6 @@ 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) - return - } - spaces, errCode := g.getDrives(r, true, APIVersion_1) if errCode != nil { errorcode.RenderError(w, r, errCode) @@ -160,13 +153,6 @@ 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) - return - } - drives, errCode := g.getDrives(r, true, APIVersion_1_Beta_1) if errCode != nil { errorcode.RenderError(w, r, errCode) @@ -437,6 +423,11 @@ func (g Graph) createDrive(w http.ResponseWriter, r *http.Request, apiVersion AP csr.Owner = us } + // force vault storage space if vault mode is enabled + if middleware.IsVaultMode(ctx) { + csr.Opaque = utils.AppendPlainToOpaque(csr.Opaque, "storage_id", utils.VaultStorageProviderID) + } + resp, err := gatewayClient.CreateStorageSpace(ctx, &csr) if err != nil { logger.Error().Err(err).Msg("could not create drive: transport error") @@ -762,6 +753,7 @@ func (g Graph) ListStorageSpacesWithFilters(ctx context.Context, filters []*stor if err != nil { return nil, err } + lReq := &storageprovider.ListStorageSpacesRequest{ Opaque: &types.Opaque{Map: map[string]*types.OpaqueEntry{ "permissions": { @@ -776,6 +768,11 @@ func (g Graph) ListStorageSpacesWithFilters(ctx context.Context, filters []*stor Filters: filters, } + // force vault storage space if vault mode is enabled + if middleware.IsVaultMode(ctx) { + lReq.Opaque = utils.AppendPlainToOpaque(lReq.Opaque, "storage_id", utils.VaultStorageProviderID) + } + gatewayClient, err := g.gatewaySelector.Next() if err != nil { return nil, err diff --git a/services/graph/pkg/service/v0/graph_test.go b/services/graph/pkg/service/v0/graph_test.go index 1112dacb2bd..f8c58e4b6cc 100644 --- a/services/graph/pkg/service/v0/graph_test.go +++ b/services/graph/pkg/service/v0/graph_test.go @@ -113,7 +113,7 @@ var _ = Describe("Graph", func() { r := httptest.NewRequest(http.MethodGet, "/graph/v1.0/me/drives", nil) r = r.WithContext(ctx) rr := httptest.NewRecorder() - svc.GetDrivesV1(rr, r) + svc.ServeHTTP(rr, r) Expect(rr.Code).To(Equal(http.StatusOK)) }) @@ -126,7 +126,7 @@ var _ = Describe("Graph", func() { r := httptest.NewRequest(http.MethodGet, "/graph/v1.0/drives", nil) r = r.WithContext(mfa.Set(ctx, true)) rr := httptest.NewRecorder() - svc.GetAllDrivesV1(rr, r) + svc.ServeHTTP(rr, r) Expect(rr.Code).To(Equal(http.StatusOK)) }) @@ -138,7 +138,7 @@ var _ = Describe("Graph", func() { r := httptest.NewRequest(http.MethodGet, "/graph/v1.0/drives", nil) rr := httptest.NewRecorder() - svc.GetAllDrivesV1(rr, r) + svc.ServeHTTP(rr, r) Expect(rr.Code).To(Equal(http.StatusForbidden)) Expect(rr.Header().Get("X-Ocis-Mfa-Required")).To(Equal("true")) }) diff --git a/services/graph/pkg/service/v0/service.go b/services/graph/pkg/service/v0/service.go index 0078756407c..9e241058a6b 100644 --- a/services/graph/pkg/service/v0/service.go +++ b/services/graph/pkg/service/v0/service.go @@ -223,9 +223,8 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx return svc, err } - m.Route(options.Config.HTTP.Root, func(r chi.Router) { + graphRoutes := func(r chi.Router, drivesRequireMFA func(http.Handler) http.Handler) { r.Use(middleware.StripSlashes) - r.Route("/v1beta1", func(r chi.Router) { r.Route("/me", func(r chi.Router) { r.Get("/drives", svc.GetDrives(APIVersion_1_Beta_1)) @@ -235,7 +234,7 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx }) }) r.Route("/drives", func(r chi.Router) { - r.Get("/", svc.GetAllDrives(APIVersion_1_Beta_1)) + r.With(drivesRequireMFA).Get("/", svc.GetAllDrives(APIVersion_1_Beta_1)) r.Post("/", svc.CreateDriveV1Beta1) r.Route("/{driveID}", func(r chi.Router) { r.Get("/", svc.GetSingleDriveV1Beta1) @@ -331,7 +330,7 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx }) }) r.Route("/drives", func(r chi.Router) { - r.Get("/", svc.GetAllDrives(APIVersion_1)) + r.With(drivesRequireMFA).Get("/", svc.GetAllDrives(APIVersion_1)) r.Post("/", svc.CreateDrive) r.Route("/{driveID}", func(r chi.Router) { r.Patch("/", svc.UpdateDrive) @@ -394,8 +393,24 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx }) }) }) + } + + requireMFA := graphm.RequireMFA(options.Logger) + blankMW := func(next http.Handler) http.Handler { return next } + + m.Route(options.Config.HTTP.Root, func(r chi.Router) { + graphRoutes(r, requireMFA) }) + // Initialize the Vault routes + if options.Config.EnableVaultMode { + m.Route("/vault/graph", func(r chi.Router) { + r.Use(requireMFA) + r.Use(graphm.VaultModeMiddleware()) + graphRoutes(r, blankMW) + }) + } + _ = chi.Walk(m, func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { options.Logger.Debug().Str("method", method).Str("route", route).Int("middlewares", len(middlewares)).Msg("serving endpoint") return nil diff --git a/services/graph/pkg/service/v0/sharedbyme.go b/services/graph/pkg/service/v0/sharedbyme.go index 0daf1fa2e6d..3666696ca8e 100644 --- a/services/graph/pkg/service/v0/sharedbyme.go +++ b/services/graph/pkg/service/v0/sharedbyme.go @@ -5,8 +5,11 @@ import ( "github.com/go-chi/render" libregraph "github.com/owncloud/libre-graph-api-go" + "github.com/owncloud/reva/v2/pkg/storagespace" + "github.com/owncloud/reva/v2/pkg/utils" "github.com/owncloud/ocis/v2/services/graph/pkg/errorcode" + "github.com/owncloud/ocis/v2/services/graph/pkg/middleware" ) type driveItemsByResourceID map[string]libregraph.DriveItem @@ -39,8 +42,15 @@ func (g Graph) GetSharedByMe(w http.ResponseWriter, r *http.Request) { } res := make([]libregraph.DriveItem, 0, len(driveItems)) + isVault := middleware.IsVaultMode(ctx) for _, v := range driveItems { - res = append(res, v) + storageID, _ := storagespace.SplitStorageID(v.GetId()) + // filters out shares that are not relevant to the current mode (vault or regular). + if isVault && storageID == utils.VaultStorageProviderID { + res = append(res, v) + } else if !isVault && storageID != utils.VaultStorageProviderID { + res = append(res, v) + } } render.Status(r, http.StatusOK) diff --git a/services/graph/pkg/service/v0/sharedwithme.go b/services/graph/pkg/service/v0/sharedwithme.go index 0a51d8b0880..a25ffadd702 100644 --- a/services/graph/pkg/service/v0/sharedwithme.go +++ b/services/graph/pkg/service/v0/sharedwithme.go @@ -8,8 +8,10 @@ import ( ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" "github.com/go-chi/render" libregraph "github.com/owncloud/libre-graph-api-go" + "github.com/owncloud/reva/v2/pkg/utils" "github.com/owncloud/ocis/v2/services/graph/pkg/errorcode" + "github.com/owncloud/ocis/v2/services/graph/pkg/middleware" "github.com/owncloud/ocis/v2/services/graph/pkg/unifiedrole" ) @@ -40,6 +42,9 @@ func (g Graph) listSharedWithMe(ctx context.Context) ([]libregraph.DriveItem, er g.logger.Error().Err(err).Msg("listing shares failed") return nil, err } + + listReceivedSharesResponse.Shares = filterVaultShares(ctx, listReceivedSharesResponse.GetShares()) + availableRoles := unifiedrole.GetRoles(unifiedrole.RoleFilterIDs(g.config.UnifiedRoles.AvailableRoles...)) driveItems, err := cs3ReceivedSharesToDriveItems(ctx, g.logger, gatewayClient, g.identityCache, listReceivedSharesResponse.GetShares(), availableRoles) if err != nil { @@ -63,3 +68,17 @@ func (g Graph) listSharedWithMe(ctx context.Context) ([]libregraph.DriveItem, er return driveItems, err } + +// filterVaultShares filters out shares that are not relevant to the current mode (vault or regular). +func filterVaultShares(ctx context.Context, shares []*collaboration.ReceivedShare) []*collaboration.ReceivedShare { + result := make([]*collaboration.ReceivedShare, 0, len(shares)) + isVault := middleware.IsVaultMode(ctx) + for _, share := range shares { + if isVault && share.GetShare().GetResourceId().StorageId == utils.VaultStorageProviderID { + result = append(result, share) + } else if !isVault && share.GetShare().GetResourceId().StorageId != utils.VaultStorageProviderID { + result = append(result, share) + } + } + return result +} diff --git a/services/graph/pkg/service/v0/spacetemplates.go b/services/graph/pkg/service/v0/spacetemplates.go index 05b7ad02461..9fe55493f36 100644 --- a/services/graph/pkg/service/v0/spacetemplates.go +++ b/services/graph/pkg/service/v0/spacetemplates.go @@ -13,6 +13,7 @@ import ( v1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" "github.com/owncloud/ocis/v2/ocis-pkg/l10n" l10n_pkg "github.com/owncloud/ocis/v2/services/graph/pkg/l10n" + "github.com/owncloud/ocis/v2/services/graph/pkg/middleware" "github.com/owncloud/reva/v2/pkg/storage/utils/metadata" "github.com/owncloud/reva/v2/pkg/storagespace" "github.com/owncloud/reva/v2/pkg/utils" @@ -53,7 +54,11 @@ func (g Graph) applySpaceTemplate(ctx context.Context, gwc gateway.GatewayAPICli } func (g Graph) applyDefaultTemplate(ctx context.Context, gwc gateway.GatewayAPIClient, root *storageprovider.ResourceId, locale string) error { - mdc := metadata.NewCS3(g.config.Reva.Address, g.config.Spaces.StorageUsersAddress) + storageUsersAddress := g.config.Spaces.StorageUsersAddress + if g.config.EnableVaultMode && middleware.IsVaultMode(ctx) { + storageUsersAddress = g.config.Spaces.StorageUsersVaultAddress + } + mdc := metadata.NewCS3(g.config.Reva.Address, storageUsersAddress) mdc.SpaceRoot = root var opaque *v1beta1.Opaque diff --git a/services/policies/pkg/service/event/service.go b/services/policies/pkg/service/event/service.go index 69f035eebd2..defbd60fa14 100644 --- a/services/policies/pkg/service/event/service.go +++ b/services/policies/pkg/service/event/service.go @@ -125,6 +125,7 @@ func (s Service) processEvent(e events.Event) error { if err := events.Publish(ctx, s.stream, events.PostprocessingStepFinished{ Outcome: outcome, UploadID: ev.UploadID, + ResourceID: ev.ResourceID, ExecutingUser: ev.ExecutingUser, Filename: ev.Filename, FinishedStep: ev.StepToStart, diff --git a/services/postprocessing/pkg/postprocessing/postprocessing.go b/services/postprocessing/pkg/postprocessing/postprocessing.go index aca4ea3e86d..d067dcbe34b 100644 --- a/services/postprocessing/pkg/postprocessing/postprocessing.go +++ b/services/postprocessing/pkg/postprocessing/postprocessing.go @@ -119,6 +119,7 @@ func (pp *Postprocessing) finished(outcome events.PostprocessingOutcome) events. UploadID: pp.ID, ExecutingUser: pp.User, Filename: pp.Filename, + ResourceID: pp.ResourceID, Outcome: outcome, ImpersonatingUser: pp.ImpersonatingUser, } diff --git a/services/proxy/pkg/command/server.go b/services/proxy/pkg/command/server.go index 95e6cb6e641..317da53da35 100644 --- a/services/proxy/pkg/command/server.go +++ b/services/proxy/pkg/command/server.go @@ -357,7 +357,7 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config, middleware.EventsPublisher(publisher), middleware.MultiInstance(cfg.MultiInstance.Enabled, cfg.MultiInstance.InstanceID, cfg.MultiInstance.MasterID, cfg.MultiInstance.MemberClaim, cfg.MultiInstance.GuestClaim, cfg.MultiInstance.GuestRole), ), - middleware.MultiFactor(cfg.MultiFactorAuthentication, middleware.Logger(logger)), + middleware.MultiFactor(cfg.MultiFactorAuthentication, middleware.Logger(logger), middleware.MFAStore(signingKeyStore)), middleware.SelectorCookie( middleware.Logger(logger), middleware.PolicySelectorConfig(*cfg.PolicySelector), @@ -373,6 +373,7 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config, middleware.Logger(logger), middleware.WithRevaGatewaySelector(gatewaySelector), middleware.RoleQuotas(cfg.RoleQuotas), + middleware.EnableVaultMode(cfg.EnableVaultMode), ), // trigger space assignment when a user logs in middleware.SpaceManager( diff --git a/services/proxy/pkg/config/config.go b/services/proxy/pkg/config/config.go index 43f3a57b8a2..acb23ec15fe 100644 --- a/services/proxy/pkg/config/config.go +++ b/services/proxy/pkg/config/config.go @@ -48,6 +48,7 @@ type Config struct { ClaimSpaceManagement ClaimSpaceManagement `yaml:"claim_space_management"` MultiFactorAuthentication MFAConfig `yaml:"mfa"` MultiInstance MultiInstanceConfig `yaml:"multi_instance"` + EnableVaultMode bool `yaml:"enable_vault_mode" env:"OCIS_ENABLE_VAULT_MODE;PROXY_ENABLE_VAULT_MODE" desc:"Set this to true to automatically create a new vault home for the user if it does not exist. Only applicapable if the storage-users-vault service, a special configured storage-users service is configured." introductionVersion:"Deledda"` Context context.Context `json:"-" yaml:"-"` } diff --git a/services/proxy/pkg/config/defaults/defaultconfig.go b/services/proxy/pkg/config/defaults/defaultconfig.go index 820590f6f29..a1a97b454f1 100644 --- a/services/proxy/pkg/config/defaults/defaultconfig.go +++ b/services/proxy/pkg/config/defaults/defaultconfig.go @@ -273,6 +273,10 @@ func DefaultPolicies() []config.Policy { Endpoint: "/graph/", Service: "com.owncloud.web.graph", }, + { + Endpoint: "/vault/graph/", + Service: "com.owncloud.web.graph", + }, { Endpoint: "/api/v0/settings", Service: "com.owncloud.web.settings", diff --git a/services/proxy/pkg/middleware/create_home.go b/services/proxy/pkg/middleware/create_home.go index 4caf453ef31..d9aed0b942f 100644 --- a/services/proxy/pkg/middleware/create_home.go +++ b/services/proxy/pkg/middleware/create_home.go @@ -10,9 +10,12 @@ import ( rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/owncloud/ocis/v2/ocis-pkg/log" + "github.com/owncloud/ocis/v2/ocis-pkg/mfa" "github.com/owncloud/ocis/v2/services/graph/pkg/errorcode" + ctxpkg "github.com/owncloud/reva/v2/pkg/ctx" revactx "github.com/owncloud/reva/v2/pkg/ctx" "github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool" + "github.com/owncloud/reva/v2/pkg/storagespace" "github.com/owncloud/reva/v2/pkg/utils" "google.golang.org/grpc/metadata" ) @@ -28,6 +31,7 @@ func CreateHome(optionSetters ...Option) func(next http.Handler) http.Handler { logger: logger, revaGatewaySelector: options.RevaGatewaySelector, roleQuotas: options.RoleQuotas, + enableVaultMode: options.EnableVaultMode, cache: sync.Map{}, } } @@ -38,6 +42,7 @@ type createHome struct { logger log.Logger revaGatewaySelector pool.Selectable[gateway.GatewayAPIClient] roleQuotas map[string]uint64 + enableVaultMode bool cache sync.Map // Store users for which personal space has been in memory indefinitely. Persistence isn't critical. } @@ -50,21 +55,23 @@ func (m *createHome) ServeHTTP(w http.ResponseWriter, req *http.Request) { token := req.Header.Get("x-access-token") // we need to pass the token to authenticate the CreateHome request. - //ctx := tokenpkg.ContextSetToken(r.Context(), token) ctx := metadata.AppendToOutgoingContext(req.Context(), revactx.TokenHeader, token) createHomeReq := &provider.CreateHomeRequest{} u, ok := revactx.ContextGetUser(ctx) - if ok { - roleIDs, err := m.getUserRoles(u) - if err != nil { - m.logger.Error().Err(err).Str("userid", u.Id.OpaqueId).Msg("failed to get roles for user") - errorcode.GeneralException.Render(w, req, http.StatusInternalServerError, "Unauthorized") - return - } - if limit, hasLimit := m.checkRoleQuotaLimit(roleIDs); hasLimit { - createHomeReq.Opaque = utils.AppendPlainToOpaque(nil, "quota", strconv.FormatUint(limit, 10)) - } + if !ok || u == nil { + m.logger.Error().Msg("no user in context") + m.next.ServeHTTP(w, req) + return + } + roleIDs, err := m.getUserRoles(u) + if err != nil { + m.logger.Error().Err(err).Str("userid", u.Id.OpaqueId).Msg("failed to get roles for user") + errorcode.GeneralException.Render(w, req, http.StatusInternalServerError, "Unauthorized") + return + } + if limit, hasLimit := m.checkRoleQuotaLimit(roleIDs); hasLimit { + createHomeReq.Opaque = utils.AppendPlainToOpaque(nil, "quota", strconv.FormatUint(limit, 10)) } client, err := m.revaGatewaySelector.Next() @@ -87,6 +94,33 @@ func (m *createHome) ServeHTTP(w http.ResponseWriter, req *http.Request) { m.logger.Error().Interface("userID", u.GetId().GetOpaqueId()).Interface("status", createHomeRes.GetStatus()).Msg("personal space creation failed") } } + + // TODO Perekhod: Create the vault home based on User permission + if m.enableVaultMode && mfa.IsMFAHeaderTrue(req) { + // Force MFA=true for vault home creation + vctx := metadata.AppendToOutgoingContext(ctx, ctxpkg.MFAOutgoingHeader, "true") + + vaultKey := storagespace.FormatStorageID(utils.VaultStorageProviderID, u.GetId().GetOpaqueId()) + if _, exists := m.cache.Load(vaultKey); !exists { + // Create vault personal space + // Inject storage_id into opaque for vault personal space + createHomeReq.Opaque = utils.AppendPlainToOpaque(createHomeReq.Opaque, "storage_id", utils.VaultStorageProviderID) + + cpsRes, err := client.CreateHome(vctx, createHomeReq) + switch { + case err != nil: + m.logger.Err(err).Msg("error calling CreateHome for vault personal") + case cpsRes.GetStatus().GetCode() == rpc.Code_CODE_OK: + m.logger.Debug().Interface("userID", u.GetId().GetOpaqueId()).Msg("vault personal space created") + m.cache.Store(vaultKey, struct{}{}) + case cpsRes.GetStatus().GetCode() == rpc.Code_CODE_ALREADY_EXISTS: + m.logger.Info().Interface("userID", u.GetId().GetOpaqueId()).Interface("status", cpsRes.GetStatus()).Msg("vault personal space already exists") + m.cache.Store(vaultKey, struct{}{}) + default: + m.logger.Error().Interface("userID", u.GetId().GetOpaqueId()).Interface("status", cpsRes.GetStatus()).Msg("vault personal space creation failed") + } + } + } } m.next.ServeHTTP(w, req) diff --git a/services/proxy/pkg/middleware/mfa.go b/services/proxy/pkg/middleware/mfa.go index f41c0b97019..26665419d10 100644 --- a/services/proxy/pkg/middleware/mfa.go +++ b/services/proxy/pkg/middleware/mfa.go @@ -2,6 +2,10 @@ package middleware import ( "net/http" + "time" + + revactx "github.com/owncloud/reva/v2/pkg/ctx" + microstore "go-micro.dev/v4/store" "github.com/owncloud/ocis/v2/ocis-pkg/log" "github.com/owncloud/ocis/v2/ocis-pkg/mfa" @@ -9,6 +13,11 @@ import ( "github.com/owncloud/ocis/v2/services/proxy/pkg/config" ) +// mfaStoreTTL is how long a verified MFA status is remembered for non-OIDC +// requests (e.g. signed-URL archiver downloads). It should be at least as +// long as the signed-URL expiry (OC-Expires). Default: 1 hour. +const mfaStoreTTL = time.Hour + // MultiFactor returns a middleware that checks requests for mfa func MultiFactor(cfg config.MFAConfig, opts ...Option) func(next http.Handler) http.Handler { options := newOptions(opts...) @@ -20,6 +29,7 @@ func MultiFactor(cfg config.MFAConfig, opts ...Option) func(next http.Handler) h logger: logger, enabled: cfg.Enabled, authLevelNames: cfg.AuthLevelNames, + store: options.MFAStore, } } } @@ -30,6 +40,10 @@ type MultiFactorAuthentication struct { logger log.Logger enabled bool authLevelNames []string + // store persists verified MFA status so that non-OIDC requests (e.g. + // signed-URL archiver downloads) can inherit it from the user's most + // recent OIDC session. Nil when no store is configured. + store microstore.Store } // ServeHTTP adds the mfa header if the request contains a valid mfa token @@ -49,10 +63,32 @@ func (m MultiFactorAuthentication) ServeHTTP(w http.ResponseWriter, req *http.Re claims := oidc.FromContext(req.Context()) + if claims == nil { + // No OIDC claims — request was authenticated via a non-OIDC method + // (e.g. signed URL, basic auth, app token). MFA cannot be determined + // from claims directly. + // + // Fall back to the persisted MFA status from the user's most recent + // OIDC-authenticated session. This allows, for example, a signed-URL + // archiver download to succeed when the user has recently proven MFA + // in their browser session. + if m.store != nil { + if u, ok := revactx.ContextGetUser(req.Context()); ok && u.GetId().GetOpaqueId() != "" { + if m.readMFAFromStore(u.GetId().GetOpaqueId()) { + mfa.SetHeader(req, true) + m.logger.Debug().Str("path", req.URL.Path).Msg("MFA status restored from store for non-OIDC request") + return + } + } + } + m.logger.Debug().Str("path", req.URL.Path).Msg("no OIDC claims in context, skipping MFA check") + return + } + // acr is a standard OIDC claim. value, err := oidc.ReadStringClaim("acr", claims) if err != nil { - m.logger.Error().Str("path", req.URL.Path).Interface("required", m.authLevelNames).Err(err).Interface("claims", claims).Msg("no acr claim found in access token") + m.logger.Debug().Str("path", req.URL.Path).Interface("required", m.authLevelNames).Err(err).Msg("acr claim not set in access token") return } @@ -63,6 +99,34 @@ func (m MultiFactorAuthentication) ServeHTTP(w http.ResponseWriter, req *http.Re mfa.SetHeader(req, true) m.logger.Debug().Str("acr", value).Str("url", req.URL.Path).Msg("mfa authenticated") + + // Persist the verified MFA status so that subsequent non-OIDC requests + // (e.g. signed-URL archiver downloads) can inherit it. The entry is + // refreshed on every successful OIDC MFA verification and expires after + // mfaStoreTTL if no further OIDC requests are made. + if m.store != nil { + if u, ok := revactx.ContextGetUser(req.Context()); ok && u.GetId().GetOpaqueId() != "" { + m.writeMFAToStore(u.GetId().GetOpaqueId()) + } + } +} + +func (m MultiFactorAuthentication) readMFAFromStore(userID string) bool { + records, err := m.store.Read(key(userID)) + if err != nil || len(records) == 0 { + return false + } + return string(records[0].Value) == "true" +} + +func (m MultiFactorAuthentication) writeMFAToStore(userID string) { + if err := m.store.Write(µstore.Record{ + Key: key(userID), + Value: []byte("true"), + Expiry: mfaStoreTTL, + }); err != nil { + m.logger.Error().Err(err).Str("userID", userID).Msg("failed to write MFA status to store") + } } // containsMFA checks if the given value is in the list of authentication level names @@ -74,3 +138,7 @@ func (m MultiFactorAuthentication) containsMFA(value string) bool { } return false } + +func key(userID string) string { + return "mfa:" + userID +} diff --git a/services/proxy/pkg/middleware/options.go b/services/proxy/pkg/middleware/options.go index 5dc24b9720f..ed3f23ca7db 100644 --- a/services/proxy/pkg/middleware/options.go +++ b/services/proxy/pkg/middleware/options.go @@ -59,6 +59,10 @@ type Options struct { DefaultAccessTokenTTL time.Duration // UserInfoCache sets the access token cache store UserInfoCache store.Store + // MFAStore is used to persist verified MFA status so that non-OIDC + // requests (e.g. signed-URL archiver downloads) can inherit the status + // from the user's most recent OIDC-authenticated session. + MFAStore store.Store // CredentialsByUserAgent sets the auth challenges on a per user-agent basis CredentialsByUserAgent map[string]string // AccessTokenVerifyMethod configures how access_tokens should be verified but the oidc_auth middleware. @@ -69,6 +73,8 @@ type Options struct { // RoleQuotas hold userid:quota mappings. These will be used when provisioning new users. // The users will get as much quota as is set for their role. RoleQuotas map[string]uint64 + // EnableVaultMode creates a new vault home for the user if it does not exist. + EnableVaultMode bool // TraceProvider sets the tracing provider. TraceProvider trace.TracerProvider // SkipUserInfo prevents the oidc middleware from querying the userinfo endpoint and read any claims directly from the access token instead @@ -216,6 +222,13 @@ func UserInfoCache(val store.Store) Option { } } +// MFAStore provides a function to set the MFA session store. +func MFAStore(val store.Store) Option { + return func(o *Options) { + o.MFAStore = val + } +} + // UserProvider sets the accounts user provider func UserProvider(up backend.UserBackend) Option { return func(o *Options) { @@ -244,6 +257,13 @@ func RoleQuotas(roleQuotas map[string]uint64) Option { } } +// EnableVaultMode sets the enable vault mode flag +func EnableVaultMode(enableVaultMode bool) Option { + return func(o *Options) { + o.EnableVaultMode = enableVaultMode + } +} + // TraceProvider sets the tracing provider. func TraceProvider(tp trace.TracerProvider) Option { return func(o *Options) { diff --git a/services/search/pkg/search/search.go b/services/search/pkg/search/search.go index 6c45f9c7a80..bcbd846cec4 100644 --- a/services/search/pkg/search/search.go +++ b/services/search/pkg/search/search.go @@ -21,6 +21,7 @@ import ( ) var scopeRegex = regexp.MustCompile(`scope:\s*([^" "\n\r]*)`) +var vaultRegex = regexp.MustCompile(`vault:\s*(\S+)`) // ResolveReference makes sure the path is relative to the space root func ResolveReference(ctx context.Context, ref *provider.Reference, ri *provider.ResourceInfo, gatewaySelector pool.Selectable[gateway.GatewayAPIClient]) (*provider.Reference, error) { @@ -149,6 +150,17 @@ func convertToWebDAVPermissions(isShared, isMountpoint, isDir bool, p *provider. return b.String() } +// ParseVaultMode extracts "vault:" from the query string and returns the +// cleaned query and whether vault mode was requested (value == "true"). +func ParseVaultMode(query string) (string, bool) { + match := vaultRegex.FindStringSubmatch(query) + if len(match) < 2 { + return query, false + } + cleaned := strings.TrimSpace(strings.ReplaceAll(query, match[0], "")) + return cleaned, match[1] == "true" +} + // ParseScope extract a scope value from the query string and returns search, scope strings func ParseScope(query string) (string, string) { match := scopeRegex.FindStringSubmatch(query) diff --git a/services/search/pkg/search/service.go b/services/search/pkg/search/service.go index 08f9b408fbd..ee5fd98007b 100644 --- a/services/search/pkg/search/service.go +++ b/services/search/pkg/search/service.go @@ -25,10 +25,12 @@ import ( "github.com/owncloud/reva/v2/pkg/tags" "github.com/owncloud/reva/v2/pkg/utils" "golang.org/x/sync/errgroup" + grpcmetadata "google.golang.org/grpc/metadata" "google.golang.org/protobuf/types/known/fieldmaskpb" libregraph "github.com/owncloud/libre-graph-api-go" "github.com/owncloud/ocis/v2/ocis-pkg/log" + "github.com/owncloud/ocis/v2/ocis-pkg/mfa" searchmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/search/v0" searchsvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/search/v0" "github.com/owncloud/ocis/v2/services/search/pkg/config" @@ -104,8 +106,14 @@ func (s *Service) Search(ctx context.Context, req *searchsvc.SearchRequest) (*se } currentUser := revactx.ContextMustGetUser(ctx) - // Extract scope from query if set - query, scope := ParseScope(req.Query) + // Extract vault mode and scope from query if set + query, isVault := ParseVaultMode(req.Query) + ctx = mfa.Set(ctx, isVault && mfa.Has(ctx)) + if mfa.Has(ctx) { + ctx = grpcmetadata.AppendToOutgoingContext(ctx, revactx.MFAOutgoingHeader, "true") + } + + query, scope := ParseScope(query) if query == "" { return nil, errtypes.BadRequest("empty query provided") } @@ -156,16 +164,47 @@ func (s *Service) Search(ctx context.Context, req *searchsvc.SearchRequest) (*se // Get the spaces to search spaces := []*provider.StorageSpace{} - listSpacesRes, err := gatewayClient.ListStorageSpaces(ctx, &provider.ListStorageSpacesRequest{Filters: filters}) + lssReq := &provider.ListStorageSpacesRequest{Filters: filters} + listSpacesRes, err := gatewayClient.ListStorageSpaces(ctx, lssReq) if err != nil { s.logger.Error().Err(err).Msg("failed to list the user's storage spaces") return nil, err } + if mfa.Has(ctx) { + // When the "storage_id" is set the ListStorageSpaces request omits "+grant" + // spaces, so we have to make an additional request to get the vault space in vault mode + lssReq.Opaque = utils.AppendPlainToOpaque(lssReq.Opaque, "storage_id", utils.VaultStorageProviderID) + listVaultSpacesRes, err := gatewayClient.ListStorageSpaces(ctx, lssReq) + if err != nil { + s.logger.Error().Err(err).Msg("failed to list the user's storage spaces") + return nil, err + } + if len(listVaultSpacesRes.StorageSpaces) > 0 { + listSpacesRes.StorageSpaces = append(listSpacesRes.StorageSpaces, listVaultSpacesRes.StorageSpaces...) + } + } for _, space := range listSpacesRes.StorageSpaces { if utils.ReadPlainFromOpaque(space.Opaque, "trashed") == _spaceStateTrashed { // Do not consider disabled spaces continue } + { + // Filter out spaces that don't match the current mode (vault or regular) + opaqueMap := sdk.DecodeOpaqueMap(space.Opaque) + var storageID string + if space.SpaceType == _spaceTypeMountpoint { + storageID = opaqueMap["grantStorageID"] + } else { + storageID = space.Root.GetStorageId() + } + isVaultSpace := storageID == utils.VaultStorageProviderID + if mfa.Has(ctx) && !isVaultSpace { + continue // vault mode: skip non-vault spaces + } + if !mfa.Has(ctx) && isVaultSpace { + continue // regular mode: skip vault spaces + } + } if space.SpaceType != "mountpoint" && req.Ref != nil && (req.Ref.GetResourceId().GetSpaceId() != space.Root.GetSpaceId()) { // Do not search (non-mountpoint) spaces that do not match the given scope (if a scope is set) // We still need the mountpoint in order to map the result paths to the according share @@ -446,6 +485,10 @@ func (s *Service) IndexSpace(spaceID *provider.StorageSpaceId) error { } rootID.OpaqueId = rootID.SpaceId + if rootID.StorageId == utils.VaultStorageProviderID { + ownerCtx = grpcmetadata.AppendToOutgoingContext(ownerCtx, revactx.MFAOutgoingHeader, "true") + } + failures := 0 w := walker.NewWalker(s.gatewaySelector) @@ -762,6 +805,10 @@ func (s *Service) resInfo(ref *provider.Reference) (context.Context, *provider.S return nil, nil, "" } + if ref.GetResourceId().GetStorageId() == utils.VaultStorageProviderID { + ownerCtx = grpcmetadata.AppendToOutgoingContext(ownerCtx, revactx.MFAOutgoingHeader, "true") + } + statRes, err := statResource(ownerCtx, ref, s.gatewaySelector, s.logger) if err != nil { return nil, nil, "" diff --git a/services/search/pkg/search/service_test.go b/services/search/pkg/search/service_test.go index 1c6b0679201..703f9d1f0a8 100644 --- a/services/search/pkg/search/service_test.go +++ b/services/search/pkg/search/service_test.go @@ -26,7 +26,9 @@ import ( 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" cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks" + "github.com/owncloud/ocis/v2/ocis-pkg/mfa" "github.com/stretchr/testify/mock" "google.golang.org/grpc" ) @@ -736,9 +738,335 @@ var _ = Describe("Searchprovider", func() { }) }) }) + + Context("vault mode", func() { + var vaultSpace *sprovider.StorageSpace + + BeforeEach(func() { + vaultSpace = &sprovider.StorageSpace{ + SpaceType: "personal", + Owner: user, + Id: &sprovider.StorageSpaceId{OpaqueId: utils.VaultStorageProviderID + "$vaultspace!vaultspace"}, + Root: &sprovider.ResourceId{StorageId: utils.VaultStorageProviderID, SpaceId: "vaultspace", OpaqueId: "vaultspace"}, + Name: "vaultspace", + } + gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{ + Status: status.NewOK(context.Background()), + Info: ri, + }, nil) + }) + + It("searches only the vault space when vault:true is in query AND context has MFA", func() { + mfaCtx := mfa.Set(ctx, true) + // First call: general spaces (no storage_id opaque key) — returns only the personal space. + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.MatchedBy(func(req *sprovider.ListStorageSpacesRequest) bool { + return utils.ReadPlainFromOpaque(req.Opaque, "storage_id") == "" + })).Return(&sprovider.ListStorageSpacesResponse{ + Status: status.NewOK(mfaCtx), + StorageSpaces: []*sprovider.StorageSpace{personalSpace}, + }, nil) + // Second call: vault-specific (storage_id set) — returns the vault space. + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.MatchedBy(func(req *sprovider.ListStorageSpacesRequest) bool { + return utils.ReadPlainFromOpaque(req.Opaque, "storage_id") == utils.VaultStorageProviderID + })).Return(&sprovider.ListStorageSpacesResponse{ + Status: status.NewOK(mfaCtx), + StorageSpaces: []*sprovider.StorageSpace{vaultSpace}, + }, nil) + indexClient.On("Search", mock.Anything, mock.MatchedBy(func(req *searchsvc.SearchIndexRequest) bool { + return req.Ref.ResourceId.SpaceId == vaultSpace.Root.SpaceId + })).Return(&searchsvc.SearchIndexResponse{ + TotalMatches: 1, + Matches: []*searchmsg.Match{ + { + Score: 1, + Entity: &searchmsg.Entity{ + Ref: &searchmsg.Reference{ + ResourceId: &searchmsg.ResourceID{ + StorageId: vaultSpace.Root.StorageId, + SpaceId: vaultSpace.Root.SpaceId, + OpaqueId: vaultSpace.Root.OpaqueId, + }, + Path: "./vault-file.pdf", + }, + Id: &searchmsg.ResourceID{ + StorageId: vaultSpace.Root.StorageId, + OpaqueId: "vault-file-id", + }, + Name: "vault-file.pdf", + }, + }, + }, + }, nil) + + res, err := s.Search(mfaCtx, &searchsvc.SearchRequest{Query: "secret vault:true"}) + Expect(err).ToNot(HaveOccurred()) + Expect(res).ToNot(BeNil()) + Expect(len(res.Matches)).To(Equal(1)) + Expect(res.Matches[0].Entity.Id.OpaqueId).To(Equal("vault-file-id")) + }) + + It("searches only regular spaces when MFA context is set but vault:true is absent", func() { + mfaCtx := mfa.Set(ctx, true) + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&sprovider.ListStorageSpacesResponse{ + Status: status.NewOK(mfaCtx), + StorageSpaces: []*sprovider.StorageSpace{personalSpace, vaultSpace}, + }, nil) + indexClient.On("Search", mock.Anything, mock.MatchedBy(func(req *searchsvc.SearchIndexRequest) bool { + return req.Ref.ResourceId.SpaceId == personalSpace.Root.SpaceId + })).Return(&searchsvc.SearchIndexResponse{ + TotalMatches: 1, + Matches: []*searchmsg.Match{ + { + Score: 1, + Entity: &searchmsg.Entity{ + Ref: &searchmsg.Reference{ + ResourceId: &searchmsg.ResourceID{ + StorageId: personalSpace.Root.StorageId, + SpaceId: personalSpace.Root.SpaceId, + OpaqueId: personalSpace.Root.OpaqueId, + }, + Path: "./path/to/Foo.pdf", + }, + Id: &searchmsg.ResourceID{ + StorageId: personalSpace.Root.StorageId, + OpaqueId: "foo-id", + }, + Name: "Foo.pdf", + }, + }, + }, + }, nil) + + res, err := s.Search(mfaCtx, &searchsvc.SearchRequest{Query: "secret"}) + Expect(err).ToNot(HaveOccurred()) + Expect(res).ToNot(BeNil()) + Expect(len(res.Matches)).To(Equal(1)) + Expect(res.Matches[0].Entity.Id.OpaqueId).To(Equal("foo-id")) + }) + + It("searches only regular spaces when vault:true is in query but context has no MFA", func() { + // ctx has no MFA — a non-MFA client cannot opt into vault mode + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&sprovider.ListStorageSpacesResponse{ + Status: status.NewOK(ctx), + StorageSpaces: []*sprovider.StorageSpace{personalSpace, vaultSpace}, + }, nil) + indexClient.On("Search", mock.Anything, mock.MatchedBy(func(req *searchsvc.SearchIndexRequest) bool { + return req.Ref.ResourceId.SpaceId == personalSpace.Root.SpaceId + })).Return(&searchsvc.SearchIndexResponse{ + TotalMatches: 1, + Matches: []*searchmsg.Match{ + { + Score: 1, + Entity: &searchmsg.Entity{ + Ref: &searchmsg.Reference{ + ResourceId: &searchmsg.ResourceID{ + StorageId: personalSpace.Root.StorageId, + SpaceId: personalSpace.Root.SpaceId, + OpaqueId: personalSpace.Root.OpaqueId, + }, + Path: "./path/to/Foo.pdf", + }, + Id: &searchmsg.ResourceID{ + StorageId: personalSpace.Root.StorageId, + OpaqueId: "foo-id", + }, + Name: "Foo.pdf", + }, + }, + }, + }, nil) + + res, err := s.Search(ctx, &searchsvc.SearchRequest{Query: "secret vault:true"}) + Expect(err).ToNot(HaveOccurred()) + Expect(res).ToNot(BeNil()) + Expect(len(res.Matches)).To(Equal(1)) + Expect(res.Matches[0].Entity.Id.OpaqueId).To(Equal("foo-id")) + }) + + It("regular search includes received shares but excludes vault spaces", func() { + grantSpace := &sprovider.StorageSpace{ + SpaceType: "grant", + Owner: otherUser, + Id: &sprovider.StorageSpaceId{OpaqueId: "storageproviderid$spaceid!otherspacegrant"}, + Root: &sprovider.ResourceId{StorageId: "storageproviderid", SpaceId: "spaceid", OpaqueId: "otherspacegrant"}, + Name: "grantspace", + RootInfo: &sprovider.ResourceInfo{ + Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "opaqueid"}, + }, + } + mountpointSpace := &sprovider.StorageSpace{ + SpaceType: "mountpoint", + Owner: otherUser, + Id: &sprovider.StorageSpaceId{OpaqueId: "storageproviderid$spaceid!otherspacemountpoint"}, + Root: &sprovider.ResourceId{StorageId: "storageproviderid", SpaceId: "spaceid", OpaqueId: "otherspacemountpoint"}, + Name: "mountpointspace", + Opaque: &typesv1beta1.Opaque{ + Map: map[string]*typesv1beta1.OpaqueEntry{ + "grantStorageID": {Decoder: "plain", Value: []byte("storageproviderid")}, + "grantSpaceID": {Decoder: "plain", Value: []byte("spaceid")}, + "grantOpaqueID": {Decoder: "plain", Value: []byte("otherspacegrant")}, + }, + }, + } + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&sprovider.ListStorageSpacesResponse{ + Status: status.NewOK(ctx), + StorageSpaces: []*sprovider.StorageSpace{personalSpace, grantSpace, mountpointSpace, vaultSpace}, + }, nil) + gatewayClient.On("GetPath", mock.Anything, mock.Anything).Return(&sprovider.GetPathResponse{ + Status: status.NewOK(ctx), + Path: "/grant/path", + }, nil) + indexClient.On("Search", mock.Anything, mock.MatchedBy(func(req *searchsvc.SearchIndexRequest) bool { + return req.Ref.ResourceId.SpaceId == grantSpace.Root.SpaceId + })).Return(&searchsvc.SearchIndexResponse{ + TotalMatches: 1, + Matches: []*searchmsg.Match{ + { + Score: 1, + Entity: &searchmsg.Entity{ + Ref: &searchmsg.Reference{ + ResourceId: &searchmsg.ResourceID{ + StorageId: grantSpace.Root.StorageId, + SpaceId: grantSpace.Root.SpaceId, + OpaqueId: grantSpace.Root.OpaqueId, + }, + Path: "./grant/path/to/Shared.pdf", + }, + Id: &searchmsg.ResourceID{StorageId: grantSpace.Root.StorageId, OpaqueId: "shared-id"}, + Name: "Shared.pdf", + }, + }, + }, + }, nil) + indexClient.On("Search", mock.Anything, mock.MatchedBy(func(req *searchsvc.SearchIndexRequest) bool { + return req.Ref.ResourceId.SpaceId == personalSpace.Root.SpaceId + })).Return(&searchsvc.SearchIndexResponse{}, nil) + + res, err := s.Search(ctx, &searchsvc.SearchRequest{Query: "file"}) + Expect(err).ToNot(HaveOccurred()) + Expect(res).ToNot(BeNil()) + Expect(len(res.Matches)).To(Equal(1)) + // Result is the share, mapped to the mountpoint path. + Expect(res.Matches[0].Entity.Id.OpaqueId).To(Equal("shared-id")) + Expect(res.Matches[0].Entity.Ref.ResourceId.OpaqueId).To(Equal(mountpointSpace.Root.OpaqueId)) + // Vault space was not searched. + indexClient.AssertNotCalled(GinkgoT(), "Search", mock.Anything, mock.MatchedBy(func(req *searchsvc.SearchIndexRequest) bool { + return req.Ref.ResourceId.StorageId == utils.VaultStorageProviderID + })) + }) + + It("vault mode search excludes received shares from regular storage", func() { + grantSpace := &sprovider.StorageSpace{ + SpaceType: "grant", + Owner: otherUser, + Id: &sprovider.StorageSpaceId{OpaqueId: "storageproviderid$spaceid!otherspacegrant"}, + Root: &sprovider.ResourceId{StorageId: "storageproviderid", SpaceId: "spaceid", OpaqueId: "otherspacegrant"}, + Name: "grantspace", + } + mountpointSpace := &sprovider.StorageSpace{ + SpaceType: "mountpoint", + Owner: otherUser, + Id: &sprovider.StorageSpaceId{OpaqueId: "storageproviderid$spaceid!otherspacemountpoint"}, + Root: &sprovider.ResourceId{StorageId: "storageproviderid", SpaceId: "spaceid", OpaqueId: "otherspacemountpoint"}, + Name: "mountpointspace", + Opaque: &typesv1beta1.Opaque{ + Map: map[string]*typesv1beta1.OpaqueEntry{ + "grantStorageID": {Decoder: "plain", Value: []byte("storageproviderid")}, + "grantSpaceID": {Decoder: "plain", Value: []byte("spaceid")}, + "grantOpaqueID": {Decoder: "plain", Value: []byte("otherspacegrant")}, + }, + }, + } + mfaCtx := mfa.Set(ctx, true) + // First LSS call: general — returns personal + grant + mountpoint (no vault). + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.MatchedBy(func(req *sprovider.ListStorageSpacesRequest) bool { + return utils.ReadPlainFromOpaque(req.Opaque, "storage_id") == "" + })).Return(&sprovider.ListStorageSpacesResponse{ + Status: status.NewOK(mfaCtx), + StorageSpaces: []*sprovider.StorageSpace{personalSpace, grantSpace, mountpointSpace}, + }, nil) + // Second LSS call: vault-specific — returns vault space. + gatewayClient.On("ListStorageSpaces", mock.Anything, mock.MatchedBy(func(req *sprovider.ListStorageSpacesRequest) bool { + return utils.ReadPlainFromOpaque(req.Opaque, "storage_id") == utils.VaultStorageProviderID + })).Return(&sprovider.ListStorageSpacesResponse{ + Status: status.NewOK(mfaCtx), + StorageSpaces: []*sprovider.StorageSpace{vaultSpace}, + }, nil) + indexClient.On("Search", mock.Anything, mock.MatchedBy(func(req *searchsvc.SearchIndexRequest) bool { + return req.Ref.ResourceId.SpaceId == vaultSpace.Root.SpaceId + })).Return(&searchsvc.SearchIndexResponse{ + TotalMatches: 1, + Matches: []*searchmsg.Match{ + { + Score: 1, + Entity: &searchmsg.Entity{ + Ref: &searchmsg.Reference{ + ResourceId: &searchmsg.ResourceID{ + StorageId: vaultSpace.Root.StorageId, + SpaceId: vaultSpace.Root.SpaceId, + OpaqueId: vaultSpace.Root.OpaqueId, + }, + Path: "./vault-file.pdf", + }, + Id: &searchmsg.ResourceID{StorageId: vaultSpace.Root.StorageId, OpaqueId: "vault-file-id"}, + Name: "vault-file.pdf", + }, + }, + }, + }, nil) + + res, err := s.Search(mfaCtx, &searchsvc.SearchRequest{Query: "file vault:true"}) + Expect(err).ToNot(HaveOccurred()) + Expect(res).ToNot(BeNil()) + Expect(len(res.Matches)).To(Equal(1)) + Expect(res.Matches[0].Entity.Id.OpaqueId).To(Equal("vault-file-id")) + // Grant/mountpoint spaces were not searched. + indexClient.AssertNotCalled(GinkgoT(), "Search", mock.Anything, mock.MatchedBy(func(req *searchsvc.SearchIndexRequest) bool { + return req.Ref.ResourceId.SpaceId == grantSpace.Root.SpaceId + })) + }) + }) }) }) +var _ = DescribeTable("Parse Vault Mode", + func(pattern, wantQuery string, wantVault bool) { + gotQuery, gotVault := search.ParseVaultMode(pattern) + Expect(gotQuery).To(Equal(wantQuery)) + Expect(gotVault).To(Equal(wantVault)) + }, + Entry("vault:true present", + `file vault:true`, + `file`, + true, + ), + Entry("vault:true at the beginning", + `vault:true file`, + `file`, + true, + ), + Entry("vault:true in the middle", + `foo vault:true bar`, + `foo bar`, + true, + ), + Entry("vault:false is not vault mode", + `+Name:*file* vault:false +Tags:"foo"`, + `+Name:*file* +Tags:"foo"`, + false, + ), + Entry("vault:false is not vault mode", + `file vault:false`, + `file`, + false, + ), + Entry("no vault token", + `+Name:*file* +Tags:"foo"`, + `+Name:*file* +Tags:"foo"`, + false, + ), +) + var _ = DescribeTable("Parse Scope", func(pattern, wantSearch, wantScope string) { gotSearch, gotScope := search.ParseScope(pattern) diff --git a/services/search/pkg/service/grpc/v0/service.go b/services/search/pkg/service/grpc/v0/service.go index 295ce4601c3..02a3c9db5bc 100644 --- a/services/search/pkg/service/grpc/v0/service.go +++ b/services/search/pkg/service/grpc/v0/service.go @@ -24,6 +24,7 @@ import ( "github.com/owncloud/ocis/v2/ocis-pkg/generators" "github.com/owncloud/ocis/v2/ocis-pkg/log" + "github.com/owncloud/ocis/v2/ocis-pkg/mfa" "github.com/owncloud/ocis/v2/ocis-pkg/registry" v0 "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/search/v0" searchsvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/search/v0" @@ -143,7 +144,10 @@ func (s Service) Search(ctx context.Context, in *searchsvc.SearchRequest, out *s } ctx = revactx.ContextSetUser(ctx, u) - key := cacheKey(in.Query, in.PageSize, in.Ref, u) + mfaVal, _ := metadata.Get(ctx, revactx.MFAOutgoingHeader) + ctx = mfa.Set(ctx, mfaVal == "true") + + key := cacheKey(in.Query, in.PageSize, in.Ref, u, mfa.Has(ctx)) res, ok := s.FromCache(key) if !ok { var err error @@ -222,6 +226,9 @@ func (s Service) Cache(key string, res *searchsvc.SearchResponse) { _ = s.cache.Set(key, res) } -func cacheKey(query string, pagesize int32, ref *v0.Reference, user *user.User) string { - return fmt.Sprintf("%s|%d|%s$%s!%s/%s|%s", query, pagesize, ref.GetResourceId().GetStorageId(), ref.GetResourceId().GetSpaceId(), ref.GetResourceId().GetOpaqueId(), ref.GetPath(), user.GetId().GetOpaqueId()) +func cacheKey(query string, pagesize int32, ref *v0.Reference, user *user.User, isVault bool) string { + return fmt.Sprintf("%s|%d|%s$%s!%s/%s|%s|%v", query, pagesize, ref.GetResourceId().GetStorageId(), ref.GetResourceId().GetSpaceId(), ref.GetResourceId().GetOpaqueId(), ref.GetPath(), user.GetId().GetOpaqueId(), isVault) } + +// ExportedCacheKey is exported for testing only. +var ExportedCacheKey = cacheKey diff --git a/services/storage-users/README.md b/services/storage-users/README.md index a0a7f451dd1..5d9a423d52c 100644 --- a/services/storage-users/README.md +++ b/services/storage-users/README.md @@ -407,3 +407,87 @@ Store specific notes: - When using `redis-sentinel`, the Redis master to use is configured via e.g. `OCIS_CACHE_STORE_NODES` in the form of `:/` like `10.10.0.200:26379/mymaster`. - When using `nats-js-kv` it is recommended to set `OCIS_CACHE_STORE_NODES` to the same value as `OCIS_EVENTS_ENDPOINT`. That way the cache uses the same nats instance as the event bus. - When using the `nats-js-kv` store, it is possible to set `OCIS_CACHE_DISABLE_PERSISTENCE` to instruct nats to not persist cache data on disc. + +## Vault Mode + +Vault mode provides a dedicated, separately stored vault storage that can be MFA-protected. Vault resources are isolated from the default user storage and have their own search, shares, and spaces — while public links are explicitly disallowed. + +### Architecture + +* A dedicated `storage-users` vault storage instance is configured with a `VaultStorageProviderID` and mounted at `/vault/users` and `/vault/projects`. +* The `graph` service API is extended to serve the `/vault` prefix when vault mode is active. +* WebDAV access is supported for vault resources. +* Search is scoped separately for default and vault files, including their shares and spaces. +* Public links are disallowed for vault resources. The capabilities endpoint accepts a `vault=true` query parameter to advertise vault-specific capabilities. + +#### The `vault mode` configuration and environment variables +Set `OCIS_ENABLE_VAULT_MODE: true`, `OCIS_MFA_ENABLED: true` to true to enable the vault mode in a OCIS. Only applicapable if the storage-users-vault service, a special configured storage-users service is configured. + +The storage-users-vault configuration: +``` +STORAGE_USERS_SERVICE_NAME: storage-users-vault +STORAGE_USERS_GRPC_ADDR: storage-users-vault:9285 +STORAGE_USERS_HTTP_ADDR: storage-users-vault:9286 +STORAGE_USERS_DATA_SERVER_URL: http://storage-users-vault:9286/data +STORAGE_USERS_DEBUG_ADDR: storage-users-vault:9287 +STORAGE_USERS_OCIS_ROOT: /var/lib/ocis/storage/users-vault +STORAGE_USERS_EVENTS_CONSUMER_GROUP: vault-dcfs +``` + +``` +~/.ocis/storage +$ tree users* +users +├── indexes +│   ├── by-group-id +│   ├── by-type +│   │   └── personal.mpk +│   └── by-user-id +│   └── a032f2bd-fa5c-430b-a163-2c19f54190d0.mpk +├── spaces +│   └── a0 +│   └── 32f2bd-fa5c-430b-a163-2c19f54190d0 +│   └── nodes +│   └── a0 +│   └── 32 +│   └── f2 +│   └── bd +│   ├── -fa5c-430b-a163-2c19f54190d0 +│   ├── -fa5c-430b-a163-2c19f54190d0.mlock +│   └── -fa5c-430b-a163-2c19f54190d0.mpk +└── uploads +users-vault +├── indexes +│   ├── by-group-id +│   ├── by-type +│   │   └── personal.mpk +│   └── by-user-id +│   └── a032f2bd-fa5c-430b-a163-2c19f54190d0.mpk +├── spaces +│   └── a0 +│   └── 32f2bd-fa5c-430b-a163-2c19f54190d0 +│   └── nodes +│   └── a0 +│   └── 32 +│   └── f2 +│   └── bd +│   ├── -fa5c-430b-a163-2c19f54190d0 +│   ├── -fa5c-430b-a163-2c19f54190d0.mlock +│   └── -fa5c-430b-a163-2c19f54190d0.mpk +└── uploads +``` + +### Running with Docker + +To enable vault mode in the `ocis_full` docker-compose stack, edit `deployments/examples/ocis_full/.env` and uncomment the following lines: + +```.env +KEYCLOAK=:keycloak.yml +VAULT_STORAGE=:vault-storage.yml +``` + +Then start the stack: + +```bash +docker compose up -d +``` diff --git a/services/storage-users/pkg/config/config.go b/services/storage-users/pkg/config/config.go index c3bfa18c90e..51859b7d5e5 100644 --- a/services/storage-users/pkg/config/config.go +++ b/services/storage-users/pkg/config/config.go @@ -45,6 +45,8 @@ type Config struct { MachineAuthAPIKey string `yaml:"machine_auth_api_key" env:"OCIS_MACHINE_AUTH_API_KEY;STORAGE_USERS_MACHINE_AUTH_API_KEY" desc:"Machine auth API key used to validate internal requests necessary for the access to resources from other services." introductionVersion:"5.0"` CliMaxAttemptsRenameFile int `yaml:"max_attempts_rename_file" env:"STORAGE_USERS_CLI_MAX_ATTEMPTS_RENAME_FILE" desc:"The maximum number of attempts to rename a file when a user restores a file to an existing destination with the same name. The minimum value is 100." introductionVersion:"5.0"` + EnableVaultMode bool `yaml:"enable_vault_mode" env:"STORAGE_USERS_ENABLE_VAULT_MODE" desc:"Enabling the flag forces the storage-users service to run with a MountID set to VaultStorageProviderID. Not applicable for use with the primary storage-users service. Use only if an additional storage-users-vault service, a special configured storage-users service is configured." introductionVersion:"Deledda"` + Context context.Context `yaml:"-"` } @@ -215,6 +217,7 @@ type Events struct { TLSRootCaCertPath string `yaml:"tls_root_ca_cert_path" env:"OCIS_EVENTS_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_EVENTS_TLS_ROOT_CA_CERTIFICATE" desc:"The root CA certificate used to validate the server's TLS certificate. If provided STORAGE_USERS_EVENTS_TLS_INSECURE will be seen as false." introductionVersion:"pre5.0"` EnableTLS bool `yaml:"enable_tls" env:"OCIS_EVENTS_ENABLE_TLS;STORAGE_USERS_EVENTS_ENABLE_TLS" desc:"Enable TLS for the connection to the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"pre5.0"` NumConsumers int `yaml:"num_consumers" env:"STORAGE_USERS_EVENTS_NUM_CONSUMERS" desc:"The amount of concurrent event consumers to start. Event consumers are used for post-processing files. Multiple consumers increase parallelisation, but will also increase CPU and memory demands. The setting has no effect when the OCIS_ASYNC_UPLOADS is set to false. The default and minimum value is 1." introductionVersion:"pre5.0"` + ConsumerGroup string `yaml:"consumer_group" env:"STORAGE_USERS_EVENTS_CONSUMER_GROUP" desc:"The name of the consumer group to be used at the event to help consumers identify the unique group." introductionVersion:"Deledda"` AuthUsername string `yaml:"username" env:"OCIS_EVENTS_AUTH_USERNAME;STORAGE_USERS_EVENTS_AUTH_USERNAME" desc:"The username to authenticate with the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"5.0"` AuthPassword string `yaml:"password" env:"OCIS_EVENTS_AUTH_PASSWORD;STORAGE_USERS_EVENTS_AUTH_PASSWORD" desc:"The password to authenticate with the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"5.0"` } diff --git a/services/storage-users/pkg/config/defaults/defaultconfig.go b/services/storage-users/pkg/config/defaults/defaultconfig.go index d6de665deea..f77ef6372f5 100644 --- a/services/storage-users/pkg/config/defaults/defaultconfig.go +++ b/services/storage-users/pkg/config/defaults/defaultconfig.go @@ -8,6 +8,7 @@ import ( "github.com/owncloud/ocis/v2/ocis-pkg/shared" "github.com/owncloud/ocis/v2/ocis-pkg/structs" "github.com/owncloud/ocis/v2/services/storage-users/pkg/config" + "github.com/owncloud/reva/v2/pkg/utils" ) // FullDefaultConfig returns a fully initialized default configuration @@ -226,6 +227,11 @@ func EnsureDefaults(cfg *config.Config) { cfg.HTTP.CORS.AllowedOrigins[0] == "https://localhost:9200") { cfg.HTTP.CORS.AllowedOrigins = []string{cfg.Commons.OcisURL} } + + // set mount id to vault storage provider id + if cfg.EnableVaultMode { + cfg.MountID = utils.VaultStorageProviderID + } } // Sanitize sanitized the configuration diff --git a/services/storage-users/pkg/revaconfig/config.go b/services/storage-users/pkg/revaconfig/config.go index 2f47e4c5fda..f5f08fff599 100644 --- a/services/storage-users/pkg/revaconfig/config.go +++ b/services/storage-users/pkg/revaconfig/config.go @@ -116,11 +116,25 @@ func StorageUsersConfigFromStruct(cfg *config.Config) map[string]interface{} { }, }, } + gcfg := rcfg["grpc"].(map[string]interface{}) if cfg.ReadOnly { - gcfg := rcfg["grpc"].(map[string]interface{}) + // Replace all interceptors with readonly when the storage is read-only. + // eventsmiddleware and prometheus are intentionally dropped in this mode. gcfg["interceptors"] = map[string]interface{}{ "readonly": map[string]interface{}{}, } } + if cfg.EnableVaultMode { + // Set mfa_enabled inside the auth interceptor config so that all gRPC + // calls to this vault storage-users instance require MFA authentication. + interceptors := gcfg["interceptors"].(map[string]interface{}) + if authCfg, ok := interceptors["auth"].(map[string]interface{}); ok { + authCfg["mfa_enabled"] = true + } else { + interceptors["auth"] = map[string]interface{}{ + "mfa_enabled": true, + } + } + } return rcfg } diff --git a/services/storage-users/pkg/revaconfig/drivers.go b/services/storage-users/pkg/revaconfig/drivers.go index 311e40c7591..66c932139be 100644 --- a/services/storage-users/pkg/revaconfig/drivers.go +++ b/services/storage-users/pkg/revaconfig/drivers.go @@ -157,6 +157,7 @@ func OwnCloudSQL(cfg *config.Config) map[string]interface{} { // Ocis is the config mapping for the Ocis storage driver func Ocis(cfg *config.Config) map[string]interface{} { return map[string]interface{}{ + "mount_id": cfg.MountID, "metadata_backend": "messagepack", "propagator": cfg.Drivers.OCIS.Propagator, "async_propagator_options": map[string]interface{}{ @@ -198,7 +199,8 @@ func Ocis(cfg *config.Config) map[string]interface{} { "cache_auth_password": cfg.IDCache.AuthPassword, }, "events": map[string]interface{}{ - "numconsumers": cfg.Events.NumConsumers, + "numconsumers": cfg.Events.NumConsumers, + "consumer_group": cfg.Events.ConsumerGroup, }, "tokens": map[string]interface{}{ "transfer_shared_secret": cfg.Commons.TransferSecret, @@ -321,7 +323,8 @@ func S3NG(cfg *config.Config) map[string]interface{} { "cache_auth_password": cfg.IDCache.AuthPassword, }, "events": map[string]interface{}{ - "numconsumers": cfg.Events.NumConsumers, + "numconsumers": cfg.Events.NumConsumers, + "consumer_group": cfg.Events.ConsumerGroup, }, "tokens": map[string]interface{}{ "transfer_shared_secret": cfg.Commons.TransferSecret, diff --git a/services/thumbnails/pkg/service/grpc/v0/service.go b/services/thumbnails/pkg/service/grpc/v0/service.go index 44e16a9a935..888178b334b 100644 --- a/services/thumbnails/pkg/service/grpc/v0/service.go +++ b/services/thumbnails/pkg/service/grpc/v0/service.go @@ -18,6 +18,7 @@ import ( "github.com/owncloud/reva/v2/pkg/utils" "github.com/pkg/errors" merrors "go-micro.dev/v4/errors" + gmmetadata "go-micro.dev/v4/metadata" "google.golang.org/grpc/metadata" "github.com/owncloud/ocis/v2/ocis-pkg/log" @@ -28,6 +29,7 @@ import ( tjwt "github.com/owncloud/ocis/v2/services/thumbnails/pkg/service/jwt" "github.com/owncloud/ocis/v2/services/thumbnails/pkg/thumbnail" "github.com/owncloud/ocis/v2/services/thumbnails/pkg/thumbnail/imgsource" + ctxpkg "github.com/owncloud/reva/v2/pkg/ctx" ) // NewService returns a service implementation for Service. @@ -140,7 +142,7 @@ func (g Thumbnail) checkThumbnail(req *thumbnailssvc.GetThumbnailRequest, sRes * func (g Thumbnail) handleCS3Source(ctx context.Context, req *thumbnailssvc.GetThumbnailRequest) (string, error) { src := req.GetCs3Source() - sRes, err := g.stat(src.GetPath(), src.GetAuthorization()) + sRes, err := g.stat(ctx, src.GetPath(), src.GetAuthorization()) if err != nil { return "", err } @@ -223,7 +225,7 @@ func (g Thumbnail) handleWebdavSource(ctx context.Context, req *thumbnailssvc.Ge auth = src.GetRevaAuthorization() statPath = req.GetFilepath() } - sRes, err := g.stat(statPath, auth) + sRes, err := g.stat(ctx, statPath, auth) if err != nil { return "", err } @@ -272,8 +274,17 @@ func (g Thumbnail) handleWebdavSource(ctx context.Context, req *thumbnailssvc.Ge return key, err } -func (g Thumbnail) stat(path, auth string) (*provider.StatResponse, error) { - ctx := metadata.AppendToOutgoingContext(context.Background(), revactx.TokenHeader, auth) +func (g Thumbnail) stat(ctx context.Context, path, auth string) (*provider.StatResponse, error) { + outCtx := metadata.AppendToOutgoingContext(ctx, revactx.TokenHeader, auth) + + // Bridge MFA status from go-micro metadata (set by the webdav service) into + // outgoing gRPC metadata. The autoprop-prefixed key is then forwarded + // automatically at every subsequent gRPC hop by the metadata interceptor. + if md, ok := gmmetadata.FromContext(ctx); ok { + if v, ok := md.Get(ctxpkg.MFAOutgoingHeader); ok && v != "" { + outCtx = metadata.AppendToOutgoingContext(outCtx, ctxpkg.MFAOutgoingHeader, v) + } + } ref, err := storagespace.ParseReference(path) if err != nil { @@ -289,7 +300,7 @@ func (g Thumbnail) stat(path, auth string) (*provider.StatResponse, error) { return nil, merrors.InternalServerError(g.serviceID, "could not select next gateway client: %s", err.Error()) } req := &provider.StatRequest{Ref: &ref} - rsp, err := client.Stat(ctx, req) + rsp, err := client.Stat(outCtx, req) if err != nil { g.logger.Error().Err(err).Str("path", path).Msg("could not stat file") return nil, merrors.InternalServerError(g.serviceID, "could not stat file: %s", err.Error()) diff --git a/services/thumbnails/pkg/thumbnail/imgsource/cs3.go b/services/thumbnails/pkg/thumbnail/imgsource/cs3.go index e399592e4f8..d770494f05f 100644 --- a/services/thumbnails/pkg/thumbnail/imgsource/cs3.go +++ b/services/thumbnails/pkg/thumbnail/imgsource/cs3.go @@ -18,6 +18,7 @@ import ( "github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool" "github.com/owncloud/reva/v2/pkg/rhttp" "github.com/owncloud/reva/v2/pkg/storagespace" + gmmetadata "go-micro.dev/v4/metadata" "google.golang.org/grpc/metadata" ) @@ -60,6 +61,16 @@ func (s CS3) Get(ctx context.Context, path string) (io.ReadCloser, error) { } ctx = metadata.AppendToOutgoingContext(ctx, revactx.TokenHeader, auth) + + // Bridge MFA status from go-micro metadata into outgoing gRPC metadata. + // The autoprop-prefixed key is then forwarded automatically at every + // subsequent gRPC hop by the metadata interceptor. + if md, ok := gmmetadata.FromContext(ctx); ok { + if v, ok := md.Get(revactx.MFAOutgoingHeader); ok && v != "" { + ctx = metadata.AppendToOutgoingContext(ctx, revactx.MFAOutgoingHeader, v) + } + } + err = s.checkImageFileSize(ctx, ref) if err != nil { return nil, err diff --git a/services/webdav/pkg/service/v0/search.go b/services/webdav/pkg/service/v0/search.go index 8eb32a73897..d632d09b1fc 100644 --- a/services/webdav/pkg/service/v0/search.go +++ b/services/webdav/pkg/service/v0/search.go @@ -50,6 +50,12 @@ func (g Webdav) Search(w http.ResponseWriter, r *http.Request) { ctx := revactx.ContextSetToken(r.Context(), t) ctx = metadata.Set(ctx, revactx.TokenHeader, t) + mfaVal := "false" + if r.Header.Get(revactx.MFAHeader) == "true" { + mfaVal = "true" + } + ctx = metadata.Set(ctx, revactx.MFAOutgoingHeader, mfaVal) + req := &searchsvc.SearchRequest{ Query: rep.SearchFiles.Search.Pattern, PageSize: int32(rep.SearchFiles.Search.Limit), diff --git a/services/webdav/pkg/service/v0/service.go b/services/webdav/pkg/service/v0/service.go index 236cf6b93f4..33c0550d959 100644 --- a/services/webdav/pkg/service/v0/service.go +++ b/services/webdav/pkg/service/v0/service.go @@ -21,9 +21,11 @@ import ( "github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool" "github.com/owncloud/reva/v2/pkg/storage/utils/templates" merrors "go-micro.dev/v4/errors" + gmmetadata "go-micro.dev/v4/metadata" grpcmetadata "google.golang.org/grpc/metadata" "github.com/owncloud/ocis/v2/ocis-pkg/log" + "github.com/owncloud/ocis/v2/ocis-pkg/mfa" "github.com/owncloud/ocis/v2/ocis-pkg/registry" "github.com/owncloud/ocis/v2/ocis-pkg/tracing" thumbnailsmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/thumbnails/v0" @@ -234,7 +236,7 @@ func (g Webdav) SpacesThumbnail(w http.ResponseWriter, r *http.Request) { t := r.Header.Get(revactx.TokenHeader) fullPath := filepath.Join(tr.Identifier, tr.Filepath) - rsp, err := g.thumbnailsClient.GetThumbnail(r.Context(), &thumbnailssvc.GetThumbnailRequest{ + rsp, err := g.thumbnailsClient.GetThumbnail(mfaOutgoingCtx(r), &thumbnailssvc.GetThumbnailRequest{ Filepath: strings.TrimLeft(tr.Filepath, "/"), ThumbnailType: extensionToThumbnailType(strings.TrimLeft(tr.Extension, ".")), Width: tr.Width, @@ -332,7 +334,7 @@ func (g Webdav) Thumbnail(w http.ResponseWriter, r *http.Request) { } fullPath := filepath.Join(templates.WithUser(user, g.config.WebdavNamespace), tr.Filepath) - rsp, err := g.thumbnailsClient.GetThumbnail(r.Context(), &thumbnailssvc.GetThumbnailRequest{ + rsp, err := g.thumbnailsClient.GetThumbnail(mfaOutgoingCtx(r), &thumbnailssvc.GetThumbnailRequest{ Filepath: strings.TrimLeft(tr.Filepath, "/"), ThumbnailType: extensionToThumbnailType(strings.TrimLeft(tr.Extension, ".")), Width: tr.Width, @@ -382,7 +384,7 @@ func (g Webdav) PublicThumbnail(w http.ResponseWriter, r *http.Request) { return } - rsp, err := g.thumbnailsClient.GetThumbnail(r.Context(), &thumbnailssvc.GetThumbnailRequest{ + rsp, err := g.thumbnailsClient.GetThumbnail(mfaOutgoingCtx(r), &thumbnailssvc.GetThumbnailRequest{ Filepath: strings.TrimLeft(tr.Filepath, "/"), ThumbnailType: extensionToThumbnailType(strings.TrimLeft(tr.Extension, ".")), Width: tr.Width, @@ -427,7 +429,7 @@ func (g Webdav) PublicThumbnailHead(w http.ResponseWriter, r *http.Request) { return } - _, err = g.thumbnailsClient.GetThumbnail(r.Context(), &thumbnailssvc.GetThumbnailRequest{ + _, err = g.thumbnailsClient.GetThumbnail(mfaOutgoingCtx(r), &thumbnailssvc.GetThumbnailRequest{ Filepath: strings.TrimLeft(tr.Filepath, "/"), ThumbnailType: extensionToThumbnailType(strings.TrimLeft(tr.Extension, ".")), Width: tr.Width, @@ -503,6 +505,20 @@ func (g Webdav) sendThumbnailResponse(rsp *thumbnailssvc.GetThumbnailResponse, w } } +// mfaOutgoingCtx returns a context derived from the HTTP request with the +// MFA status forwarded as go-micro metadata. The thumbnail service is a +// go-micro service: go-micro propagates metadata via its own mechanism +// (sent as Grpc-Metadata- headers), not standard gRPC outgoing metadata. +// The thumbnail service then converts this to standard gRPC outgoing metadata +// when calling the gateway / vault storage. +func mfaOutgoingCtx(r *http.Request) context.Context { + mfaVal := "false" + if r.Header.Get(mfa.MFAHeader) == "true" { + mfaVal = "true" + } + return gmmetadata.Set(r.Context(), revactx.MFAOutgoingHeader, mfaVal) +} + func extensionToThumbnailType(ext string) thumbnailsmsg.ThumbnailType { switch strings.ToUpper(ext) { case "GIF":