Skip to content

Sync-in · Sovereign platform for file storage, sharing, synchronization, and collaboration.

fix(backend:shares): use canonical external scope for nested shares

johaven7f2b8f6c0035
diff --git a/backend/src/applications/shares/services/shares-queries.service.spec.ts b/backend/src/applications/shares/services/shares-queries.service.spec.ts
new file mode 100644
index 00000000..a583bb50
--- /dev/null
+++ b/backend/src/applications/shares/services/shares-queries.service.spec.ts
@@ -0,0 +1,57 @@
+import 'reflect-metadata'
+import type { Cache } from '../../../infrastructure/cache/cache.service'
+import { SharesQueries } from './shares-queries.service'
+
+interface CacheMock {
+ genSlugKey: ReturnType<typeof vi.fn>
+ get: ReturnType<typeof vi.fn>
+ set: ReturnType<typeof vi.fn>
+}
+
+describe(SharesQueries.name, () => {
+ let cache: CacheMock
+ let service: SharesQueries
+ let execute: ReturnType<typeof vi.fn>
+
+ beforeEach(() => {
+ cache = {
+ genSlugKey: vi.fn(() => 'share-permissions'),
+ get: vi.fn().mockResolvedValue(undefined),
+ set: vi.fn().mockResolvedValue(undefined)
+ }
+ execute = vi.fn()
+ service = new SharesQueries({} as any, cache as unknown as Cache)
+ Reflect.set(service, 'sharePermissionsQuery', { execute })
+ })
+
+ afterEach(() => vi.restoreAllMocks())
+
+ it('uses the external root selected by the permissions query without another lookup', async () => {
+ execute.mockResolvedValue([
+ {
+ id: 30,
+ alias: 'grandchild',
+ permissions: 'd:r',
+ root: {
+ externalPath: '/mnt/archive',
+ externalParentShareId: 10
+ }
+ }
+ ])
+ const findHighestParentShare = vi.spyOn(service, 'findHighestParentShare')
+
+ const result = await service.permissions(7, 'grandchild')
+
+ expect(findHighestParentShare).not.toHaveBeenCalled()
+ expect(result.root.externalParentShareId).toBe(10)
+ expect(result.permissions).toBe('d:r')
+ })
+
+ it('returns no permissions when the query rejects an unresolved external hierarchy', async () => {
+ execute.mockResolvedValue([])
+ const findHighestParentShare = vi.spyOn(service, 'findHighestParentShare')
+
+ await expect(service.permissions(7, 'grandchild')).resolves.toBeUndefined()
+ expect(findHighestParentShare).not.toHaveBeenCalled()
+ })
+})
diff --git a/backend/src/applications/shares/services/shares-queries.service.ts b/backend/src/applications/shares/services/shares-queries.service.ts
index 0cc58bb0..09d068f4 100644
--- a/backend/src/applications/shares/services/shares-queries.service.ts
+++ b/backend/src/applications/shares/services/shares-queries.service.ts
@@ -652,6 +652,8 @@ export class SharesQueries {
const shareSpaceRoot: any = alias(spacesRoots, 'shareSpaceRoot')
const originOwner: any = alias(users, 'originOwner')
const childShare: any = alias(shares, 'childShare')
+ const externalParentShare: any = alias(shares, 'externalParentShare')
+ const externalRootScopeAlias = 'externalRootScope'
const selectUnion: FileProps | SelectedFields<any, any> = {
id: files.id,
path: sql`IF (${files.id} IS NOT NULL, ${filePathSQL(files)}, '')`.as('path'),
@@ -668,7 +670,6 @@ export class SharesQueries {
originSpaceExternalRootId: sql`${files.spaceExternalRootId}`.as('originSpaceExternalRootId'),
originSpaceRootExternalPath: sql`IF (${spacesRoots.externalPath} IS NULL,
${shareSpaceRoot.externalPath}, ${spacesRoots.externalPath})`.as('originSpaceRootExternalPath'),
- originShareExternalId: sql`IF (${shares.externalPath} IS NOT NULL, ${shares.parentId}, NULL)`.as('originShareExternalId'),
rootId: sql`${shares.id}`.as('rootId'),
rootAlias: shares.alias,
rootName: shares.name,
@@ -689,6 +690,51 @@ export class SharesQueries {
syncPathClientName: sql`JSON_VALUE(${syncClients.info}, '$.node')`.as('syncPathClientName')
}
const filters: SQL[] = [or(isNull(shares.ownerId), ne(shares.ownerId, sql.placeholder('userId')))]
+ const externalShareFilters = [...filters, isNotNull(shares.externalPath)]
+ const externalShareTargets = union(
+ this.fromUserQuery({ id: shares.id, parentId: shares.parentId, externalPath: shares.externalPath }, externalShareFilters),
+ this.fromGroupsQuery({ id: shares.id, parentId: shares.parentId, externalPath: shares.externalPath }, externalShareFilters),
+ this.fromAdminSharesQuery({ id: shares.id, parentId: shares.parentId, externalPath: shares.externalPath }, externalShareFilters)
+ )
+ // Make lock enrichment use the same storage namespace regardless of the
+ // descendant through which an external file is listed. File records and
+ // locks are indexed by the highest external ancestor, not by the immediate
+ // parent. `targetShares` applies the same user/group/admin filters as the
+ // main UNION, so recursion walks only the ancestors of visible shares.
+ // For A -> B -> C, the result maps A, B and C to the storage scope A.
+ // A missing or non-external parent stops the traversal, leaving the
+ // malformed external share without a scope so it can be filtered below.
+ const externalRootScope = sql`
+ (
+ WITH RECURSIVE targetShares (id, parentId, externalPath) AS
+ (${externalShareTargets}),
+ ancestors (targetId, id, parentId, externalPath) AS
+ (SELECT targetShares.id,
+ targetShares.id,
+ targetShares.parentId,
+ targetShares.externalPath
+ FROM targetShares
+ UNION
+ SELECT ancestors.targetId,
+ ${externalParentShare.id},
+ ${externalParentShare.parentId},
+ ${externalParentShare.externalPath}
+ FROM ${shares} AS externalParentShare
+ INNER JOIN ancestors ON ${externalParentShare.id} = ancestors.parentId
+ WHERE ${externalParentShare.externalPath} IS NOT NULL),
+ rootShare (targetId, externalRootShareId) AS
+ (SELECT ancestors.targetId,
+ ancestors.id
+ FROM ancestors
+ WHERE ancestors.parentId IS NULL
+ AND ancestors.externalPath IS NOT NULL)
+ SELECT rootShare.targetId,
+ rootShare.externalRootShareId
+ FROM rootShare
+ ) AS ${sql.identifier(externalRootScopeAlias)}
+ `
+ const externalRootScopeTargetId = sql<number>`${sql.identifier(externalRootScopeAlias)}.${sql.identifier('targetId')}`
+ const externalRootShareId = sql<number | null>`${sql.identifier(externalRootScopeAlias)}.${sql.identifier('externalRootShareId')}`
const fromUser = this.fromUserQuery(selectUnion, filters).$dynamic()
const fromGroups = this.fromGroupsQuery(selectUnion, filters).$dynamic()
const fromAdminShares = this.fromAdminSharesQuery({ ...selectUnion, rootPermissions: sql`${SHARE_ALL_OPERATIONS}` }, filters).$dynamic()
@@ -752,7 +798,7 @@ export class SharesQueries {
spaceAlias: unionAlias.originSpaceAlias,
spaceExternalRootId: unionAlias.originSpaceExternalRootId,
spaceRootExternalPath: unionAlias.originSpaceRootExternalPath,
- shareExternalId: unionAlias.originShareExternalId
+ shareExternalId: externalRootShareId
},
root: {
id: unionAlias.rootId,
@@ -782,7 +828,16 @@ export class SharesQueries {
})}, '[]')`.mapWith(dbParseJson),
hasComments: sql<boolean>`IF (${sql.placeholder('withHasComments')}, ${fileHasCommentsSubquerySQL(unionAlias.id)}, 0)`.mapWith(Boolean)
}
- this.shareRootFilesQuery = this.db.select(select).from(unionAlias).groupBy(unionAlias.rootId).prepare()
+ this.shareRootFilesQuery = this.db
+ .select(select)
+ .from(unionAlias)
+ .leftJoin(externalRootScope, eq(externalRootScopeTargetId, unionAlias.rootId))
+ // Non-external shares do not need this scope. An external share must
+ // resolve one: otherwise omit it so `updateRootFile()` cannot mistake
+ // the share-record owner for the owner of its external storage.
+ .where(or(isNull(unionAlias.rootExternalPath), isNotNull(externalRootShareId)))
+ .groupBy(unionAlias.rootId)
+ .prepare()
}
const fps: FileProps[] = await this.shareRootFilesQuery.execute({
userId: user.id,
@@ -801,6 +856,58 @@ export class SharesQueries {
async permissions(userId: number, shareAlias: string, isAdmin: number = 0): Promise<Partial<SpaceEnv>> {
if (!this.sharePermissionsQuery) {
const shareSpaceRoot: any = alias(spacesRoots, 'shareSpaceRoot')
+ const permissionParentShare: any = alias(shares, 'permissionParentShare')
+ const externalRootScopeAlias = 'externalRootScope'
+ // Make every file operation through a nested external share address the
+ // same file records and locks as an operation through its external root.
+ // This storage ancestry is independent from permission inheritance:
+ // `shares.parentId` remains the immediate permission parent, while this
+ // CTE exposes the highest ancestor used by `files.shareExternalId`.
+ // Only external child shares recurse; roots and non-external shares keep
+ // a null `externalParentShareId` and retain their existing fallback scope.
+ // A missing or non-external parent produces no root row, so the inner join
+ // denies access to a malformed external child before any file operation.
+ const externalRootScope = sql`
+ (
+ WITH RECURSIVE targetShare (id, parentId, externalPath) AS
+ (SELECT ${shares.id},
+ ${shares.parentId},
+ ${shares.externalPath}
+ FROM ${shares}
+ WHERE ${shares.alias} = ${sql.placeholder('shareAlias')}),
+ ancestors (targetId, id, parentId, externalPath) AS
+ (SELECT targetShare.id,
+ targetShare.id,
+ targetShare.parentId,
+ targetShare.externalPath
+ FROM targetShare
+ WHERE targetShare.externalPath IS NOT NULL
+ AND targetShare.parentId IS NOT NULL
+ UNION
+ SELECT ancestors.targetId,
+ ${permissionParentShare.id},
+ ${permissionParentShare.parentId},
+ ${permissionParentShare.externalPath}
+ FROM ${shares} AS permissionParentShare
+ INNER JOIN ancestors ON ${permissionParentShare.id} = ancestors.parentId
+ WHERE ${permissionParentShare.externalPath} IS NOT NULL),
+ rootShare (targetId, externalRootShareId) AS
+ (SELECT ancestors.targetId,
+ ancestors.id
+ FROM ancestors
+ WHERE ancestors.parentId IS NULL
+ AND ancestors.externalPath IS NOT NULL)
+ SELECT targetShare.id AS targetId,
+ rootShare.externalRootShareId
+ FROM targetShare
+ LEFT JOIN rootShare ON rootShare.targetId = targetShare.id
+ WHERE targetShare.externalPath IS NULL
+ OR targetShare.parentId IS NULL
+ OR rootShare.externalRootShareId IS NOT NULL
+ ) AS ${sql.identifier(externalRootScopeAlias)}
+ `
+ const externalRootScopeTargetId = sql<number>`${sql.identifier(externalRootScopeAlias)}.${sql.identifier('targetId')}`
+ const externalRootShareId = sql<number | null>`${sql.identifier(externalRootScopeAlias)}.${sql.identifier('externalRootShareId')}`
const selectUnion: SpaceEnv | SelectedFields<any, any> = {
id: shares.id,
alias: shares.alias,
@@ -815,7 +922,6 @@ export class SharesQueries {
rootPath: sql`IF (${files.id} IS NOT NULL, ${filePathSQL(files)}, NULL)`.as('rootPath'),
rootInTrash: files.inTrash,
rootExternalPath: shares.externalPath,
- rootExternalParentShareId: sql`IF (${shares.externalPath} IS NOT NULL, ${shares.parentId}, NULL)`.as('rootExternalParentShareId'),
rootSpaceRootId: sql`IF (${spacesRoots.id} IS NULL, ${shareSpaceRoot.id}, ${spacesRoots.id})`.as('rootSpaceRootId'),
rootSpaceRootExternalPath: sql`IF (${spacesRoots.externalPath} IS NULL,
${shareSpaceRoot.externalPath}, ${spacesRoots.externalPath})`.as('rootSpaceRootExternalPath')
@@ -864,10 +970,16 @@ export class SharesQueries {
root: { id: unionAlias.rootSpaceRootId, externalPath: unionAlias.rootSpaceRootExternalPath }
},
externalPath: unionAlias.rootExternalPath,
- externalParentShareId: unionAlias.rootExternalParentShareId
+ externalParentShareId: externalRootShareId
}
}
- this.sharePermissionsQuery = this.db.select(select).from(unionAlias).groupBy(unionAlias.id).limit(1).prepare()
+ this.sharePermissionsQuery = this.db
+ .select(select)
+ .from(unionAlias)
+ .innerJoin(externalRootScope, eq(externalRootScopeTargetId, unionAlias.id))
+ .groupBy(unionAlias.id)
+ .limit(1)
+ .prepare()
}
// `userId` is used in `fromUserQuery` and `fromGroupsQuery` function
// `isAdmin` is used in `fromAdminSharesQuery` function
diff --git a/backend/src/applications/shares/shares.e2e-spec.ts b/backend/src/applications/shares/shares.e2e-spec.ts
new file mode 100644
index 00000000..4341da08
--- /dev/null
+++ b/backend/src/applications/shares/shares.e2e-spec.ts
@@ -0,0 +1,168 @@
+import { Test, TestingModule } from '@nestjs/testing'
+import { inArray } from 'drizzle-orm'
+import { randomUUID } from 'node:crypto'
+import type { Cache } from '../../infrastructure/cache/cache.service'
+import { DB_TOKEN_PROVIDER } from '../../infrastructure/database/constants'
+import { DatabaseModule } from '../../infrastructure/database/database.module'
+import type { DBSchema } from '../../infrastructure/database/interfaces/database.interface'
+import { dbGetInsertedId } from '../../infrastructure/database/utils'
+import type { UserModel } from '../users/models/user.model'
+import { users } from '../users/schemas/users.schema'
+import { SharesQueries } from './services/shares-queries.service'
+import { sharesMembers } from './schemas/shares-members.schema'
+import { shares } from './schemas/shares.schema'
+
+describe('Shares (e2e)', () => {
+ let module: TestingModule
+ let db: DBSchema
+ let sharesQueries: SharesQueries
+ let actorId: number | undefined
+ let ownerId: number | undefined
+ let externalRootId: number | undefined
+ let childId: number | undefined
+ let grandchildId: number | undefined
+ let internalRootId: number | undefined
+
+ const suffix = randomUUID().replaceAll('-', '').slice(0, 12)
+ const aliases = {
+ root: `e2e-ext-root-${suffix}`,
+ child: `e2e-ext-child-${suffix}`,
+ grandchild: `e2e-ext-grandchild-${suffix}`,
+ unauthorizedChild: `e2e-ext-unauthorized-${suffix}`,
+ internalRoot: `e2e-internal-root-${suffix}`,
+ malformedChild: `e2e-ext-malformed-${suffix}`
+ }
+ const externalPath = `/e2e/external/${suffix}`
+ const noCache = {
+ genSlugKey: vi.fn((...args: unknown[]) => args.join(':')),
+ get: vi.fn().mockResolvedValue(undefined),
+ set: vi.fn().mockResolvedValue(true)
+ } as unknown as Cache
+
+ beforeAll(async () => {
+ module = await Test.createTestingModule({ imports: [DatabaseModule] }).compile()
+ module.useLogger(['fatal'])
+ db = await module.resolve<DBSchema>(DB_TOKEN_PROVIDER)
+ sharesQueries = new SharesQueries(db, noCache)
+
+ actorId = dbGetInsertedId(
+ await db.insert(users).values({
+ login: `e2e-share-actor-${suffix}`,
+ email: `e2e-share-actor-${suffix}@example.test`,
+ password: 'password'
+ })
+ )
+ ownerId = dbGetInsertedId(
+ await db.insert(users).values({
+ login: `e2e-share-owner-${suffix}`,
+ email: `e2e-share-owner-${suffix}@example.test`,
+ password: 'password'
+ })
+ )
+
+ externalRootId = dbGetInsertedId(await db.insert(shares).values({ alias: aliases.root, name: 'External root', ownerId: null, externalPath }))
+ childId = dbGetInsertedId(
+ await db.insert(shares).values({
+ alias: aliases.child,
+ name: 'External child',
+ ownerId,
+ parentId: externalRootId,
+ externalPath
+ })
+ )
+ grandchildId = dbGetInsertedId(
+ await db.insert(shares).values({
+ alias: aliases.grandchild,
+ name: 'External grandchild',
+ ownerId,
+ parentId: childId,
+ externalPath
+ })
+ )
+ await db.insert(shares).values({
+ alias: aliases.unauthorizedChild,
+ name: 'External child without membership',
+ ownerId,
+ parentId: externalRootId,
+ externalPath
+ })
+
+ internalRootId = dbGetInsertedId(
+ await db.insert(shares).values({ alias: aliases.internalRoot, name: 'Internal root', ownerId, externalPath: null })
+ )
+ const malformedChildId = dbGetInsertedId(
+ await db.insert(shares).values({
+ alias: aliases.malformedChild,
+ name: 'Malformed external child',
+ ownerId,
+ parentId: internalRootId,
+ externalPath
+ })
+ )
+
+ await db.insert(sharesMembers).values([
+ { shareId: externalRootId, userId: actorId, permissions: 'a:d:m:so' },
+ { shareId: childId, userId: actorId, permissions: 'd:m' },
+ { shareId: grandchildId, userId: actorId, permissions: 'm' },
+ { shareId: malformedChildId, userId: actorId, permissions: 'd:m' }
+ ])
+ })
+
+ afterAll(async () => {
+ try {
+ const rootIds = [externalRootId, internalRootId].filter((id): id is number => Number.isInteger(id))
+ if (rootIds.length) {
+ await db.delete(shares).where(inArray(shares.id, rootIds))
+ }
+ const userIds = [actorId, ownerId].filter((id): id is number => Number.isInteger(id))
+ if (userIds.length) {
+ await db.delete(users).where(inArray(users.id, userIds))
+ }
+ } finally {
+ await module?.close()
+ }
+ })
+
+ it('keeps descendant permissions while resolving the external root storage scope', async () => {
+ const root = await sharesQueries.permissions(actorId, aliases.root)
+ const child = await sharesQueries.permissions(actorId, aliases.child)
+ const grandchild = await sharesQueries.permissions(actorId, aliases.grandchild)
+
+ expect(root).toMatchObject({
+ id: externalRootId,
+ permissions: 'a:d:m:so',
+ root: { externalPath, externalParentShareId: null }
+ })
+ expect(child).toMatchObject({
+ id: childId,
+ permissions: 'd:m',
+ root: { externalPath, externalParentShareId: externalRootId }
+ })
+ expect(grandchild).toMatchObject({
+ id: grandchildId,
+ permissions: 'm',
+ root: { externalPath, externalParentShareId: externalRootId }
+ })
+ expect(grandchild.root.externalParentShareId).not.toBe(childId)
+ })
+
+ it('uses the same external root scope without replacing each listed share permissions', async () => {
+ const roots = await sharesQueries.shareRootFiles({ id: actorId, isAdmin: false } as UserModel, {})
+ const child = roots.find((root) => root.root.alias === aliases.child)
+ const grandchild = roots.find((root) => root.root.alias === aliases.grandchild)
+
+ expect(child).toMatchObject({ origin: { shareExternalId: externalRootId }, root: { permissions: 'd:m' } })
+ expect(grandchild).toMatchObject({ origin: { shareExternalId: externalRootId }, root: { permissions: 'm' } })
+ })
+
+ it('does not inherit access from an external parent without a child membership', async () => {
+ await expect(sharesQueries.permissions(actorId, aliases.unauthorizedChild)).resolves.toBeUndefined()
+ })
+
+ it('fails closed when an external child has a non-external parent', async () => {
+ await expect(sharesQueries.permissions(actorId, aliases.malformedChild)).resolves.toBeUndefined()
+
+ const roots = await sharesQueries.shareRootFiles({ id: actorId, isAdmin: false } as UserModel, {})
+ expect(roots.some((root) => root.root.alias === aliases.malformedChild)).toBe(false)
+ })
+})
diff --git a/backend/src/applications/shares/shares.md b/backend/src/applications/shares/shares.md
index e01c9bbc..09257c56 100644
--- a/backend/src/applications/shares/shares.md
+++ b/backend/src/applications/shares/shares.md
@@ -1,56 +1,83 @@
# Shares
-The `shares` module exposes existing storage through share aliases. A share does
-not copy its source and does not become the owner of the underlying storage.
+The `shares` module exposes existing storage through share aliases. A share does not copy its source and does not become the owner of the underlying
+storage.
## Storage provenance
-The share keeps enough provenance to resolve the physical source and its
-managed storage owner:
+The share keeps enough provenance to resolve the physical source and its managed storage owner:
-| Share source | Storage provenance |
-| --- | --- |
-| Personal files | The source file's `ownerId` |
-| Native space | The source `spaceId` |
-| External root attached to a native space | The source `spaceId` and `spaceRootId` |
-| External share | The root share's `externalPath` and `files.shareExternalId` |
-| Child of an external share | The highest external parent and a path below its `externalPath` |
+| Share source | Storage provenance |
+|------------------------------------------|-----------------------------------------------------------------|
+| Personal files | The source file's `ownerId` |
+| Native space | The source `spaceId` |
+| External root attached to a native space | The source `spaceId` and `spaceRootId` |
+| External share | The root share's `externalPath` and `files.shareExternalId` |
+| Child of an external share | The highest external parent and a path below its `externalPath` |
-For a native-space external root, the native space remains the managed storage
-owner even though the files are physically outside its home.
+For a native-space external root, the native space remains the managed storage owner even though the files are physically outside its home.
A root external share has no managed user or native-space storage owner. Its
-`ownerId` is therefore `null`. A child share can have an `ownerId` identifying
-the owner of the share record, but that value is not storage ownership and must
-not be used to select a user trash repository.
+`ownerId` is therefore `null`. A child share can have an `ownerId` identifying the owner of the share record, but that value is not storage ownership
+and must not be used to select a user trash repository.
-Files indexed below an external share use `files.shareExternalId`. For a child
-share, this identifier refers to the highest external parent so that every
-descendant resolves against the same physical external root.
+Files indexed below an external share use `files.shareExternalId`. For a child share, this identifier refers to the highest external parent so that
+every descendant resolves against the same physical external root.
+
+### Nested-share hierarchy and external storage scope
+
+Nested external shares have two independent ancestry concepts:
+
+- `shares.parentId` always identifies the immediate parent. It defines the share hierarchy and drives permission delegation and propagation.
+- `files.shareExternalId` identifies the highest external ancestor. For descendants, `SpaceEnv.root.externalParentShareId` carries that canonical
+ storage scope to file operations.
+
+For a hierarchy `A -> B -> C`, where `A` is the root external share:
+
+| Share | Immediate `parentId` | Canonical `files.shareExternalId` |
+|-------|----------------------|-----------------------------------|
+| `A` | `null` | `A` |
+| `B` | `A` | `A` |
+| `C` | `B` | `A` |
+
+Resolving the external storage scope must never rewrite `shares.parentId`. File metadata, lock conflict checks and cleanup, and event and quota
+repository routing must all use the same canonical `files.shareExternalId`. A correct physical path is not sufficient to identify this logical scope.
+
+If the highest external ancestor cannot be resolved, the operation must fail before modifying the filesystem. It must not fall back to the immediate
+parent, the current descendant, or the authenticated actor.
+
+## Child-share permission delegation
+
+Creating a child share requires the effective `SHARE_OUTSIDE` permission on its immediate parent. Requested member and link permissions are
+intersected with the creator's effective permissions on that parent, so a child cannot delegate rights that its creator does not hold.
+
+Member and link permissions are stored on each share. Permission removals on a parent are propagated through the descendant branches created from that
+delegation. New permissions on a parent do not automatically expand existing descendant grants. Removing a member from a parent can also remove child
+shares owned through that delegation unless another effective membership still grants the required share permission.
## Deleting a share and deleting shared content
-Deleting a share definition removes the share, its memberships, and its child
-share definitions. It does not delete the source content from the filesystem.
+Deleting a share definition removes the share, its memberships, and its child share definitions. It does not delete the source content from the
+filesystem.
-Deleting a file or directory while browsing `shares/<share-alias>/...` is a
-separate file operation. It follows the storage provenance of the shared
+Deleting a file or directory while browsing `shares/<share-alias>/...` is a separate file operation. It follows the storage provenance of the shared
content rather than the authenticated actor or the owner of the share record.
+The `shares/<share-alias>` endpoint itself is virtual and cannot be deleted by a file operation; only its descendants can be deletion targets.
+Selecting permanent deletion does not bypass the effective `DELETE` permission or lock conflict checks.
+
## Shared-content deletion policy
-| Shared content | Deletion target |
-| --- | --- |
-| Personal files | The source owner's managed user trash |
-| Native-space files | The source space's managed trash |
-| External root attached to a native space | The source space's managed trash |
-| External share | Permanent deletion |
-| Child or other descendant of an external share | Permanent deletion |
+| Shared content | Deletion target |
+|------------------------------------------------|---------------------------------------|
+| Personal files | The source owner's managed user trash |
+| Native-space files | The source space's managed trash |
+| External root attached to a native space | The source space's managed trash |
+| External share | Permanent deletion |
+| Child or other descendant of an external share | Permanent deletion |
-The permanent-deletion rule is selected when the resolved space is in the
-shares repository and its root has an `externalPath`, unless its provenance
-points to a native space. It applies regardless of whether the actor is a
-regular user, guest, or link pseudo-user.
+The permanent-deletion rule is selected when the resolved space is in the shares repository and its root has an `externalPath`, unless its provenance
+points to a native space. It applies regardless of whether the actor is a regular user, guest, or link pseudo-user.
For an external share, deleting shared content:
@@ -60,20 +87,15 @@ For an external share, deleting shared content:
4. emits a `DELETE_PERMANENTLY` event.
The operation never uses the actor's home, a share-record owner's home, or an
-`<external-root>/.trash/` directory. There is no fallback destination and no
-migration from an existing `.trash` directory.
+`<external-root>/.trash/` directory. There is no fallback destination and no migration from an existing `.trash` directory.
-Because no managed trash entry is created, deleted external-share content
-cannot be listed, restored, or removed later by the trash retention scheduler.
-If the external location cannot be modified, the deletion fails instead of
-redirecting the resource to another storage owner.
+Because no managed trash entry is created, deleted external-share content cannot be listed, restored, or removed later by the trash retention
+scheduler. If the external location cannot be modified, the deletion fails instead of redirecting the resource to another storage owner.
## Future external trash support
-The permanent-deletion rule is the current policy until external trash is
-implemented as a first-class repository. Such a repository must be explicitly
-addressable by the file browser and must define empty, restore, and retention
-lifecycles before external-share deletion can target it.
+The permanent-deletion rule is the current policy until external trash is implemented as a first-class repository. Such a repository must be
+explicitly addressable by the file browser and must define empty, restore, and retention lifecycles before external-share deletion can target it.
The managed trash layout and lifecycle are specified in
[`spaces.md`](../spaces/spaces.md).
diff --git a/backend/src/applications/spaces/models/space-env.model.ts b/backend/src/applications/spaces/models/space-env.model.ts
index 88a81cbc..5045a77a 100644
--- a/backend/src/applications/spaces/models/space-env.model.ts
+++ b/backend/src/applications/spaces/models/space-env.model.ts
@@ -31,7 +31,7 @@ export class SpaceEnv implements Pick<Space, 'id' | 'alias' | 'name' | 'enabled'
owner?: { id: number; login: string }
// root.externalPath or share.externalPath
externalPath?: string
- // in share case, if defined, it's an external child share with a parent
+ // in share case, if defined, it's an external child share and this is its highest parent share id
externalParentShareId?: number
file?: {
// space and root are only used when the space is a share
diff --git a/backend/src/applications/spaces/utils/paths.ts b/backend/src/applications/spaces/utils/paths.ts
index 706c9340..9becb7f3 100644
--- a/backend/src/applications/spaces/utils/paths.ts
+++ b/backend/src/applications/spaces/utils/paths.ts
@@ -206,7 +206,7 @@ export function dbFileFromSpace(userId: number, space: SpaceEnv): FileDBProps {
dbFile.spaceExternalRootId = space.inSharesRepository ? null : space.root.id
if (space.inSharesRepository) {
// in this case space.id is the share.id
- // if the `externalParentShareId` property is defined, it's an external child share that must use the parent id
+ // if the `externalParentShareId` property is defined, the external child share must use its highest parent share id
dbFile.shareExternalId = space.root?.externalParentShareId ? space.root.externalParentShareId : space.id
} else {
dbFile.shareExternalId = null