feat(collaboration): close WOPI property gaps (#12593)

* 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>
This commit is contained in:
authored and GitHub committed 2026-08-25 18:01:56 +02:00
1 parent 79dbfa1af0
commit 4d9c46f3a7
13 files changed
+3129 -44

No files matched your search

@@ -0,0 +1,21 @@
Enhancement: Close Collabora WOPI CheckFileInfo property gaps
The collaboration service's Collabora CheckFileInfo response was missing several
properties that the Microsoft and OnlyOffice fileinfo types already had `case`
handling for, but that were never populated in the shared properties map:
Version, LastModifiedTime, ReadOnly, SupportsUpdate, IsAnonymousUser, several
file URLs (CloseUrl, DownloadUrl, plus the already-computed HostEditUrl/
HostViewUrl/FileSharingUrl/FileVersionUrl), the BreadcrumbBrandName/
BreadcrumbBrandUrl breadcrumb pair, an EditModePostMessage flag, and two new
Collabora-specific properties, IsUserLocked and IsAdminUser.
We've added all of these. Note that since Microsoft and OnlyOffice already had
`case` handling for ReadOnly and CloseUrl (and Microsoft for DownloadUrl too),
populating those keys unconditionally changes their CheckFileInfo output as
well, not just Collabora's: ReadOnly now actually surfaces as `true` for
read-only/view-only sessions on all three targets, and CloseUrl (plus
DownloadUrl for Microsoft) is now populated where it previously wasn't. Only
IsUserLocked and IsAdminUser are genuinely Collabora-only additions with no
matching `case` elsewhere.
https://github.com/owncloud/ocis/pull/12593
@@ -205,7 +205,7 @@ func (c *ContentConnector) GetFile(ctx context.Context, w http.ResponseWriter) e
// 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
// 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 {
@@ -6,10 +6,12 @@ import (
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/url"
"path"
"slices"
"strings"
"time"
@@ -28,6 +30,7 @@ import (
"github.com/owncloud/ocis/v2/services/collaboration/pkg/helpers"
"github.com/owncloud/ocis/v2/services/collaboration/pkg/middleware"
"github.com/owncloud/ocis/v2/services/collaboration/pkg/wopisrc"
"github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults"
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/storagespace"
@@ -1225,6 +1228,18 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
}
}
// IsAdminUser is a Collabora-specific property that unlocks the server audit panel.
// It must only be set for the built-in oCIS admin role, never for SpaceAdmin or any
// other role, so the admin role UUID is compared explicitly rather than checking for
// "any elevated role".
isAdminUser := false
if rolesEntry, ok := user.GetOpaque().GetMap()["roles"]; ok {
var roleIDs []string
if err := json.Unmarshal(rolesEntry.GetValue(), &roleIDs); err == nil {
isAdminUser = slices.Contains(roleIDs, defaults.BundleUUIDRoleAdmin)
}
}
breadcrumbFolderName := path.Dir(statRes.GetInfo().GetPath())
if breadcrumbFolderName == "." || breadcrumbFolderName == "" || breadcrumbFolderName == "/" {
breadcrumbFolderName = statRes.GetInfo().GetSpace().GetName()
@@ -1257,6 +1272,22 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
logger.Error().Err(err).Msg("CheckFileInfo: error getting scopes from the context")
}
}
// BreadcrumbBrandURL points at the space's root resource, exposing an internal
// space/resource id; for public shares an anonymous user has no other way to reach
// that id, so (like parentFolderURL above) the link is withheld. BreadcrumbBrandName
// is just a display string, not a navigable link, so it stays populated either way.
// Only build the link when the stat response actually carries space info: without a
// root resource id there is nothing to point at, and joining an empty id into the
// path would otherwise produce a misleading bare ".../f" URL.
breadcrumbBrandURL := ""
if !isPublicShare {
if spaceRoot := statRes.GetInfo().GetSpace().GetRoot(); spaceRoot != nil {
brandURL := &url.URL{}
*brandURL = *ocisURL
brandURL.Path = path.Join(ocisURL.Path, "f", storagespace.FormatResourceID(spaceRoot))
breadcrumbBrandURL = brandURL.String()
}
}
// fileinfo map
var size interface{}
size = int64(statRes.GetInfo().GetSize())
@@ -1284,6 +1315,11 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
// to get the folder we actually need to do a GetPath() request
fileinfo.KeyBreadcrumbFolderName: breadcrumbFolderName,
fileinfo.KeyBreadcrumbFolderURL: parentFolderURL.String(),
fileinfo.KeyBreadcrumbBrandName: statRes.GetInfo().GetSpace().GetName(),
fileinfo.KeyBreadcrumbBrandURL: breadcrumbBrandURL,
// the WOPI client should navigate here when the editor is closed; the folder
// containing the file is the same target used for the breadcrumb folder link
fileinfo.KeyCloseURL: parentFolderURL.String(),
fileinfo.KeyHostViewURL: createHostUrl("view", ocisURL, f.cfg.App.Name, statRes.GetInfo()),
fileinfo.KeyHostEditURL: createHostUrl("write", ocisURL, f.cfg.App.Name, statRes.GetInfo()),
@@ -1301,11 +1337,23 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
fileinfo.KeyIsAnonymousUser: isAnonymousUser,
fileinfo.KeyUserFriendlyName: userFriendlyName,
fileinfo.KeyUserID: userId,
fileinfo.KeyIsAdminUser: isAdminUser, // only for collabora
fileinfo.KeyPostMessageOrigin: f.cfg.Commons.OcisURL,
fileinfo.KeyLicenseCheckForEditIsEnabled: f.cfg.App.LicenseCheckEnable,
}
infoMap[fileinfo.KeyReadOnly] = wopiContext.ViewMode != appproviderv1beta1.ViewMode_VIEW_MODE_READ_WRITE
// Only Collabora currently has a web frontend handler wired up for UI_Edit; the other
// PostMessage flags (Close, EditNotification, FileSharing, FileVersion) are left unset
// so Collabora falls back to the corresponding URL properties instead of sending
// PostMessages nobody listens for. OnlyOffice's SetProperties also implements these
// keys, so this must stay an explicit target check rather than an unconditional write.
if strings.ToLower(f.cfg.App.Product) == "collabora" {
infoMap[fileinfo.KeyEditModePostMessage] = true
}
switch wopiContext.ViewMode {
case appproviderv1beta1.ViewMode_VIEW_MODE_READ_WRITE:
infoMap[fileinfo.KeyUserCanWrite] = true
@@ -1318,8 +1366,16 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
infoMap[fileinfo.KeyDisableExport] = true // only for collabora
infoMap[fileinfo.KeyDisableCopy] = true // only for collabora
infoMap[fileinfo.KeyDisablePrint] = true
if !isPublicShare && wopiContext.ViewOnlyToken != "" {
infoMap[fileinfo.KeyWatermarkText] = f.watermarkText(user) // only for collabora
if wopiContext.ViewOnlyToken != "" {
// Secure-view access (view-only mode reached via a view-only token) is the
// codebase's existing definition of a locked-down session; apply Collabora's
// feature-locking on top of the Disable*/watermark restrictions above,
// regardless of whether the user is a public-share guest or authenticated.
infoMap[fileinfo.KeyIsUserLocked] = true // only for collabora
if !isPublicShare {
infoMap[fileinfo.KeyWatermarkText] = f.watermarkText(user) // only for collabora
}
}
}
@@ -1330,12 +1386,44 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
}
}
// a direct download link for the current file; omitted (not a hard failure) if the
// wopi access token can't be generated, e.g. due to a token store misconfiguration
if du, err := f.createFileDownloadURL(wopiContext, collaborationURL); err == nil {
infoMap[fileinfo.KeyDownloadURL] = du
} else {
logger.Error().Err(err).Msg("CheckFileInfo: failed to create download URL")
}
info.SetProperties(infoMap)
logger.Debug().Interface("FileInfo", info).Msg("CheckFileInfo: success")
return NewResponseSuccessBody(info), nil
}
// createWopiResourceURL builds a URL pointing at one of the collaboration service's own
// WOPI routes for the file referenced by wopiContext, hashing the resource id into the
// path and attaching a freshly generated WOPI access token as the "access_token" query
// parameter. routePrefix selects the route (e.g. "wopi/files" or "wopi/templates") and
// pathSuffix is appended after the hashed resource id (e.g. "contents", or "" when the
// route ends at the hash).
func (f *FileConnector) createWopiResourceURL(wopiContext middleware.WopiContext, collaborationURL *url.URL, routePrefix string, pathSuffix string) (string, error) {
token, _, err := middleware.GenerateWopiToken(wopiContext, f.cfg, f.store)
if err != nil {
return "", err
}
resourceURL := *collaborationURL
resourceURL.Path = path.Join(
collaborationURL.Path,
routePrefix,
helpers.HashResourceId(wopiContext.FileReference.GetResourceId()),
pathSuffix,
)
q := resourceURL.Query()
q.Add("access_token", token)
resourceURL.RawQuery = q.Encode()
return resourceURL.String(), nil
}
// createDownloadURL will create a download URL for the template file.
// It uses a new wopi context with the template reference set as the file reference
// and a reva access token to download the file.
@@ -1344,20 +1432,15 @@ func (f *FileConnector) createDownloadURL(wopiContext middleware.WopiContext, co
templateContext.FileReference = wopiContext.TemplateReference
templateContext.TemplateReference = nil
token, _, err := middleware.GenerateWopiToken(templateContext, f.cfg, f.store)
if err != nil {
return "", err
}
downloadURL := *collaborationURL
downloadURL.Path = path.Join(
collaborationURL.Path,
"wopi/templates/",
helpers.HashResourceId(templateContext.FileReference.GetResourceId()),
)
q := downloadURL.Query()
q.Add("access_token", token)
downloadURL.RawQuery = q.Encode()
return downloadURL.String(), nil
return f.createWopiResourceURL(templateContext, collaborationURL, "wopi/templates", "")
}
// createFileDownloadURL creates a direct download URL for the current file (as opposed
// to a template), pointing at the collaboration service's own WOPI file-content route
// (GET /wopi/files/{fileid}/contents), authenticated via a freshly generated WOPI access
// token. Used for the WOPI DownloadUrl CheckFileInfo property.
func (f *FileConnector) createFileDownloadURL(wopiContext middleware.WopiContext, collaborationURL *url.URL) (string, error) {
return f.createWopiResourceURL(wopiContext, collaborationURL, "wopi/files", "contents")
}
func createHostUrl(mode string, ocisUrl *url.URL, appName string, info *providerv1beta1.ResourceInfo) string {
File diff suppressed because it is too large. Load diff
@@ -29,6 +29,46 @@ type Collabora struct {
UserID string `json:"UserId,omitempty"`
// copied from MS WOPI
UserFriendlyName string `json:"UserFriendlyName,omitempty"`
// copied from MS WOPI
Version string `json:"Version,omitempty"`
// copied from MS WOPI - required for Collabora conflict detection via X-COOL-WOPI-Timestamp
LastModifiedTime string `json:"LastModifiedTime,omitempty"`
// copied from MS WOPI
ReadOnly bool `json:"ReadOnly"`
//
// PostMessage properties
//
// Specifies if Collabora should send UI_Close PostMessage when the user closes the editor
ClosePostMessage bool `json:"ClosePostMessage,omitempty"`
// Specifies if Collabora should send UI_Edit PostMessage when the user activates edit mode
EditModePostMessage bool `json:"EditModePostMessage,omitempty"`
// Specifies if Collabora should send Edit_Notification PostMessage when the user starts editing
EditNotificationPostMessage bool `json:"EditNotificationPostMessage,omitempty"`
// Specifies if Collabora should send UI_Sharing PostMessage when the user activates the share UI
FileSharingPostMessage bool `json:"FileSharingPostMessage,omitempty"`
// Specifies if Collabora should send UI_FileVersions PostMessage when the user activates version history
FileVersionPostMessage bool `json:"FileVersionPostMessage,omitempty"`
//
// File URL properties
//
// copied from MS WOPI
CloseURL string `json:"CloseUrl,omitempty"`
// copied from MS WOPI
DownloadURL string `json:"DownloadUrl,omitempty"`
// copied from MS WOPI
FileSharingURL string `json:"FileSharingUrl,omitempty"`
// copied from MS WOPI
FileVersionURL string `json:"FileVersionUrl,omitempty"`
// copied from MS WOPI
HostEditURL string `json:"HostEditUrl,omitempty"`
// copied from MS WOPI
HostViewURL string `json:"HostViewUrl,omitempty"`
// copied from MS WOPI
SignoutURL string `json:"SignoutUrl,omitempty"`
//
// Extended response properties
@@ -73,11 +113,29 @@ type Collabora struct {
// If set to "true", user list on the status bar will be hidden
// If set to "mobile" | "tablet" | "desktop", will be hidden on a specified device
// (may be joint, delimited by commas eg. "mobile,tablet")
HideUserList string `json:"HideUserList,omitempty"`
SupportsLocks bool `json:"SupportsLocks"`
SupportsRename bool `json:"SupportsRename"`
HideUserList string `json:"HideUserList,omitempty"`
SupportsLocks bool `json:"SupportsLocks"`
SupportsRename bool `json:"SupportsRename"`
// copied from MS WOPI
SupportsUpdate bool `json:"SupportsUpdate"`
UserCanRename bool `json:"UserCanRename"`
BreadcrumbDocName string `json:"BreadcrumbDocName,omitempty"`
// copied from MS WOPI
IsAnonymousUser bool `json:"IsAnonymousUser,omitempty"`
// copied from MS WOPI
BreadcrumbBrandName string `json:"BreadcrumbBrandName,omitempty"`
// copied from MS WOPI
BreadcrumbBrandURL string `json:"BreadcrumbBrandUrl,omitempty"`
// copied from MS WOPI
BreadcrumbFolderName string `json:"BreadcrumbFolderName,omitempty"`
// copied from MS WOPI
BreadcrumbFolderURL string `json:"BreadcrumbFolderUrl,omitempty"`
// Collabora-specific: when true, Collabora applies the locked_commands configuration
// from coolwsd.xml to this user, restricting which UNO commands they can access.
IsUserLocked bool `json:"IsUserLocked,omitempty"`
// Collabora-specific: when true, Collabora shows the server audit panel to this user.
// Only oCIS system administrators should receive this flag.
IsAdminUser bool `json:"IsAdminUser,omitempty"`
}
// SetProperties will set the file properties for the Collabora implementation.
@@ -104,6 +162,38 @@ func (cinfo *Collabora) SetProperties(props map[string]interface{}) {
cinfo.UserID = value.(string)
case KeyUserFriendlyName:
cinfo.UserFriendlyName = value.(string)
case KeyVersion:
cinfo.Version = value.(string)
case KeyLastModifiedTime:
cinfo.LastModifiedTime = value.(string)
case KeyReadOnly:
cinfo.ReadOnly = value.(bool)
case KeyClosePostMessage:
cinfo.ClosePostMessage = value.(bool)
case KeyEditModePostMessage:
cinfo.EditModePostMessage = value.(bool)
case KeyEditNotificationPostMessage:
cinfo.EditNotificationPostMessage = value.(bool)
case KeyFileSharingPostMessage:
cinfo.FileSharingPostMessage = value.(bool)
case KeyFileVersionPostMessage:
cinfo.FileVersionPostMessage = value.(bool)
case KeyCloseURL:
cinfo.CloseURL = value.(string)
case KeyDownloadURL:
cinfo.DownloadURL = value.(string)
case KeyFileSharingURL:
cinfo.FileSharingURL = value.(string)
case KeyFileVersionURL:
cinfo.FileVersionURL = value.(string)
case KeyHostEditURL:
cinfo.HostEditURL = value.(string)
case KeyHostViewURL:
cinfo.HostViewURL = value.(string)
case KeySignoutURL:
cinfo.SignoutURL = value.(string)
case KeyEnableInsertRemoteImage:
cinfo.EnableInsertRemoteImage = value.(bool)
@@ -140,10 +230,26 @@ func (cinfo *Collabora) SetProperties(props map[string]interface{}) {
cinfo.SupportsLocks = value.(bool)
case KeySupportsRename:
cinfo.SupportsRename = value.(bool)
case KeySupportsUpdate:
cinfo.SupportsUpdate = value.(bool)
case KeyUserCanRename:
cinfo.UserCanRename = value.(bool)
case KeyBreadcrumbDocName:
cinfo.BreadcrumbDocName = value.(string)
case KeyIsAnonymousUser:
cinfo.IsAnonymousUser = value.(bool)
case KeyBreadcrumbBrandName:
cinfo.BreadcrumbBrandName = value.(string)
case KeyBreadcrumbBrandURL:
cinfo.BreadcrumbBrandURL = value.(string)
case KeyBreadcrumbFolderName:
cinfo.BreadcrumbFolderName = value.(string)
case KeyBreadcrumbFolderURL:
cinfo.BreadcrumbFolderURL = value.(string)
case KeyIsUserLocked:
cinfo.IsUserLocked = value.(bool)
case KeyIsAdminUser:
cinfo.IsAdminUser = value.(bool)
}
}
}
@@ -0,0 +1,886 @@
package fileinfo
import (
"encoding/json"
"testing"
)
func TestCollaboraSetPropertiesVersion(t *testing.T) {
tests := []struct {
name string
version string
expectedResult string
}{
{
name: "Version set correctly",
version: "v42",
expectedResult: "v42",
},
{
name: "Empty version",
version: "",
expectedResult: "",
},
{
name: "Complex version string",
version: "2024-07-16T12:34:56Z",
expectedResult: "2024-07-16T12:34:56Z",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cinfo := &Collabora{}
cinfo.SetProperties(map[string]interface{}{
KeyVersion: tt.version,
})
if cinfo.Version != tt.expectedResult {
t.Errorf("SetProperties Version: got %q, want %q", cinfo.Version, tt.expectedResult)
}
})
}
}
func TestCollaboraJSONMarshallingIncludesVersion(t *testing.T) {
tests := []struct {
name string
version string
shouldInclude bool
}{
{
name: "Version with value should be included",
version: "abc123",
shouldInclude: true,
},
{
name: "Empty version should be omitted",
version: "",
shouldInclude: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cinfo := &Collabora{
Version: tt.version,
}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
_, hasVersion := jsonMap["Version"]
if hasVersion != tt.shouldInclude {
if tt.shouldInclude {
t.Errorf("Expected Version field to be in JSON, but it was not")
} else {
t.Errorf("Expected Version field to be omitted from JSON due to omitempty, but it was present")
}
}
if tt.shouldInclude && tt.version != "" {
if val, ok := jsonMap["Version"].(string); !ok || val != tt.version {
t.Errorf("Version field: got %v, want %q", jsonMap["Version"], tt.version)
}
}
})
}
}
func TestCollaboraSetPropertiesLastModifiedTime(t *testing.T) {
tests := []struct {
name string
lastModifiedTime string
expectedResult string
}{
{
name: "LastModifiedTime set correctly",
lastModifiedTime: "2025-04-13T10:00:00.0000000Z",
expectedResult: "2025-04-13T10:00:00.0000000Z",
},
{
name: "Empty LastModifiedTime",
lastModifiedTime: "",
expectedResult: "",
},
{
name: "Complex LastModifiedTime string",
lastModifiedTime: "2024-07-16T12:34:56.1234567Z",
expectedResult: "2024-07-16T12:34:56.1234567Z",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cinfo := &Collabora{}
cinfo.SetProperties(map[string]interface{}{
KeyLastModifiedTime: tt.lastModifiedTime,
})
if cinfo.LastModifiedTime != tt.expectedResult {
t.Errorf("SetProperties LastModifiedTime: got %q, want %q", cinfo.LastModifiedTime, tt.expectedResult)
}
})
}
}
func TestCollaboraJSONMarshallingIncludesLastModifiedTime(t *testing.T) {
tests := []struct {
name string
lastModifiedTime string
shouldInclude bool
}{
{
name: "LastModifiedTime with value should be included",
lastModifiedTime: "2025-04-13T10:00:00.0000000Z",
shouldInclude: true,
},
{
name: "Empty LastModifiedTime should be omitted",
lastModifiedTime: "",
shouldInclude: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cinfo := &Collabora{
LastModifiedTime: tt.lastModifiedTime,
}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
_, hasLastModifiedTime := jsonMap["LastModifiedTime"]
if hasLastModifiedTime != tt.shouldInclude {
if tt.shouldInclude {
t.Errorf("Expected LastModifiedTime field to be in JSON, but it was not")
} else {
t.Errorf("Expected LastModifiedTime field to be omitted from JSON due to omitempty, but it was present")
}
}
if tt.shouldInclude && tt.lastModifiedTime != "" {
if val, ok := jsonMap["LastModifiedTime"].(string); !ok || val != tt.lastModifiedTime {
t.Errorf("LastModifiedTime field: got %v, want %q", jsonMap["LastModifiedTime"], tt.lastModifiedTime)
}
}
})
}
}
func TestCollaboraSetPropertiesReadOnly(t *testing.T) {
tests := []struct {
name string
readOnly bool
expectedResult bool
}{
{
name: "ReadOnly set to true",
readOnly: true,
expectedResult: true,
},
{
name: "ReadOnly set to false",
readOnly: false,
expectedResult: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cinfo := &Collabora{}
cinfo.SetProperties(map[string]interface{}{
KeyReadOnly: tt.readOnly,
})
if cinfo.ReadOnly != tt.expectedResult {
t.Errorf("SetProperties ReadOnly: got %v, want %v", cinfo.ReadOnly, tt.expectedResult)
}
})
}
}
func TestCollaboraJSONMarshallingIncludesReadOnly(t *testing.T) {
// ReadOnly has no `omitempty`, so it must always be present in the JSON
// output, including when false.
tests := []struct {
name string
readOnly bool
}{
{
name: "ReadOnly true is included",
readOnly: true,
},
{
name: "ReadOnly false is included",
readOnly: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cinfo := &Collabora{
ReadOnly: tt.readOnly,
}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
val, hasReadOnly := jsonMap["ReadOnly"]
if !hasReadOnly {
t.Fatalf("Expected ReadOnly field to always be present in JSON (no omitempty), but it was missing: %s", string(jsonBytes))
}
boolVal, ok := val.(bool)
if !ok || boolVal != tt.readOnly {
t.Errorf("ReadOnly field: got %v, want %v", val, tt.readOnly)
}
})
}
}
func TestCollaboraSetPropertiesSupportsUpdate(t *testing.T) {
tests := []struct {
name string
supportsUpdate bool
expectedResult bool
}{
{
name: "SupportsUpdate set to true",
supportsUpdate: true,
expectedResult: true,
},
{
name: "SupportsUpdate set to false",
supportsUpdate: false,
expectedResult: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cinfo := &Collabora{}
cinfo.SetProperties(map[string]interface{}{
KeySupportsUpdate: tt.supportsUpdate,
})
if cinfo.SupportsUpdate != tt.expectedResult {
t.Errorf("SetProperties SupportsUpdate: got %v, want %v", cinfo.SupportsUpdate, tt.expectedResult)
}
})
}
}
func TestCollaboraJSONMarshallingIncludesSupportsUpdate(t *testing.T) {
// SupportsUpdate has no `omitempty`, so it must always be present in the JSON
// output, including when false.
tests := []struct {
name string
supportsUpdate bool
}{
{
name: "SupportsUpdate true is included",
supportsUpdate: true,
},
{
name: "SupportsUpdate false is included",
supportsUpdate: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cinfo := &Collabora{
SupportsUpdate: tt.supportsUpdate,
}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
val, hasSupportsUpdate := jsonMap["SupportsUpdate"]
if !hasSupportsUpdate {
t.Fatalf("Expected SupportsUpdate field to always be present in JSON (no omitempty), but it was missing: %s", string(jsonBytes))
}
boolVal, ok := val.(bool)
if !ok || boolVal != tt.supportsUpdate {
t.Errorf("SupportsUpdate field: got %v, want %v", val, tt.supportsUpdate)
}
})
}
}
func TestCollaboraSetPropertiesIsAnonymousUser(t *testing.T) {
tests := []struct {
name string
isAnonymous bool
expectedResult bool
}{
{
name: "IsAnonymousUser set to true",
isAnonymous: true,
expectedResult: true,
},
{
name: "IsAnonymousUser set to false",
isAnonymous: false,
expectedResult: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cinfo := &Collabora{}
cinfo.SetProperties(map[string]interface{}{
KeyIsAnonymousUser: tt.isAnonymous,
})
if cinfo.IsAnonymousUser != tt.expectedResult {
t.Errorf("SetProperties IsAnonymousUser: got %v, want %v", cinfo.IsAnonymousUser, tt.expectedResult)
}
})
}
}
func TestCollaboraJSONOmitsIsAnonymousUserWhenFalse(t *testing.T) {
// IsAnonymousUser has `omitempty`, so it should be omitted from JSON when false
cinfo := &Collabora{
IsAnonymousUser: false,
}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
_, hasIsAnonymousUser := jsonMap["IsAnonymousUser"]
if hasIsAnonymousUser {
t.Errorf("Expected IsAnonymousUser field to be omitted from JSON when false, but it was present: %s", string(jsonBytes))
}
}
func TestCollaboraJSONIncludesIsAnonymousUserWhenTrue(t *testing.T) {
// IsAnonymousUser has `omitempty`, so it should be included in JSON when true
cinfo := &Collabora{
IsAnonymousUser: true,
}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
val, hasIsAnonymousUser := jsonMap["IsAnonymousUser"]
if !hasIsAnonymousUser {
t.Errorf("Expected IsAnonymousUser field to be in JSON when true, but it was not: %s", string(jsonBytes))
}
boolVal, ok := val.(bool)
if !ok || !boolVal {
t.Errorf("IsAnonymousUser field: got %v, want true", val)
}
}
// urlPropertyCases describes each of the 7 WOPI URL properties added to Collabora: the
// SetProperties key that populates it, the JSON tag it is expected to be marshalled
// under, a getter for its value, and a distinct sample value for it. Used to drive the
// table-driven tests below.
var urlPropertyCases = []struct {
name string
key string
jsonTag string
value string
getter func(*Collabora) string
}{
{"CloseURL", KeyCloseURL, "CloseUrl", "https://ocis.example.prv/close", func(c *Collabora) string { return c.CloseURL }},
{"DownloadURL", KeyDownloadURL, "DownloadUrl", "https://ocis.example.prv/download", func(c *Collabora) string { return c.DownloadURL }},
{"FileSharingURL", KeyFileSharingURL, "FileSharingUrl", "https://ocis.example.prv/share", func(c *Collabora) string { return c.FileSharingURL }},
{"FileVersionURL", KeyFileVersionURL, "FileVersionUrl", "https://ocis.example.prv/versions", func(c *Collabora) string { return c.FileVersionURL }},
{"HostEditURL", KeyHostEditURL, "HostEditUrl", "https://ocis.example.prv/edit", func(c *Collabora) string { return c.HostEditURL }},
{"HostViewURL", KeyHostViewURL, "HostViewUrl", "https://ocis.example.prv/view", func(c *Collabora) string { return c.HostViewURL }},
{"SignoutURL", KeySignoutURL, "SignoutUrl", "https://ocis.example.prv/signout", func(c *Collabora) string { return c.SignoutURL }},
}
// TestCollaboraSetPropertiesURLProperties covers brief item 1: for each of the 7 URL
// properties, SetProperties must correctly set the corresponding struct field.
func TestCollaboraSetPropertiesURLProperties(t *testing.T) {
for _, prop := range urlPropertyCases {
t.Run(prop.name, func(t *testing.T) {
cinfo := &Collabora{}
cinfo.SetProperties(map[string]interface{}{
prop.key: prop.value,
})
if got := prop.getter(cinfo); got != prop.value {
t.Errorf("SetProperties %s: got %q, want %q", prop.name, got, prop.value)
}
})
}
}
// TestCollaboraJSONMarshallingIncludesURLProperties covers brief item 2: marshalling a
// Collabora struct with all 7 URL properties populated must include all of them in the
// resulting JSON, under their MS-WOPI-compatible tag names.
func TestCollaboraJSONMarshallingIncludesURLProperties(t *testing.T) {
cinfo := &Collabora{}
for _, prop := range urlPropertyCases {
cinfo.SetProperties(map[string]interface{}{prop.key: prop.value})
}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
for _, prop := range urlPropertyCases {
val, ok := jsonMap[prop.jsonTag]
if !ok {
t.Errorf("Expected %q field to be in JSON, but it was not: %s", prop.jsonTag, string(jsonBytes))
continue
}
if val != prop.value {
t.Errorf("%s field: got %v, want %q", prop.jsonTag, val, prop.value)
}
}
}
// TestCollaboraJSONOmitsEmptyURLProperties covers brief item 3: each of the 7 URL
// properties has `omitempty` and must be absent from the JSON output when empty.
func TestCollaboraJSONOmitsEmptyURLProperties(t *testing.T) {
cinfo := &Collabora{}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
for _, prop := range urlPropertyCases {
if _, ok := jsonMap[prop.jsonTag]; ok {
t.Errorf("Expected %q field to be omitted from JSON when empty due to omitempty, but it was present: %s", prop.jsonTag, string(jsonBytes))
}
}
}
// TestCollaboraSetPropertiesAllURLPropertiesSimultaneously covers brief item 4: setting
// all 7 URL properties in a single SetProperties call must set all of them correctly.
func TestCollaboraSetPropertiesAllURLPropertiesSimultaneously(t *testing.T) {
props := make(map[string]interface{}, len(urlPropertyCases))
for _, prop := range urlPropertyCases {
props[prop.key] = prop.value
}
cinfo := &Collabora{}
cinfo.SetProperties(props)
for _, prop := range urlPropertyCases {
if got := prop.getter(cinfo); got != prop.value {
t.Errorf("SetProperties %s: got %q, want %q", prop.name, got, prop.value)
}
}
}
// breadcrumbPropertyCases describes each of the 4 breadcrumb WOPI properties added to
// Collabora in addition to the pre-existing BreadcrumbDocName: the SetProperties key
// that populates it, the JSON tag it is expected to be marshalled under, a getter for
// its value, and a distinct sample value for it. Used to drive the table-driven tests
// below.
var breadcrumbPropertyCases = []struct {
name string
key string
jsonTag string
value string
getter func(*Collabora) string
}{
{"BreadcrumbBrandName", KeyBreadcrumbBrandName, "BreadcrumbBrandName", "ownCloud", func(c *Collabora) string { return c.BreadcrumbBrandName }},
{"BreadcrumbBrandURL", KeyBreadcrumbBrandURL, "BreadcrumbBrandUrl", "https://ocis.example.prv/f/storageid$spaceid%21rootid", func(c *Collabora) string { return c.BreadcrumbBrandURL }},
{"BreadcrumbFolderName", KeyBreadcrumbFolderName, "BreadcrumbFolderName", "Documents", func(c *Collabora) string { return c.BreadcrumbFolderName }},
{"BreadcrumbFolderURL", KeyBreadcrumbFolderURL, "BreadcrumbFolderUrl", "https://ocis.example.prv/f/storageid$spaceid%21parentid", func(c *Collabora) string { return c.BreadcrumbFolderURL }},
}
// TestCollaboraSetPropertiesBreadcrumbProperties covers brief item 1: SetProperties with
// all four breadcrumb properties must set each of them correctly.
func TestCollaboraSetPropertiesBreadcrumbProperties(t *testing.T) {
props := make(map[string]interface{}, len(breadcrumbPropertyCases))
for _, prop := range breadcrumbPropertyCases {
props[prop.key] = prop.value
}
cinfo := &Collabora{}
cinfo.SetProperties(props)
for _, prop := range breadcrumbPropertyCases {
if got := prop.getter(cinfo); got != prop.value {
t.Errorf("SetProperties %s: got %q, want %q", prop.name, got, prop.value)
}
}
}
// TestCollaboraJSONMarshallingIncludesBreadcrumbProperties covers brief item 2:
// marshalling a Collabora struct with all four breadcrumb properties populated must
// include all of them in the resulting JSON, under their MS-WOPI-compatible tag names.
func TestCollaboraJSONMarshallingIncludesBreadcrumbProperties(t *testing.T) {
cinfo := &Collabora{}
for _, prop := range breadcrumbPropertyCases {
cinfo.SetProperties(map[string]interface{}{prop.key: prop.value})
}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
for _, prop := range breadcrumbPropertyCases {
val, ok := jsonMap[prop.jsonTag]
if !ok {
t.Errorf("Expected %q field to be in JSON, but it was not: %s", prop.jsonTag, string(jsonBytes))
continue
}
if val != prop.value {
t.Errorf("%s field: got %v, want %q", prop.jsonTag, val, prop.value)
}
}
}
// TestCollaboraJSONOmitsEmptyBreadcrumbProperties covers brief item 3: each of the four
// breadcrumb properties has `omitempty` and must be absent from the JSON output when
// empty.
func TestCollaboraJSONOmitsEmptyBreadcrumbProperties(t *testing.T) {
cinfo := &Collabora{}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
for _, prop := range breadcrumbPropertyCases {
if _, ok := jsonMap[prop.jsonTag]; ok {
t.Errorf("Expected %q field to be omitted from JSON when empty due to omitempty, but it was present: %s", prop.jsonTag, string(jsonBytes))
}
}
}
// TestCollaboraJSONMixedBreadcrumbProperties covers brief item 4: setting only
// BreadcrumbBrandName and BreadcrumbFolderName (leaving BreadcrumbBrandURL and
// BreadcrumbFolderURL empty) must result in only the former two appearing in the
// marshalled JSON.
func TestCollaboraJSONMixedBreadcrumbProperties(t *testing.T) {
cinfo := &Collabora{}
cinfo.SetProperties(map[string]interface{}{
KeyBreadcrumbBrandName: "ownCloud",
KeyBreadcrumbFolderName: "Documents",
})
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
if val, ok := jsonMap["BreadcrumbBrandName"]; !ok || val != "ownCloud" {
t.Errorf("Expected BreadcrumbBrandName to be %q in JSON, got %v (present: %v)", "ownCloud", val, ok)
}
if val, ok := jsonMap["BreadcrumbFolderName"]; !ok || val != "Documents" {
t.Errorf("Expected BreadcrumbFolderName to be %q in JSON, got %v (present: %v)", "Documents", val, ok)
}
if _, ok := jsonMap["BreadcrumbBrandUrl"]; ok {
t.Errorf("Expected BreadcrumbBrandUrl to be omitted from JSON, but it was present: %s", string(jsonBytes))
}
if _, ok := jsonMap["BreadcrumbFolderUrl"]; ok {
t.Errorf("Expected BreadcrumbFolderUrl to be omitted from JSON, but it was present: %s", string(jsonBytes))
}
}
// postMessagePropertyCases describes each of the 5 PostMessage WOPI properties added to
// Collabora: the SetProperties key that populates it, the JSON tag it is expected to be
// marshalled under, and a getter for its value. Used to drive the table-driven tests
// below.
var postMessagePropertyCases = []struct {
name string
key string
jsonTag string
getter func(*Collabora) bool
}{
{"ClosePostMessage", KeyClosePostMessage, "ClosePostMessage", func(c *Collabora) bool { return c.ClosePostMessage }},
{"EditModePostMessage", KeyEditModePostMessage, "EditModePostMessage", func(c *Collabora) bool { return c.EditModePostMessage }},
{"EditNotificationPostMessage", KeyEditNotificationPostMessage, "EditNotificationPostMessage", func(c *Collabora) bool { return c.EditNotificationPostMessage }},
{"FileSharingPostMessage", KeyFileSharingPostMessage, "FileSharingPostMessage", func(c *Collabora) bool { return c.FileSharingPostMessage }},
{"FileVersionPostMessage", KeyFileVersionPostMessage, "FileVersionPostMessage", func(c *Collabora) bool { return c.FileVersionPostMessage }},
}
// TestCollaboraSetPropertiesPostMessageProperties covers brief item 1: for each of the 5
// PostMessage properties, SetProperties must correctly set the corresponding struct field,
// both when set to true and when set to false.
func TestCollaboraSetPropertiesPostMessageProperties(t *testing.T) {
for _, prop := range postMessagePropertyCases {
t.Run(prop.name, func(t *testing.T) {
for _, value := range []bool{true, false} {
cinfo := &Collabora{}
cinfo.SetProperties(map[string]interface{}{
prop.key: value,
})
if got := prop.getter(cinfo); got != value {
t.Errorf("SetProperties %s: got %v, want %v", prop.name, got, value)
}
}
})
}
}
// TestCollaboraJSONMarshallingIncludesPostMessageProperties covers brief item 2:
// marshalling a Collabora struct with all 5 PostMessage properties set to true must
// include all of them in the resulting JSON.
func TestCollaboraJSONMarshallingIncludesPostMessageProperties(t *testing.T) {
cinfo := &Collabora{}
for _, prop := range postMessagePropertyCases {
cinfo.SetProperties(map[string]interface{}{prop.key: true})
}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
for _, prop := range postMessagePropertyCases {
val, ok := jsonMap[prop.jsonTag]
if !ok {
t.Errorf("Expected %q field to be in JSON, but it was not: %s", prop.jsonTag, string(jsonBytes))
continue
}
if val != true {
t.Errorf("%s field: got %v, want true", prop.jsonTag, val)
}
}
}
// TestCollaboraJSONOmitsPostMessagePropertiesWhenFalse covers brief item 3: each of the 5
// PostMessage properties has `omitempty` and must be absent from the JSON output when
// false (the zero value).
func TestCollaboraJSONOmitsPostMessagePropertiesWhenFalse(t *testing.T) {
cinfo := &Collabora{}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
for _, prop := range postMessagePropertyCases {
if _, ok := jsonMap[prop.jsonTag]; ok {
t.Errorf("Expected %q field to be omitted from JSON when false due to omitempty, but it was present: %s", prop.jsonTag, string(jsonBytes))
}
}
}
// TestCollaboraSetPropertiesAllPostMessagePropertiesSimultaneously covers brief item 4:
// setting all 5 PostMessage properties to true in a single SetProperties call must set
// all of them correctly.
func TestCollaboraSetPropertiesAllPostMessagePropertiesSimultaneously(t *testing.T) {
props := make(map[string]interface{}, len(postMessagePropertyCases))
for _, prop := range postMessagePropertyCases {
props[prop.key] = true
}
cinfo := &Collabora{}
cinfo.SetProperties(props)
for _, prop := range postMessagePropertyCases {
if got := prop.getter(cinfo); !got {
t.Errorf("SetProperties %s: got %v, want true", prop.name, got)
}
}
}
// collaboraSpecificPropertyCases describes the 2 Collabora-only WOPI properties added in
// this task (IsUserLocked, IsAdminUser): the SetProperties key that populates it, the
// JSON tag it is expected to be marshalled under, and a getter for its value. Used to
// drive the table-driven tests below.
var collaboraSpecificPropertyCases = []struct {
name string
key string
jsonTag string
getter func(*Collabora) bool
}{
{"IsUserLocked", KeyIsUserLocked, "IsUserLocked", func(c *Collabora) bool { return c.IsUserLocked }},
{"IsAdminUser", KeyIsAdminUser, "IsAdminUser", func(c *Collabora) bool { return c.IsAdminUser }},
}
// TestCollaboraSetPropertiesIsUserLocked covers brief item 1: SetProperties with
// IsUserLocked=true must set the field.
func TestCollaboraSetPropertiesIsUserLocked(t *testing.T) {
cinfo := &Collabora{}
cinfo.SetProperties(map[string]interface{}{
KeyIsUserLocked: true,
})
if !cinfo.IsUserLocked {
t.Errorf("SetProperties IsUserLocked: got %v, want true", cinfo.IsUserLocked)
}
}
// TestCollaboraSetPropertiesIsAdminUser covers brief item 2: SetProperties with
// IsAdminUser=true must set the field.
func TestCollaboraSetPropertiesIsAdminUser(t *testing.T) {
cinfo := &Collabora{}
cinfo.SetProperties(map[string]interface{}{
KeyIsAdminUser: true,
})
if !cinfo.IsAdminUser {
t.Errorf("SetProperties IsAdminUser: got %v, want true", cinfo.IsAdminUser)
}
}
// TestCollaboraSetPropertiesCollaboraSpecificPropertiesFalse verifies SetProperties also
// correctly sets both new properties to false (the values are not simply left at their
// zero-value default by coincidence).
func TestCollaboraSetPropertiesCollaboraSpecificPropertiesFalse(t *testing.T) {
for _, prop := range collaboraSpecificPropertyCases {
t.Run(prop.name, func(t *testing.T) {
cinfo := &Collabora{}
cinfo.SetProperties(map[string]interface{}{
prop.key: false,
})
if got := prop.getter(cinfo); got {
t.Errorf("SetProperties %s: got %v, want false", prop.name, got)
}
})
}
}
// TestCollaboraJSONOmitsCollaboraSpecificPropertiesWhenFalse covers brief item 3: both
// IsUserLocked and IsAdminUser have `omitempty` and must be absent from the JSON output
// when false (the zero value).
func TestCollaboraJSONOmitsCollaboraSpecificPropertiesWhenFalse(t *testing.T) {
cinfo := &Collabora{}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
for _, prop := range collaboraSpecificPropertyCases {
if _, ok := jsonMap[prop.jsonTag]; ok {
t.Errorf("Expected %q field to be omitted from JSON when false due to omitempty, but it was present: %s", prop.jsonTag, string(jsonBytes))
}
}
}
// TestCollaboraJSONIncludesCollaboraSpecificPropertiesWhenTrue covers brief item 4: both
// IsUserLocked and IsAdminUser must be included in the JSON output when true.
func TestCollaboraJSONIncludesCollaboraSpecificPropertiesWhenTrue(t *testing.T) {
cinfo := &Collabora{
IsUserLocked: true,
IsAdminUser: true,
}
jsonBytes, err := json.Marshal(cinfo)
if err != nil {
t.Fatalf("Failed to marshal JSON: %v", err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(jsonBytes, &jsonMap); err != nil {
t.Fatalf("Failed to unmarshal JSON: %v", err)
}
for _, prop := range collaboraSpecificPropertyCases {
val, ok := jsonMap[prop.jsonTag]
if !ok {
t.Errorf("Expected %q field to be in JSON, but it was not: %s", prop.jsonTag, string(jsonBytes))
continue
}
if val != true {
t.Errorf("%s field: got %v, want true", prop.jsonTag, val)
}
}
}
// TestCollaboraConstantsExist covers brief item 5: KeyIsUserLocked and KeyIsAdminUser
// must be defined with their expected wire-property names.
func TestCollaboraConstantsExist(t *testing.T) {
if KeyIsUserLocked != "IsUserLocked" {
t.Errorf("KeyIsUserLocked: got %q, want %q", KeyIsUserLocked, "IsUserLocked")
}
if KeyIsAdminUser != "IsAdminUser" {
t.Errorf("KeyIsAdminUser: got %q, want %q", KeyIsAdminUser, "IsAdminUser")
}
}
@@ -119,6 +119,10 @@ const (
KeyEnableShare = "EnableShare"
KeyHideUserList = "HideUserList"
// Collabora-specific properties (not part of the MS WOPI spec)
KeyIsUserLocked = "IsUserLocked"
KeyIsAdminUser = "IsAdminUser"
// OnlyOffice (non-dupped) properties below
KeyClosePostMessage = "ClosePostMessage"
@@ -2,6 +2,7 @@ package middleware_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
@@ -11,6 +12,7 @@ import (
appprovider "github.com/cs3org/go-cs3apis/cs3/app/provider/v1beta1"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
providerv1beta1 "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/golang-jwt/jwt/v5"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@@ -18,6 +20,8 @@ import (
"github.com/owncloud/ocis/v2/services/collaboration/pkg/helpers"
"github.com/owncloud/ocis/v2/services/collaboration/pkg/middleware"
"github.com/owncloud/ocis/v2/services/collaboration/pkg/wopisrc"
"github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults"
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/token"
rjwt "github.com/owncloud/reva/v2/pkg/token/manager/jwt"
)
@@ -345,4 +349,73 @@ var _ = Describe("Wopi Context Middleware", func() {
mw.ServeHTTP(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK))
})
It("Should preserve the admin role Opaque entry through the reva token mint/dismantle round trip", func() {
// Unlike the fileinfo/fileconnector tests, which inject the user directly
// into the context via ctxpkg.ContextSetUser (bypassing token serialization
// entirely), this exercises the actual seam IsAdminUser depends on in
// production: the reva access token is minted once at file-open time,
// then later dismantled here on every WOPI request. If the roles Opaque
// entry didn't survive that round trip, IsAdminUser would silently never
// fire despite every direct-injection unit test passing.
rolesJSON, err := json.Marshal([]string{defaults.BundleUUIDRoleAdmin})
Expect(err).ToNot(HaveOccurred())
adminUser := &userv1beta1.User{
Id: &userv1beta1.UserId{
Idp: "example.com",
OpaqueId: "12345",
Type: userv1beta1.UserType_USER_TYPE_PRIMARY,
},
Username: "admin",
Mail: "admin@example.com",
Opaque: &typesv1beta1.Opaque{
Map: map[string]*typesv1beta1.OpaqueEntry{
"roles": {
Decoder: "json",
Value: rolesJSON,
},
},
},
}
var captured *userv1beta1.User
capturingNext := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
captured, _ = ctxpkg.ContextGetUser(r.Context())
w.WriteHeader(http.StatusOK)
})
capturingMw := middleware.WopiContextAuthMiddleware(cfg, nil, capturingNext)
token, err := tknMngr.MintToken(ctx, adminUser, nil)
Expect(err).ToNot(HaveOccurred())
wopiContext := middleware.WopiContext{
AccessToken: token,
ViewMode: appprovider.ViewMode_VIEW_MODE_READ_WRITE,
FileReference: &providerv1beta1.Reference{
ResourceId: rid,
Path: ".",
},
}
wopiToken, ttl, err := middleware.GenerateWopiToken(wopiContext, cfg, nil)
Expect(err).ToNot(HaveOccurred())
req := httptest.NewRequest("GET", src.String(), nil).WithContext(ctx)
q := req.URL.Query()
q.Add("access_token", wopiToken)
q.Add("access_token_ttl", strconv.FormatInt(ttl, 10))
req.URL.RawQuery = q.Encode()
resp := httptest.NewRecorder()
capturingMw.ServeHTTP(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK))
Expect(captured).ToNot(BeNil())
rolesEntry, ok := captured.GetOpaque().GetMap()["roles"]
Expect(ok).To(BeTrue())
var roleIDs []string
Expect(json.Unmarshal(rolesEntry.GetValue(), &roleIDs)).To(Succeed())
Expect(roleIDs).To(ContainElement(defaults.BundleUUIDRoleAdmin))
})
})
@@ -355,7 +355,7 @@ Feature: check file info with different wopi apps
"const": "Alice Hansen"
},
"ReadOnly": {
"const": false
"const": <read-only>
},
"UserCanNotWriteRelative": {
"const": false
@@ -394,10 +394,10 @@ Feature: check file info with different wopi apps
}
"""
Examples:
| mode | disable-print | user-can-write | user-can-rename |
| view | true | false | false |
| read | false | false | false |
| write | false | true | true |
| mode | disable-print | user-can-write | user-can-rename | read-only |
| view | true | false | false | true |
| read | false | false | false | true |
| write | false | true | true | false |
Scenario Outline: check file info with different mode (fakeOffice)
@@ -492,7 +492,7 @@ Feature: check file info with different wopi apps
"const": "Alice Hansen"
},
"ReadOnly": {
"const": false
"const": <read-only>
},
"RestrictedWebViewOnly": {
"const": false
@@ -531,10 +531,10 @@ Feature: check file info with different wopi apps
}
"""
Examples:
| mode | disable-print | user-can-write | user-can-rename |
| view | true | false | false |
| read | false | false | false |
| write | false | true | true |
| mode | disable-print | user-can-write | user-can-rename | read-only |
| view | true | false | false | true |
| read | false | false | false | true |
| write | false | true | true | false |
Scenario Outline: check file info with different view-mode (collabora)
@@ -1587,7 +1587,7 @@ Feature: check file info with different wopi apps
"const": "Alice Hansen"
},
"ReadOnly": {
"const": false
"const": <read-only>
},
"UserCanNotWriteRelative": {
"const": false
@@ -1617,10 +1617,10 @@ Feature: check file info with different wopi apps
}
"""
Examples:
| mode | disable-print | user-can-write | user-can-rename |
| view | true | false | false |
| read | false | false | false |
| write | false | true | true |
| mode | disable-print | user-can-write | user-can-rename | read-only |
| view | true | false | false | true |
| read | false | false | false | true |
| write | false | true | true | false |
Scenario Outline: check the information of a project space file with different modes (fakeOffice)
@@ -1718,7 +1718,7 @@ Feature: check file info with different wopi apps
"const": "Alice Hansen"
},
"ReadOnly": {
"const": false
"const": <read-only>
},
"RestrictedWebViewOnly": {
"const": false
@@ -1757,10 +1757,10 @@ Feature: check file info with different wopi apps
}
"""
Examples:
| mode | disable-print | user-can-write | user-can-rename |
| view | true | false | false |
| read | false | false | false |
| write | false | true | true |
| mode | disable-print | user-can-write | user-can-rename | read-only |
| view | true | false | false | true |
| read | false | false | false | true |
| write | false | true | true | false |
Scenario Outline: check the information of a project space file with different modes (collabora)
@@ -0,0 +1,53 @@
import { expect } from '@playwright/test'
import { test } from '../../environment/test'
import * as api from '../../steps/api/api'
import * as ui from '../../steps/ui/index'
import { application } from '../../environment/constants'
import { getWorld } from '../../environment/world'
const suites = [
{
name: 'Collabora',
viewer: application.collabora,
type: 'OpenDocument',
file: 'closeurl-collabora.odt'
},
{
name: 'OnlyOffice',
viewer: application.onlyOffice,
type: 'Microsoft Word',
file: 'closeurl-onlyoffice.docx'
}
] as const
test.describe('WOPI CheckFileInfo: CloseUrl', { tag: '@predefined-users' }, () => {
test.beforeEach(async () => {
await api.usersHaveBeenCreated({ stepUser: 'Admin', users: ['Alice'] })
await ui.userLogsIn({ stepUser: 'Alice' })
await ui.userOpensApplication({ stepUser: 'Alice', name: 'files' })
})
for (const suite of suites) {
test(`closing ${suite.name} navigates back into the files app via CloseUrl`, async () => {
await ui.userCreatesResources({
stepUser: 'Alice',
resources: [{ name: suite.file, type: suite.type, content: 'close url content' }]
})
await ui.userOpensResourceInViewer({
stepUser: 'Alice',
resource: suite.file,
viewer: suite.viewer
})
const world = getWorld()
const { page } = world.actorsEnvironment.getActor({ key: 'Alice' })
// userClosesFileViewer's underlying editor.close() already waits for
// page.waitForURL(/.*\/files\/(spaces|shares|link|search)\/.*/) internally, so a broken
// CloseUrl would already cause this call to time out and fail the test
await ui.userClosesFileViewer({ stepUser: 'Alice' })
await expect(page).toHaveURL(/.*\/files\/(spaces|shares|link|search)\/.*/)
})
}
})
@@ -0,0 +1,83 @@
import { test } from '../../environment/test'
import * as api from '../../steps/api/api'
import * as ui from '../../steps/ui/index'
import { application, fileAction } from '../../environment/constants'
const suites = [
{
name: 'Collabora',
viewer: application.collabora,
type: 'OpenDocument',
file: 'readonly-collabora.odt'
},
{
name: 'OnlyOffice',
viewer: application.onlyOffice,
type: 'Microsoft Word',
file: 'readonly-onlyoffice.docx'
}
] as const
test.describe('WOPI CheckFileInfo: ReadOnly', { tag: '@predefined-users' }, () => {
test.beforeEach(async () => {
await api.usersHaveBeenCreated({ stepUser: 'Admin', users: ['Alice', 'Brian'] })
await ui.userLogsIn({ stepUser: 'Alice' })
await ui.userOpensApplication({ stepUser: 'Alice', name: 'files' })
})
for (const suite of suites) {
test(`ReadOnly is false for the file owner in ${suite.name}`, async () => {
await ui.userCreatesResources({
stepUser: 'Alice',
resources: [{ name: suite.file, type: suite.type, content: 'owner content' }]
})
await ui.userOpensResourceInViewer({
stepUser: 'Alice',
resource: suite.file,
viewer: suite.viewer
})
await ui.userEditsResources({
stepUser: 'Alice',
resources: [{ name: suite.file, type: suite.type, content: 'owner edited content' }]
})
await ui.userShouldSeeContentInEditor({
stepUser: 'Alice',
expectedContent: 'owner edited content',
editor: suite.name
})
await ui.userClosesFileViewer({ stepUser: 'Alice' })
})
test(`ReadOnly is true for a view-only share recipient in ${suite.name}`, async () => {
await ui.userCreatesResources({
stepUser: 'Alice',
resources: [{ name: suite.file, type: suite.type, content: 'owner content' }]
})
await ui.userSharesResources({
stepUser: 'Alice',
actionType: fileAction.sideBarPanel,
shares: [
{
resource: suite.file,
recipient: 'Brian',
type: 'user',
role: 'Can view',
resourceType: 'file'
}
]
})
await ui.userLogsIn({ stepUser: 'Brian' })
await ui.userNavigatesToSharedWithMePage({ stepUser: 'Brian' })
await ui.userOpensResourceInViewer({
stepUser: 'Brian',
resource: suite.file,
viewer: suite.viewer
})
await ui.userShouldNotBeAbleToEditContentOfResources({
stepUser: 'Brian',
resources: [{ name: suite.file, type: suite.type, content: 'owner content' }]
})
await ui.userClosesFileViewer({ stepUser: 'Brian' })
})
}
})
@@ -0,0 +1,63 @@
import { test } from '../../environment/test'
import * as api from '../../steps/api/api'
import * as ui from '../../steps/ui/index'
import { application } from '../../environment/constants'
const suites = [
{
name: 'Collabora',
viewer: application.collabora,
type: 'OpenDocument',
file: 'supportsupdate-collabora.odt'
},
{
name: 'OnlyOffice',
viewer: application.onlyOffice,
type: 'Microsoft Word',
file: 'supportsupdate-onlyoffice.docx'
}
] as const
test.describe('WOPI CheckFileInfo: SupportsUpdate', { tag: '@predefined-users' }, () => {
test.beforeEach(async () => {
await api.usersHaveBeenCreated({ stepUser: 'Admin', users: ['Alice'] })
await ui.userLogsIn({ stepUser: 'Alice' })
await ui.userOpensApplication({ stepUser: 'Alice', name: 'files' })
})
for (const suite of suites) {
test(`SupportsUpdate: a new ${suite.name} document created via the office suite persists its content`, async () => {
// creating a resource of this type/content via the office suite's "New" menu goes
// through the WOPI PutRelativeFile flow, the specific operation SupportsUpdate vouches for
await ui.userCreatesResources({
stepUser: 'Alice',
resources: [{ name: suite.file, type: suite.type, content: 'created via office suite' }]
})
await ui.userOpensResourceInViewer({
stepUser: 'Alice',
resource: suite.file,
viewer: suite.viewer
})
await ui.userShouldSeeContentInEditor({
stepUser: 'Alice',
expectedContent: 'created via office suite',
editor: suite.name
})
await ui.userClosesFileViewer({ stepUser: 'Alice' })
// reopen to confirm the PutRelativeFile write actually landed server-side, not just
// reflected in the editor's own in-memory state
await ui.userOpensResourceInViewer({
stepUser: 'Alice',
resource: suite.file,
viewer: suite.viewer
})
await ui.userShouldSeeContentInEditor({
stepUser: 'Alice',
expectedContent: 'created via office suite',
editor: suite.name
})
await ui.userClosesFileViewer({ stepUser: 'Alice' })
})
}
})
@@ -0,0 +1,85 @@
import { test } from '../../environment/test'
import * as api from '../../steps/api/api'
import * as ui from '../../steps/ui/index'
import { application, fileAction } from '../../environment/constants'
const suites = [
{
name: 'Collabora',
viewer: application.collabora,
type: 'OpenDocument',
file: 'version-collabora.odt'
},
{
name: 'OnlyOffice',
viewer: application.onlyOffice,
type: 'Microsoft Word',
file: 'version-onlyoffice.docx'
}
] as const
test.describe(
'WOPI CheckFileInfo: Version and LastModifiedTime',
{ tag: '@predefined-users' },
() => {
test.beforeEach(async () => {
await api.usersHaveBeenCreated({ stepUser: 'Admin', users: ['Alice', 'Brian'] })
await ui.userLogsIn({ stepUser: 'Alice' })
await ui.userOpensApplication({ stepUser: 'Alice', name: 'files' })
})
for (const suite of suites) {
test(`a fresh edit is visible to another session opening ${suite.name} afterward`, async () => {
await ui.userCreatesResources({
stepUser: 'Alice',
resources: [{ name: suite.file, type: suite.type, content: 'initial content' }]
})
await ui.userSharesResources({
stepUser: 'Alice',
actionType: fileAction.sideBarPanel,
shares: [
{
resource: suite.file,
recipient: 'Brian',
type: 'user',
role: 'Can edit',
resourceType: 'file'
}
]
})
await ui.userOpensResourceInViewer({
stepUser: 'Alice',
resource: suite.file,
viewer: suite.viewer
})
await ui.userEditsResources({
stepUser: 'Alice',
resources: [{ name: suite.file, type: suite.type, content: 'edited content v2' }]
})
await ui.userShouldSeeContentInEditor({
stepUser: 'Alice',
expectedContent: 'edited content v2',
editor: suite.name
})
await ui.userClosesFileViewer({ stepUser: 'Alice' })
await ui.userLogsIn({ stepUser: 'Brian' })
await ui.userNavigatesToSharedWithMePage({ stepUser: 'Brian' })
await ui.userOpensResourceInViewer({
stepUser: 'Brian',
resource: suite.file,
viewer: suite.viewer
})
// if LastModifiedTime/Version were wrong or stale, the WOPI client could serve Brian a
// cached pre-edit copy instead of fetching the actual current content
await ui.userShouldSeeContentInEditor({
stepUser: 'Brian',
expectedContent: 'edited content v2',
editor: suite.name
})
await ui.userClosesFileViewer({ stepUser: 'Brian' })
})
}
}
)