* feat(collaboration): add Version to Collabora WOPI CheckFileInfo Add Version field to the Collabora struct to match Microsoft and OnlyOffice implementations. This allows Collabora Online to properly detect stale documents for cache invalidation and document reload detection, which is particularly important in multi-node Kubernetes deployments. - Add Version field to Collabora struct with json:"Version,omitempty" tag - Add case for KeyVersion in Collabora.SetProperties method - Update existing Collabora integration tests to verify Version is populated - Add three unit tests for Version handling in collabora_test.go - Add integration test verifying Collabora CheckFileInfo response includes Version Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: David Walter <david.walter@kiteworks.com> * feat(collaboration): add LastModifiedTime to Collabora CheckFileInfo for conflict detection Add LastModifiedTime to the Collabora struct to match Microsoft and OnlyOffice, and implement the X-COOL-WOPI-Timestamp conflict detection PutFile relies on to use it. Collabora Online tracks the LastModifiedTime it received in CheckFileInfo and sends it back during PutFile; without this field the WOPI host has no way to detect that a file changed since Collabora last checked it, so concurrent edits could silently overwrite each other. - Add LastModifiedTime field to Collabora struct (json:"LastModifiedTime,omitempty") and wire it in Collabora.SetProperties via the existing KeyLastModifiedTime constant - fileconnector.go already populates KeyLastModifiedTime unconditionally for all targets, so no gating changes were needed there - Add HeaderCoolWopiTimestamp ("X-COOL-WOPI-Timestamp") constant and thread it from HttpAdapter.PutFile through the ContentConnectorService.PutFile interface - ContentConnector.PutFile compares the client-supplied timestamp against the file's current mtime and returns a new NewResponseCOOLConflict() (409, COOLStatusCode 1010) on mismatch; an empty timestamp (Microsoft/OnlyOffice, and file-creation call sites in PutRelativeFileSuggested/Relative) skips the check entirely, so existing WOPI clients see no behavior change - Hand-updated the mockery-generated ContentConnectorService mock (mockery itself fails to build under the local Go toolchain) and every PutFile call site/mock expectation across fileconnector.go, fileconnector_test.go, contentconnector_test.go and httpadapter_test.go for the new 5-arg signature - Add fileinfo/collabora_test.go unit tests for LastModifiedTime SetProperties/ JSON marshalling/omitempty, update the 3 existing Collabora CheckFileInfo integration tests with the expected LastModifiedTime, and add PutFile tests covering COOL timestamp mismatch (409) and match (success) in contentconnector_test.go 🤖 Generated with Claude Code Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: David Walter <david.walter@kiteworks.com> * fix(collaboration): handle nil Mtime and add HttpAdapter test coverage for COOL WOPI timestamp The COOL conflict-detection check in ContentConnector.PutFile treated a nil Mtime as an automatic mismatch, causing a permanent 409 on every save for files with no recorded mtime. Skip the comparison (fail open) when Mtime is nil, matching CheckFileInfo's fallback posture. Also add a regression test for that case, plus a test asserting HttpAdapter.PutFile correctly reads the X-COOL-WOPI-Timestamp header and passes it through to the content connector, which previously had no coverage. Signed-off-by: David Walter <david.walter@kiteworks.com> * feat(collaboration): add ReadOnly to Collabora WOPI CheckFileInfo Add ReadOnly to the Collabora struct to match Microsoft and OnlyOffice, and populate it in CheckFileInfo for all three targets. KeyReadOnly already existed as a constant and both Microsoft.SetProperties and OnlyOffice.SetProperties already had a `case KeyReadOnly:`, but nothing in fileconnector.go ever put a value into the properties map for it - so ReadOnly was silently false for every WOPI target, regardless of whether the user actually had write access. - Add ReadOnly field to the Collabora struct (json:"ReadOnly", no omitempty, consistent with Microsoft/OnlyOffice since false is meaningful) and wire it in Collabora.SetProperties via the existing KeyReadOnly constant - In fileconnector.go's CheckFileInfo, set infoMap[fileinfo.KeyReadOnly] = wopiContext.ViewMode != VIEW_MODE_READ_WRITE unconditionally for all targets. wopiContext.ViewMode is already resolved upstream from the actual CS3 permissions, space status and lock state, so this derives ReadOnly from that single source of truth instead of re-deriving the same signals in the connector - Add fileinfo/collabora_test.go unit tests for ReadOnly SetProperties (true/ false) and JSON marshalling (asserting the field is present for both true and false, since there is no omitempty) - Add two new CheckFileInfo integration tests asserting ReadOnly=true for a view-only mode and ReadOnly=false for read-write, and add ReadOnly: true to the 4 existing CheckFileInfo integration tests that assert a full Microsoft/Collabora/OnlyOffice struct under a non-read-write ViewMode (the 2 ViewMode assignments in the Lock/GetLock test block were left untouched since those tests don't assert against a FileInfo struct) 🤖 Generated with Claude Code Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: David Walter <david.walter@kiteworks.com> * feat(collaboration): add SupportsUpdate to Collabora WOPI CheckFileInfo Signed-off-by: David Walter <david.walter@kiteworks.com> * fix(collaboration): add missing godoc comment to Collabora.SupportsUpdate Signed-off-by: David Walter <david.walter@kiteworks.com> * feat(collaboration): add IsAnonymousUser to Collabora WOPI CheckFileInfo Implement support for the IsAnonymousUser property in the Collabora struct, enabling Collabora Online to distinguish between authenticated and anonymous users (public share access). This property is derived from the user context's public-share-role indicator and is already computed in fileconnector.go. Changes: - Add IsAnonymousUser field to Collabora struct with omitempty tag - Wire KeyIsAnonymousUser case in SetProperties - Add unit tests: SetProperties behavior, JSON omit/include when false/true - Add integration tests: anonymous user context returns true, authenticated user returns false, UserId still populated for anonymous users Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: David Walter <david.walter@kiteworks.com> * feat(collaboration): add URL properties to Collabora WOPI CheckFileInfo Add the 7 MS-WOPI file URL properties (CloseUrl, DownloadUrl, FileSharingUrl, FileVersionUrl, HostEditUrl, HostViewUrl, SignoutUrl) to the Collabora fileinfo struct, mirroring the Microsoft struct's existing fields and JSON tags. This is struct/SetProperties wiring only; fileconnector.go population follows in a subsequent commit. SignoutUrl is intentionally left unpopulated in CheckFileInfo (no fileconnector.go change): the collaboration service has no OIDC issuer/logout configuration to build a real sign-out URL from, so Collabora reaches parity with Microsoft/OnlyOffice's existing "field exists but is never populated" gap rather than introducing a new one. Signed-off-by: David Walter <david.walter@kiteworks.com> * feat(collaboration): populate CloseURL and DownloadURL in CheckFileInfo CloseURL and DownloadURL were never populated in CheckFileInfo for any WOPI target (Microsoft, OnlyOffice, or Collabora), despite Microsoft's struct having had these fields all along. - CloseURL reuses the existing parentFolderURL (the same "folder containing the file" URL already used for BreadcrumbFolderURL) rather than building a second URL for the same concept. This flows through the shared infoMap, so it now also reaches Microsoft and OnlyOffice, both of which already declare KeyCloseURL in their SetProperties switch; existing full-struct-equality test expectations are updated accordingly. - DownloadURL is built by a new createFileDownloadURL helper pointing at this service's own GET /wopi/files/{fileid}/contents route, authenticated with a freshly generated WOPI access token. It shares its "generate token + build hashed-resource-id path + attach access_token query param" logic with the existing template createDownloadURL via an extracted createWopiResourceURL helper, rather than duplicating it. Population is defensive: if WOPI token generation fails, DownloadURL is simply omitted (logged) instead of failing the whole CheckFileInfo request, mirroring the existing TemplateSource pattern. HostViewURL, HostEditURL, FileSharingURL, and FileVersionURL needed no fileconnector.go change - they were already unconditionally computed into infoMap; only Collabora's struct lacked the fields to receive them (added in the previous commit). Adds integration test coverage for: CloseURL/BreadcrumbFolderURL reuse, HostEditURL vs HostViewURL distinctness, the DownloadURL route pattern, and graceful omission of DownloadURL when WOPI token generation fails (via ShortTokens with no store configured) without the overall request failing. Signed-off-by: David Walter <david.walter@kiteworks.com> * feat(collaboration): complete Breadcrumb properties in Collabora WOPI CheckFileInfo Add the four Breadcrumb* fields to the Collabora fileinfo struct that were already present on Microsoft/OnlyOffice (BreadcrumbFolderName/URL just needed struct wiring; BreadcrumbBrandName/URL needed new logic in CheckFileInfo, derived from the CS3 StorageSpace Name/Root). BreadcrumbBrandURL is withheld for public-share (anonymous) access, mirroring the existing precedent for parentFolderURL/CloseURL, since it would expose an internal space/resource id an anonymous user has no other way to reach. BreadcrumbBrandName is just a display string and stays populated either way. Also guards the new brand URL construction against a nil space root so it degrades to an empty string instead of a misleading bare ".../f" URL when no space info is available. 🤖 Generated with Claude Code Signed-off-by: David Walter <david.walter@kiteworks.com> * test(collaboration): cover BreadcrumbBrandURL when space has no root Add a new test case to verify that when a StorageSpace has a Name but a nil Root, the BreadcrumbBrandName is populated while BreadcrumbBrandURL remains empty, ensuring the nil-guard doesn't allow malformed URLs. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: David Walter <david.walter@kiteworks.com> * feat(collaboration): add PostMessage properties to Collabora WOPI CheckFileInfo Add ClosePostMessage, EditModePostMessage, EditNotificationPostMessage, FileSharingPostMessage, and FileVersionPostMessage to the Collabora fileinfo struct with SetProperties wiring and godoc comments, mirroring what OnlyOffice already exposes. Only EditModePostMessage is actually populated in CheckFileInfo, gated to the Collabora target: the oCIS web frontend's iframe wrapper (web-app-external/src/App.vue, shared by all WOPI targets) only has a real postMessage handler for UI_Edit today. The other four flags are left unset so Collabora falls back to the corresponding URL properties (HostEditURL/HostViewURL/FileSharingURL/FileVersionURL, added in an earlier task) instead of firing PostMessages nobody listens for. Because OnlyOffice's SetProperties already implements these same keys, the Collabora-only behavior requires an explicit `if` gate on f.cfg.App.Product rather than an unconditional map write, to avoid silently changing OnlyOffice's current (all-absent) behavior. Signed-off-by: David Walter <david.walter@kiteworks.com> * feat(collaboration): add Collabora-specific IsUserLocked and IsAdminUser to WOPI CheckFileInfo Add the two Collabora-only WOPI CheckFileInfo properties: IsUserLocked (applies coolwsd.xml locked_commands to the user) and IsAdminUser (unlocks Collabora's server audit panel). - IsUserLocked is derived from the existing "secure view" condition already used to gate DisableExport/DisableCopy/DisablePrint/ WatermarkText (ViewMode == VIEW_MODE_VIEW_ONLY with a non-empty ViewOnlyToken), applied regardless of public-share vs authenticated user. - IsAdminUser is derived from the CS3 user's Opaque.Map["roles"] JSON array (the same raw data ocis-pkg/middleware/account.go lifts into go-micro metadata), compared against defaults.BundleUUIDRoleAdmin only - SpaceAdmin and other roles do not qualify. Both keys have no matching SetProperties case in Microsoft/OnlyOffice, so they are silently dropped for those targets, consistent with the existing pattern for other Collabora-only properties in this connector. No new config surface was added, matching the scoping approach used throughout this properties-gap series. 🤖 Generated with Claude Code Signed-off-by: David Walter <david.walter@kiteworks.com> * test(collaboration): remove redundant Collabora omitempty test duplicates TestCollaboraVersionOmitEmpty and TestCollaboraLastModifiedTimeOmitEmpty fully duplicated the coverage already provided by TestCollaboraJSONMarshallingIncludesVersion and TestCollaboraJSONMarshallingIncludesLastModifiedTime (both already assert JSON inclusion/omission via a shouldInclude flag). Removing the duplicates also drops an unused `expected` table field flagged by the final whole-branch review. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: David Walter <david.walter@kiteworks.com> * docs(changelog): add changelog entry for Collabora WOPI CheckFileInfo gaps Signed-off-by: David Walter <david.walter@kiteworks.com> * test(collaboration): fix checkFileInfo acceptance tests for ReadOnly derivation Four "check file info with different mode(s)" scenario outlines (onlyOffice/fakeOffice, personal space and project space) hardcoded "ReadOnly": {"const": false} for every view mode. That was accurate only because ReadOnly was never actually populated in CheckFileInfo before this PR (it silently defaulted to Go's zero value). Now that ReadOnly correctly reflects whether the WOPI session grants write access (ReadOnly = ViewMode != READ_WRITE, the exact negation of UserCanWrite), "view" and "read" mode responses correctly report ReadOnly: true, which these tests now assert via a new "read-only" Examples column instead of a static const. The "check file info with different view-mode (collabora)" scenario is unaffected: it never asserted ReadOnly in its schema. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: David Walter <david.walter@kiteworks.com> * revert(collaboration): remove X-COOL-WOPI-Timestamp PutFile conflict detection CI on owncloud/ocis PR #12593 reproducibly failed the e2e test web/tests/e2e/specs/app-provider/officeSuites.spec.ts:17:3 "create an OpenDocument file with Collabora" across two independent full CI runs, timing out after 180s behind a Collabora "document conflict" popup that intercepts all clicks. Server logs showed the new PutFile conflict check firing on literally the first save of a freshly-created document, with a consistent ~8s gap between the client's cached X-COOL-WOPI-Timestamp and the server's current mtime that never resolved across 6+ retries over 3+ minutes. This is most likely oCIS's async post-processing (search indexing, thumbnailing, etc.) legitimately bumping the file's mtime shortly after creation - something this comparison can't distinguish from a real edit conflict, and which Collabora's client doesn't recover from automatically. Revert just the conflict-detection portion of task 02: the coolWopiTimestamp parameter on ContentConnectorService.PutFile / its implementation, the X-COOL-WOPI-Timestamp header handling in HttpAdapter.PutFile, and NewResponseCOOLConflict, plus their tests and mock signatures. The LastModifiedTime WOPI property (and everything else task 02 added) is untouched and remains fully intact. 🤖 Generated with Claude Code Signed-off-by: David Walter <david.walter@kiteworks.com> * test(web): add e2e Playwright coverage for WOPI CheckFileInfo properties Adds dedicated Playwright specs, each covering both Collabora and OnlyOffice, for the WOPI CheckFileInfo properties this PR added that have a genuinely observable, already-proven-safe browser-level signal: - wopiReadOnly.spec.ts: false for the file owner, true for a view-only share recipient (via the existing canEditCollaboraDocument/ canEditOnlyOfficeDocument-backed userShouldNotBeAbleToEditContentOfResources step). - wopiSupportsUpdate.spec.ts: a new document created via the office suite's own "New" menu (PutRelativeFile) persists its content across a reopen. - wopiVersionAndLastModifiedTime.spec.ts: an edit saved by one actor is visible to a second actor opening the file afterward, rather than a stale cached copy. - wopiCloseUrl.spec.ts: closing the editor navigates the top-level page back into the files app. All four are built exclusively from step-level helpers already proven reliable elsewhere in this suite (officeSuites.spec.ts, secureView.spec.ts) - no new selectors into Collabora's or OnlyOffice's own iframe DOM. Not added: dedicated e2e tests for BreadcrumbBrandName/Url, EditModePostMessage, IsUserLocked, and IsAdminUser. CheckFileInfo is a server-to-server call the office suite's own backend makes directly to the collaboration service - it is never visible to the browser, so Playwright cannot observe the JSON response for any property. These four also have no independently observable browser effect without either inventing unverified selectors into third-party iframe internals (breadcrumb bar, edit-mode button) or Collabora-side configuration (locked_commands, audit panel) this test environment doesn't set up. They remain correctly covered by the Go unit/integration tests (fileinfo/collabora_test.go, fileconnector_test.go) and the tests/acceptance/features/apiCollaboration/checkFileInfo.feature acceptance suite, which assert the actual JSON response server-side. An initial IsAnonymousUser spec was written and dropped after review: it only asserted that content loads, which IsAnonymousUser does not gate, making it indistinguishable from a regression (already covered correctly at the Go level in fileconnector_test.go). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: David Walter <david.walter@kiteworks.com> * fix(web): reformat wopiVersionAndLastModifiedTime.spec.ts for prettier pnpm check:format (web-build-test CI job) flagged the test.describe() call: its 3 arguments (title, options, callback) didn't fit within this repo's printWidth 100 on one line, so prettier expects them wrapped one per line. Reformatted to match and reindented the describe block body accordingly. No logic change. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: David Walter <david.walter@kiteworks.com> * fix(collaboration): address PR #12593 review findings - Restructure the VIEW_ONLY watermark check to nest inside the ViewOnlyToken check instead of repeating the condition, per jvillafanez's review comment. - Add a reva token mint/dismantle round-trip test covering the admin role Opaque entry, exercising the real JWT serialization seam IsAdminUser depends on rather than only direct context injection, per DeepDiver1975's review. - Correct the changelog entry: ReadOnly/CloseUrl (and DownloadUrl for Microsoft) already had matching `case` handling in microsoft.go/ onlyoffice.go, so populating them unconditionally changes those targets' output too, not just Collabora's. Only IsUserLocked/ IsAdminUser are genuinely Collabora-only. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: David Walter <david.walter@kiteworks.com> --------- Signed-off-by: David Walter <david.walter@kiteworks.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> Co-authored-by: Juan Pablo Villafañez <jpvillafanez@izertis.com>
385 lines
14 KiB
Go
385 lines
14 KiB
Go
package connector
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/tls"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
appproviderv1beta1 "github.com/cs3org/go-cs3apis/cs3/app/provider/v1beta1"
|
|
gatewayv1beta1 "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
|
|
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/tracing"
|
|
"github.com/owncloud/ocis/v2/services/collaboration/pkg/config"
|
|
"github.com/owncloud/ocis/v2/services/collaboration/pkg/middleware"
|
|
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
|
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
|
"github.com/owncloud/reva/v2/pkg/rhttp"
|
|
"github.com/rs/zerolog"
|
|
)
|
|
|
|
// ContentConnectorService is the interface to implement the "File contents"
|
|
// endpoint. Basically upload and download contents.
|
|
// All operations need a context containing a WOPI context and, optionally,
|
|
// a zerolog logger.
|
|
// Target file is within the WOPI context
|
|
type ContentConnectorService interface {
|
|
// GetFile downloads the file and write its contents in the provider writer
|
|
GetFile(ctx context.Context, w http.ResponseWriter) error
|
|
// PutFile uploads the stream up to the stream length. The file should be
|
|
// locked beforehand, so the lockID needs to be provided.
|
|
// The current lockID will be returned ONLY if a conflict happens (the file is
|
|
// locked with a different lockID)
|
|
PutFile(ctx context.Context, stream io.Reader, streamLength int64, lockID string) (*ConnectorResponse, error)
|
|
}
|
|
|
|
// ContentConnector implements the "File contents" endpoint.
|
|
// Basically, the ContentConnector handles downloads (GetFile) and
|
|
// uploads (PutFile)
|
|
// Note that operations might return any kind of error, not just ConnectorError
|
|
type ContentConnector struct {
|
|
gws pool.Selectable[gatewayv1beta1.GatewayAPIClient]
|
|
cfg *config.Config
|
|
}
|
|
|
|
// NewContentConnector creates a new content connector
|
|
func NewContentConnector(gws pool.Selectable[gatewayv1beta1.GatewayAPIClient], cfg *config.Config) *ContentConnector {
|
|
return &ContentConnector{
|
|
gws: gws,
|
|
cfg: cfg,
|
|
}
|
|
}
|
|
|
|
func newHttpRequest(ctx context.Context, wopiContext middleware.WopiContext, method, url, transferToken string, body io.Reader) (*http.Request, error) {
|
|
httpReq, err := tracing.GetNewRequestWithContext(ctx, method, url, body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if url == "" {
|
|
return nil, NewConnectorError(500, "url is missing")
|
|
}
|
|
if transferToken != "" {
|
|
httpReq.Header.Add("X-Reva-Transfer", transferToken)
|
|
}
|
|
if wopiContext.ViewMode == appproviderv1beta1.ViewMode_VIEW_MODE_VIEW_ONLY && wopiContext.ViewOnlyToken != "" {
|
|
httpReq.Header.Add("X-Access-Token", wopiContext.ViewOnlyToken)
|
|
} else {
|
|
httpReq.Header.Add("X-Access-Token", wopiContext.AccessToken)
|
|
}
|
|
return httpReq, nil
|
|
}
|
|
|
|
// GetFile downloads the file from the storage
|
|
// https://docs.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/getfile
|
|
//
|
|
// The context MUST have a WOPI context, otherwise an error will be returned.
|
|
// You can pass a pre-configured zerologger instance through the context that
|
|
// will be used to log messages.
|
|
//
|
|
// The contents of the file will be written directly into the http Response writer passed as
|
|
// parameter.
|
|
// Be aware that the body of the response will be written during the execution of this method.
|
|
// Any further modifications to the response headers or body will be ignored.
|
|
func (c *ContentConnector) GetFile(ctx context.Context, w http.ResponseWriter) error {
|
|
wopiContext, err := middleware.WopiContextFromCtx(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
logger := zerolog.Ctx(ctx).With().
|
|
Interface("FileReference", wopiContext.FileReference).
|
|
Logger()
|
|
logger.Debug().Msg("GetFile: start")
|
|
|
|
gwc, err := c.gws.Next()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
sResp, err := gwc.Stat(ctx, &providerv1beta1.StatRequest{
|
|
Ref: wopiContext.FileReference,
|
|
})
|
|
if err := requestFailed(logger, sResp.GetStatus(), false, err, "GetFile: Stat Request failed"); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Initiate download request
|
|
req := &providerv1beta1.InitiateFileDownloadRequest{
|
|
Ref: wopiContext.FileReference,
|
|
}
|
|
|
|
if wopiContext.ViewMode == appproviderv1beta1.ViewMode_VIEW_MODE_VIEW_ONLY && wopiContext.ViewOnlyToken != "" {
|
|
ctx = revactx.ContextSetToken(ctx, wopiContext.ViewOnlyToken)
|
|
}
|
|
gwc, err = c.gws.Next()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
resp, err := gwc.InitiateFileDownload(ctx, req)
|
|
if err := requestFailed(logger, resp.GetStatus(), false, err, "GetFile: InitiateFileDownload failed"); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Figure out the download endpoint and download token
|
|
downloadEndpoint := ""
|
|
downloadToken := ""
|
|
hasDownloadToken := false
|
|
|
|
for _, proto := range resp.GetProtocols() {
|
|
if proto.GetProtocol() == "simple" || proto.GetProtocol() == "spaces" {
|
|
downloadEndpoint = proto.GetDownloadEndpoint()
|
|
downloadToken = proto.GetToken()
|
|
hasDownloadToken = proto.GetToken() != ""
|
|
break
|
|
}
|
|
}
|
|
|
|
logger = logger.With().
|
|
Str("Endpoint", downloadEndpoint).
|
|
Bool("HasDownloadToken", hasDownloadToken).Logger()
|
|
|
|
// autopropagation of metadata is already included in the client
|
|
httpClient := rhttp.GetHTTPClient(
|
|
rhttp.MinVersion(tls.VersionTLS12),
|
|
rhttp.Insecure(c.cfg.CS3Api.DataGateway.Insecure),
|
|
)
|
|
|
|
// Prepare the request to download the file
|
|
// public link downloads have the token in the download endpoint
|
|
httpReq, err := newHttpRequest(ctx, wopiContext, http.MethodGet, downloadEndpoint, downloadToken, bytes.NewReader([]byte("")))
|
|
if err != nil {
|
|
logger.Error().Err(err).Msg("GetFile: Could not create the request to the endpoint")
|
|
return err
|
|
}
|
|
|
|
httpResp, err := httpClient.Do(httpReq)
|
|
if err != nil {
|
|
logger.Error().Err(err).Msg("GetFile: Get request to the download endpoint failed")
|
|
return err
|
|
}
|
|
|
|
defer httpResp.Body.Close()
|
|
|
|
if httpResp.StatusCode != http.StatusOK {
|
|
logger.Error().
|
|
Int("HttpCode", httpResp.StatusCode).
|
|
Msg("GetFile: downloading the file failed")
|
|
return NewConnectorError(500, "GetFile: Downloading the file failed")
|
|
}
|
|
|
|
w.Header().Set(HeaderWopiVersion, getVersion(sResp.GetInfo().GetMtime()))
|
|
|
|
// Copy the download into the writer
|
|
_, err = io.Copy(w, httpResp.Body)
|
|
if err != nil {
|
|
logger.Error().Msg("GetFile: copying the file content to the response body failed")
|
|
return err
|
|
}
|
|
logger.Debug().Msg("GetFile: success")
|
|
return nil
|
|
}
|
|
|
|
// PutFile uploads the file to the storage
|
|
// https://docs.microsoft.com/en-us/microsoft-365/cloud-storage-partner-program/rest/files/putfile
|
|
//
|
|
// The context MUST have a WOPI context, otherwise an error will be returned.
|
|
// You can pass a pre-configured zerologger instance through the context that
|
|
// will be used to log messages.
|
|
//
|
|
// The contents of the file will be read from the stream. The full stream
|
|
// length must be provided in order to upload the file.
|
|
//
|
|
// A lock ID must be provided for the upload (which must match the lock in the
|
|
// file). The only case where an empty lock ID can be used is if the target
|
|
// file has 0 size.
|
|
//
|
|
// This method will return the lock ID that should be returned in case of a
|
|
// conflict, otherwise it will return an empty string. This means that if the
|
|
// method returns a ConnectorError with code 409, the returned string is the
|
|
// lock ID that should be used in the X-WOPI-Lock header. In other error
|
|
// cases or if the method is successful, an empty string will be returned
|
|
// (check for err != nil to know if something went wrong)
|
|
//
|
|
// On success, the method will return the new mtime of the file.
|
|
func (c *ContentConnector) PutFile(ctx context.Context, stream io.Reader, streamLength int64, lockID string) (*ConnectorResponse, error) {
|
|
wopiContext, err := middleware.WopiContextFromCtx(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
logger := zerolog.Ctx(ctx).With().
|
|
Str("RequestedLockID", lockID).
|
|
Int64("UploadLength", streamLength).
|
|
Interface("FileReference", wopiContext.FileReference).
|
|
Logger()
|
|
logger.Debug().Msg("PutFile: start")
|
|
|
|
gwc, err := c.gws.Next()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// We need a stat call on the target file in order to get both the lock
|
|
// (if any) and the current size of the file
|
|
statRes, err := gwc.Stat(ctx, &providerv1beta1.StatRequest{
|
|
Ref: wopiContext.FileReference,
|
|
})
|
|
// we can ignore a not found error here, as we're going to create the file
|
|
if err := requestFailed(logger, statRes.GetStatus(), true, err, "PutFile: stat failed"); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
mtime := statRes.GetInfo().GetMtime()
|
|
// If there is a lock and it mismatches, return 409
|
|
if statRes.GetInfo().GetLock() != nil && statRes.GetInfo().GetLock().GetLockId() != lockID {
|
|
logger.Error().
|
|
Str("LockID", statRes.GetInfo().GetLock().GetLockId()).
|
|
Msg("PutFile: wrong lock")
|
|
// onlyoffice says it's required to send the current lockId, MS doesn't say anything
|
|
return NewResponseLockConflict(statRes.GetInfo().GetLock().GetLockId(), "Lock Mismatch"), nil
|
|
}
|
|
|
|
// only unlocked uploads can go through if the target file is empty,
|
|
// otherwise the X-WOPI-Lock header is required even if there is no lock on the file
|
|
// This is part of the onlyoffice documentation (https://api.onlyoffice.com/editors/wopi/restapi/putfile)
|
|
// Wopivalidator fails some tests if we don't also check for the X-WOPI-Lock header.
|
|
if lockID == "" && statRes.GetInfo().GetLock() == nil && statRes.GetInfo().GetSize() > 0 {
|
|
logger.Error().Msg("PutFile: file must be locked first")
|
|
// onlyoffice says to send an empty string if the file is unlocked, MS doesn't say anything
|
|
return NewResponseLockConflict("", "Cannot PutFile on unlocked file"), nil
|
|
}
|
|
|
|
// Prepare the data to initiate the upload
|
|
opaque := &types.Opaque{
|
|
Map: make(map[string]*types.OpaqueEntry),
|
|
}
|
|
|
|
if streamLength >= 0 {
|
|
opaque.Map["Upload-Length"] = &types.OpaqueEntry{
|
|
Decoder: "plain",
|
|
Value: []byte(strconv.FormatInt(streamLength, 10)),
|
|
}
|
|
}
|
|
|
|
req := &providerv1beta1.InitiateFileUploadRequest{
|
|
Opaque: opaque,
|
|
Ref: wopiContext.FileReference,
|
|
LockId: lockID,
|
|
Options: &providerv1beta1.InitiateFileUploadRequest_IfMatch{
|
|
IfMatch: statRes.GetInfo().GetEtag(),
|
|
},
|
|
}
|
|
|
|
gwc, err = c.gws.Next()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// Initiate the upload request
|
|
resp, err := gwc.InitiateFileUpload(ctx, req)
|
|
if err := requestFailed(logger, resp.GetStatus(), false, err, "PutFile: InitiateFileUpload failed"); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// if the content length is greater than 0, we need to upload the content to the
|
|
// target endpoint, otherwise we're done
|
|
if streamLength > 0 {
|
|
|
|
uploadEndpoint := ""
|
|
uploadToken := ""
|
|
hasUploadToken := false
|
|
|
|
for _, proto := range resp.GetProtocols() {
|
|
if proto.GetProtocol() == "simple" || proto.GetProtocol() == "spaces" {
|
|
uploadEndpoint = proto.GetUploadEndpoint()
|
|
uploadToken = proto.GetToken()
|
|
hasUploadToken = proto.GetToken() != ""
|
|
break
|
|
}
|
|
}
|
|
|
|
logger = logger.With().
|
|
Str("Endpoint", uploadEndpoint).
|
|
Bool("HasUploadToken", hasUploadToken).Logger()
|
|
|
|
// autopropagation of metadata is already included in the client
|
|
httpClient := rhttp.GetHTTPClient(
|
|
rhttp.MinVersion(tls.VersionTLS12),
|
|
rhttp.Insecure(c.cfg.CS3Api.DataGateway.Insecure),
|
|
rhttp.Timeout(10*time.Second),
|
|
)
|
|
|
|
// prepare the request to upload the contents to the upload endpoint
|
|
// public link uploads have the token in the upload endpoint
|
|
httpReq, err := newHttpRequest(ctx, wopiContext, http.MethodPut, uploadEndpoint, uploadToken, stream)
|
|
if err != nil {
|
|
logger.Error().Err(err).Msg("UploadHelper: Could not create the request to the endpoint")
|
|
return nil, err
|
|
}
|
|
// "stream" is an *http.body and doesn't fill the httpReq.ContentLength automatically
|
|
// we need to fill the ContentLength ourselves, and must match the stream length in order
|
|
// to prevent issues
|
|
httpReq.ContentLength = streamLength
|
|
|
|
httpReq.Header.Add("X-Lock-Id", lockID)
|
|
// TODO: better mechanism for the upload while locked, relies on patch in REVA
|
|
//if lockID, ok := ctxpkg.ContextGetLockID(ctx); ok {
|
|
// httpReq.Header.Add("X-Lock-Id", lockID)
|
|
//}
|
|
|
|
httpResp, err := httpClient.Do(httpReq)
|
|
if err != nil {
|
|
logger.Error().Err(err).Msg("UploadHelper: Put request to the upload endpoint failed")
|
|
return nil, err
|
|
}
|
|
defer httpResp.Body.Close()
|
|
|
|
if httpResp.StatusCode != http.StatusOK {
|
|
logger.Error().
|
|
Int("HttpCode", httpResp.StatusCode).
|
|
Msg("UploadHelper: Put request to the upload endpoint failed with unexpected status")
|
|
return nil, NewConnectorError(500, fmt.Sprintf("unexpected status code %d from the upload endpoint", httpResp.StatusCode))
|
|
}
|
|
gwc, err = c.gws.Next()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// We need a stat call on the target file after the upload to get the
|
|
// new mtime
|
|
statResAfter, err := gwc.Stat(ctx, &providerv1beta1.StatRequest{
|
|
Ref: wopiContext.FileReference,
|
|
})
|
|
if err := requestFailed(logger, statResAfter.GetStatus(), false, err, "PutFile: stat after upload failed"); err != nil {
|
|
return nil, err
|
|
}
|
|
mtime = statResAfter.GetInfo().GetMtime()
|
|
}
|
|
|
|
logger.Debug().Msg("PutFile: success")
|
|
return NewResponseWithVersion(mtime), nil
|
|
}
|
|
|
|
func requestFailed(logger zerolog.Logger, s *rpcv1beta1.Status, allowNotFound bool, err error, msg string) error {
|
|
switch {
|
|
case err != nil: // a connection error
|
|
logger.Error().Err(err).Msg(msg)
|
|
return err
|
|
case s == nil: // we need a status
|
|
logger.Error().Msg(msg + ": nil status")
|
|
return NewConnectorError(500, msg+": nil status")
|
|
case s.GetCode() == rpcv1beta1.Code_CODE_OK: // ok is fine
|
|
return nil
|
|
case allowNotFound && s.GetCode() == rpcv1beta1.Code_CODE_NOT_FOUND: // not found might be ok
|
|
return nil
|
|
default: // any other status is an error
|
|
logger.Error().
|
|
Str("StatusCode", s.GetCode().String()).
|
|
Str("StatusMsg", s.GetMessage()).
|
|
Msg(msg)
|
|
return NewConnectorError(500, s.GetCode().String()+" "+s.GetMessage())
|
|
}
|
|
}
|