Skip to content

Fully autonomous AI Agents system capable of performing complex penetration testing tasks

feat(resources): add multi-source move, copy and flow-file promotion

Dmitry Ng6890584c64e4
diff --git a/backend/pkg/server/docs/docs.go b/backend/pkg/server/docs/docs.go
index 8840f7b2..f015226d 100644
--- a/backend/pkg/server/docs/docs.go
+++ b/backend/pkg/server/docs/docs.go
@@ -2455,7 +2455,7 @@ const docTemplate = `{
"tags": [
"FlowFiles"
],
- "summary": "Promote a flow file or directory to user resources",
+ "summary": "Promote flow file(s) or directory/directories to user resources",
"parameters": [
{
"minimum": 0,
@@ -2466,7 +2466,7 @@ const docTemplate = `{
"required": true
},
{
- "description": "source path, destination and force flag",
+ "description": "source(s), destination and force flag",
"name": "body",
"in": "body",
"required": true,
@@ -5417,7 +5417,7 @@ const docTemplate = `{
"tags": [
"Resources"
],
- "summary": "Copy a resource (file or directory)",
+ "summary": "Copy resource(s) (files or directories)",
"parameters": [
{
"description": "copy request",
@@ -5633,7 +5633,7 @@ const docTemplate = `{
"tags": [
"Resources"
],
- "summary": "Move or rename a resource (file or directory)",
+ "summary": "Move or rename resource(s) (files or directories)",
"parameters": [
{
"description": "move request",
@@ -5820,7 +5820,7 @@ const docTemplate = `{
{
"type": "integer",
"description": "role id",
- "name": "id",
+ "name": "roleID",
"in": "path",
"required": true
}
@@ -7415,21 +7415,27 @@ const docTemplate = `{
"models.AddResourceFromFlowRequest": {
"type": "object",
"required": [
- "destination",
- "source"
+ "destination"
],
"properties": {
"destination": {
- "description": "Destination is the virtual path the resource will have in the user's resource tree.",
+ "description": "Destination is the virtual path prefix in the user's resource tree.",
"type": "string"
},
"force": {
- "description": "Force overwrites an existing resource at Destination if one already exists.",
+ "description": "Force overwrites existing resources at the target paths when true.",
"type": "boolean"
},
"source": {
- "description": "Source is a relative path within the flow cache, e.g. \"container/work/result.md\" or \"uploads/task.md\" or \"uploads/work/\".",
+ "description": "Source is a single relative path within the flow cache (kept for backward\ncompatibility). Combined with Sources when both are provided.",
"type": "string"
+ },
+ "sources": {
+ "description": "Sources is a list of relative paths within the flow cache. Combined with\nSource when both are provided; duplicate entries are silently removed.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
}
}
},
@@ -7810,18 +7816,27 @@ const docTemplate = `{
"models.CopyResourceRequest": {
"type": "object",
"required": [
- "destination",
- "source"
+ "destination"
],
"properties": {
"destination": {
+ "description": "Destination is the exact target path (single source) or base directory\n(multiple sources). Required.",
"type": "string"
},
"force": {
+ "description": "Force overwrites existing resources at the target paths when true.",
"type": "boolean"
},
"source": {
+ "description": "Source is kept for backward compatibility (single source).\nCombined with Sources when both are provided; duplicates are removed.",
"type": "string"
+ },
+ "sources": {
+ "description": "Sources is a list of virtual resource paths to copy.\nCombined with Source when both are provided; duplicates are removed.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
}
}
},
@@ -8476,18 +8491,27 @@ const docTemplate = `{
"models.MoveResourceRequest": {
"type": "object",
"required": [
- "destination",
- "source"
+ "destination"
],
"properties": {
"destination": {
+ "description": "Destination is the exact target path (single source) or base directory\n(multiple sources). Required.",
"type": "string"
},
"force": {
+ "description": "Force overwrites existing resources at the target paths when true.",
"type": "boolean"
},
"source": {
+ "description": "Source is kept for backward compatibility (single source).\nCombined with Sources when both are provided; duplicates are removed.",
"type": "string"
+ },
+ "sources": {
+ "description": "Sources is a list of virtual resource paths to move.\nCombined with Source when both are provided; duplicates are removed.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
}
}
},
diff --git a/backend/pkg/server/docs/swagger.json b/backend/pkg/server/docs/swagger.json
index 2b5dc920..4d1f3c53 100644
--- a/backend/pkg/server/docs/swagger.json
+++ b/backend/pkg/server/docs/swagger.json
@@ -2447,7 +2447,7 @@
"tags": [
"FlowFiles"
],
- "summary": "Promote a flow file or directory to user resources",
+ "summary": "Promote flow file(s) or directory/directories to user resources",
"parameters": [
{
"minimum": 0,
@@ -2458,7 +2458,7 @@
"required": true
},
{
- "description": "source path, destination and force flag",
+ "description": "source(s), destination and force flag",
"name": "body",
"in": "body",
"required": true,
@@ -5409,7 +5409,7 @@
"tags": [
"Resources"
],
- "summary": "Copy a resource (file or directory)",
+ "summary": "Copy resource(s) (files or directories)",
"parameters": [
{
"description": "copy request",
@@ -5625,7 +5625,7 @@
"tags": [
"Resources"
],
- "summary": "Move or rename a resource (file or directory)",
+ "summary": "Move or rename resource(s) (files or directories)",
"parameters": [
{
"description": "move request",
@@ -5812,7 +5812,7 @@
{
"type": "integer",
"description": "role id",
- "name": "id",
+ "name": "roleID",
"in": "path",
"required": true
}
@@ -7407,21 +7407,27 @@
"models.AddResourceFromFlowRequest": {
"type": "object",
"required": [
- "destination",
- "source"
+ "destination"
],
"properties": {
"destination": {
- "description": "Destination is the virtual path the resource will have in the user's resource tree.",
+ "description": "Destination is the virtual path prefix in the user's resource tree.",
"type": "string"
},
"force": {
- "description": "Force overwrites an existing resource at Destination if one already exists.",
+ "description": "Force overwrites existing resources at the target paths when true.",
"type": "boolean"
},
"source": {
- "description": "Source is a relative path within the flow cache, e.g. \"container/work/result.md\" or \"uploads/task.md\" or \"uploads/work/\".",
+ "description": "Source is a single relative path within the flow cache (kept for backward\ncompatibility). Combined with Sources when both are provided.",
"type": "string"
+ },
+ "sources": {
+ "description": "Sources is a list of relative paths within the flow cache. Combined with\nSource when both are provided; duplicate entries are silently removed.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
}
}
},
@@ -7802,18 +7808,27 @@
"models.CopyResourceRequest": {
"type": "object",
"required": [
- "destination",
- "source"
+ "destination"
],
"properties": {
"destination": {
+ "description": "Destination is the exact target path (single source) or base directory\n(multiple sources). Required.",
"type": "string"
},
"force": {
+ "description": "Force overwrites existing resources at the target paths when true.",
"type": "boolean"
},
"source": {
+ "description": "Source is kept for backward compatibility (single source).\nCombined with Sources when both are provided; duplicates are removed.",
"type": "string"
+ },
+ "sources": {
+ "description": "Sources is a list of virtual resource paths to copy.\nCombined with Source when both are provided; duplicates are removed.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
}
}
},
@@ -8468,18 +8483,27 @@
"models.MoveResourceRequest": {
"type": "object",
"required": [
- "destination",
- "source"
+ "destination"
],
"properties": {
"destination": {
+ "description": "Destination is the exact target path (single source) or base directory\n(multiple sources). Required.",
"type": "string"
},
"force": {
+ "description": "Force overwrites existing resources at the target paths when true.",
"type": "boolean"
},
"source": {
+ "description": "Source is kept for backward compatibility (single source).\nCombined with Sources when both are provided; duplicates are removed.",
"type": "string"
+ },
+ "sources": {
+ "description": "Sources is a list of virtual resource paths to move.\nCombined with Source when both are provided; duplicates are removed.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
}
}
},
diff --git a/backend/pkg/server/docs/swagger.yaml b/backend/pkg/server/docs/swagger.yaml
index 7e2cf2b6..25044d39 100644
--- a/backend/pkg/server/docs/swagger.yaml
+++ b/backend/pkg/server/docs/swagger.yaml
@@ -163,20 +163,27 @@ definitions:
models.AddResourceFromFlowRequest:
properties:
destination:
- description: Destination is the virtual path the resource will have in the
- user's resource tree.
+ description: Destination is the virtual path prefix in the user's resource
+ tree.
type: string
force:
- description: Force overwrites an existing resource at Destination if one already
- exists.
+ description: Force overwrites existing resources at the target paths when
+ true.
type: boolean
source:
- description: Source is a relative path within the flow cache, e.g. "container/work/result.md"
- or "uploads/task.md" or "uploads/work/".
+ description: |-
+ Source is a single relative path within the flow cache (kept for backward
+ compatibility). Combined with Sources when both are provided.
type: string
+ sources:
+ description: |-
+ Sources is a list of relative paths within the flow cache. Combined with
+ Source when both are provided; duplicate entries are silently removed.
+ items:
+ type: string
+ type: array
required:
- destination
- - source
type: object
models.AddResourcesRequest:
properties:
@@ -449,14 +456,28 @@ definitions:
models.CopyResourceRequest:
properties:
destination:
+ description: |-
+ Destination is the exact target path (single source) or base directory
+ (multiple sources). Required.
type: string
force:
+ description: Force overwrites existing resources at the target paths when
+ true.
type: boolean
source:
+ description: |-
+ Source is kept for backward compatibility (single source).
+ Combined with Sources when both are provided; duplicates are removed.
type: string
+ sources:
+ description: |-
+ Sources is a list of virtual resource paths to copy.
+ Combined with Source when both are provided; duplicates are removed.
+ items:
+ type: string
+ type: array
required:
- destination
- - source
type: object
models.CreateAPITokenRequest:
properties:
@@ -912,14 +933,28 @@ definitions:
models.MoveResourceRequest:
properties:
destination:
+ description: |-
+ Destination is the exact target path (single source) or base directory
+ (multiple sources). Required.
type: string
force:
+ description: Force overwrites existing resources at the target paths when
+ true.
type: boolean
source:
+ description: |-
+ Source is kept for backward compatibility (single source).
+ Combined with Sources when both are provided; duplicates are removed.
type: string
+ sources:
+ description: |-
+ Sources is a list of virtual resource paths to move.
+ Combined with Source when both are provided; duplicates are removed.
+ items:
+ type: string
+ type: array
required:
- destination
- - source
type: object
models.Msglog:
properties:
@@ -3495,7 +3530,7 @@ paths:
name: flowID
required: true
type: integer
- - description: source path, destination and force flag
+ - description: source(s), destination and force flag
in: body
name: body
required: true
@@ -3535,7 +3570,7 @@ paths:
$ref: '#/definitions/ErrorResponse'
security:
- BearerAuth: []
- summary: Promote a flow file or directory to user resources
+ summary: Promote flow file(s) or directory/directories to user resources
tags:
- FlowFiles
/flows/{flowID}/graph:
@@ -5491,7 +5526,7 @@ paths:
$ref: '#/definitions/ErrorResponse'
security:
- BearerAuth: []
- summary: Copy a resource (file or directory)
+ summary: Copy resource(s) (files or directories)
tags:
- Resources
/resources/download:
@@ -5623,7 +5658,7 @@ paths:
$ref: '#/definitions/ErrorResponse'
security:
- BearerAuth: []
- summary: Move or rename a resource (file or directory)
+ summary: Move or rename resource(s) (files or directories)
tags:
- Resources
/roles/:
@@ -5713,7 +5748,7 @@ paths:
parameters:
- description: role id
in: path
- name: id
+ name: roleID
required: true
type: integer
produces:
diff --git a/backend/pkg/server/models/flow_files.go b/backend/pkg/server/models/flow_files.go
index fb63baca..8e1dacbb 100644
--- a/backend/pkg/server/models/flow_files.go
+++ b/backend/pkg/server/models/flow_files.go
@@ -54,12 +54,26 @@ type AddResourcesRequest struct {
Force bool `json:"force"`
}
-// AddResourceFromFlowRequest is the request body for promoting a flow file to user resources.
+// AddResourceFromFlowRequest is the request body for promoting one or more flow
+// files / directories into the user's global resource store.
+//
+// At least one of Source or Sources must be non-empty after deduplication.
+//
+// - Single source (Source XOR one entry in Sources):
+// Destination is the exact target path (file) or root directory (dir tree).
+// - Multiple sources:
+// Destination is treated as a base directory; each source's base name is
+// appended automatically, e.g. sources ["uploads/a.txt", "container/b.txt"]
+// with destination "results" → "results/a.txt" and "results/b.txt".
type AddResourceFromFlowRequest struct {
- // Source is a relative path within the flow cache, e.g. "container/work/result.md" or "uploads/task.md" or "uploads/work/".
- Source string `json:"source" binding:"required"`
- // Destination is the virtual path the resource will have in the user's resource tree.
+ // Source is a single relative path within the flow cache (kept for backward
+ // compatibility). Combined with Sources when both are provided.
+ Source string `json:"source"`
+ // Sources is a list of relative paths within the flow cache. Combined with
+ // Source when both are provided; duplicate entries are silently removed.
+ Sources []string `json:"sources"`
+ // Destination is the virtual path prefix in the user's resource tree.
Destination string `json:"destination" binding:"required"`
- // Force overwrites an existing resource at Destination if one already exists.
+ // Force overwrites existing resources at the target paths when true.
Force bool `json:"force"`
}
diff --git a/backend/pkg/server/models/resources.go b/backend/pkg/server/models/resources.go
index dcf4af77..f8fb3431 100644
--- a/backend/pkg/server/models/resources.go
+++ b/backend/pkg/server/models/resources.go
@@ -43,15 +43,49 @@ type MkdirResourceRequest struct {
}
// MoveResourceRequest is the request body for moving or renaming a resource.
+//
+// At least one of Source or Sources must be non-empty after deduplication.
+//
+// - Single source: Destination is the exact target path (file) or root
+// directory (dir tree), identical to the original single-source behaviour.
+// - Multiple sources: Destination is treated as a base directory; each
+// source's base name is appended automatically, e.g. moving "a.txt" and
+// "b.txt" to "archive" produces "archive/a.txt" and "archive/b.txt".
+// All moves happen atomically inside a single DB transaction.
type MoveResourceRequest struct {
- Source string `json:"source" binding:"required"`
+ // Source is kept for backward compatibility (single source).
+ // Combined with Sources when both are provided; duplicates are removed.
+ Source string `json:"source"`
+ // Sources is a list of virtual resource paths to move.
+ // Combined with Source when both are provided; duplicates are removed.
+ Sources []string `json:"sources"`
+ // Destination is the exact target path (single source) or base directory
+ // (multiple sources). Required.
Destination string `json:"destination" binding:"required"`
- Force bool `json:"force"`
+ // Force overwrites existing resources at the target paths when true.
+ Force bool `json:"force"`
}
// CopyResourceRequest is the request body for copying a resource.
+//
+// At least one of Source or Sources must be non-empty after deduplication.
+//
+// - Single source: Destination is the exact target path (file) or root
+// directory (dir tree), identical to the original single-source behaviour.
+// - Multiple sources: Destination is treated as a base directory; each
+// source's base name is appended automatically, e.g. copying "a.txt" and
+// "b.txt" to "backup" produces "backup/a.txt" and "backup/b.txt".
+// All copies happen atomically inside a single DB transaction.
type CopyResourceRequest struct {
- Source string `json:"source" binding:"required"`
+ // Source is kept for backward compatibility (single source).
+ // Combined with Sources when both are provided; duplicates are removed.
+ Source string `json:"source"`
+ // Sources is a list of virtual resource paths to copy.
+ // Combined with Source when both are provided; duplicates are removed.
+ Sources []string `json:"sources"`
+ // Destination is the exact target path (single source) or base directory
+ // (multiple sources). Required.
Destination string `json:"destination" binding:"required"`
- Force bool `json:"force"`
+ // Force overwrites existing resources at the target paths when true.
+ Force bool `json:"force"`
}
diff --git a/backend/pkg/server/services/flow_files.go b/backend/pkg/server/services/flow_files.go
index 3efe8f33..10cb5d5a 100644
--- a/backend/pkg/server/services/flow_files.go
+++ b/backend/pkg/server/services/flow_files.go
@@ -1561,17 +1561,36 @@ func (s *FlowFileService) AddResourcesToFlow(c *gin.Context) {
})
}
-// AddResourceFromFlow promotes a flow cache file or directory tree into the
-// user's global resource store. The response always lists every created or
-// updated entry, including any virtual parent directories that were ensured
-// during the promotion.
-// @Summary Promote a flow file or directory to user resources
+// sourceEntry is a validated (absPath → destPath) pair used internally by
+// AddResourceFromFlow to represent one item to promote to user resources.
+type sourceEntry struct {
+ absPath string // validated absolute path inside the flow cache
+ destPath string // sanitized virtual destination path in the resource tree
+ isDir bool
+}
+
+// AddResourceFromFlow promotes one or more flow cache files or directory trees
+// into the user's global resource store. Both Source (single, backward-compat)
+// and Sources (multi) can be provided and are merged + deduplicated before
+// processing. The response lists every created or updated entry.
+//
+// Single-source behaviour (exactly one unique source after dedup):
+//
+// Destination is the exact target path (file) or tree root (directory).
+//
+// Multi-source behaviour (two or more unique sources):
+//
+// Destination is treated as a base directory; each source's base name is
+// appended automatically so that "uploads/a.txt" + "container/b.txt" with
+// destination "results" → "results/a.txt" and "results/b.txt".
+//
+// @Summary Promote flow file(s) or directory/directories to user resources
// @Tags FlowFiles
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param flowID path int true "flow id" minimum(0)
-// @Param body body models.AddResourceFromFlowRequest true "source path, destination and force flag"
+// @Param body body models.AddResourceFromFlowRequest true "source(s), destination and force flag"
// @Success 200 {object} response.successResp{data=models.ResourceList} "resources created or updated"
// @Failure 400 {object} response.errorResp "invalid request"
// @Failure 403 {object} response.errorResp "not permitted"
@@ -1612,31 +1631,19 @@ func (s *FlowFileService) AddResourceFromFlow(c *gin.Context) {
return
}
- absPath, err := flowfiles.ResolveCachedPath(s.dataDir, flowID, req.Source)
- if err != nil {
- logger.FromContext(c).WithError(err).Error("invalid source path for add resource from flow")
- response.Error(c, response.ErrFlowFilesInvalidData, err)
- return
- }
-
- info, statErr := os.Lstat(absPath)
- if statErr != nil {
- if os.IsNotExist(statErr) {
- response.Error(c, response.ErrFlowFilesNotFound, statErr)
- return
- }
- logger.FromContext(c).WithError(statErr).Error("error stating flow source")
- response.Error(c, response.ErrInternal, statErr)
- return
+ // ── Merge + deduplicate source paths ──────────────────────────────────────
+ rawSources := req.Sources
+ if req.Source != "" {
+ rawSources = append(rawSources, req.Source)
}
- if !info.IsDir() && !info.Mode().IsRegular() {
- // Reject symlinks and other special files: os.Open would follow
- // symlinks at the OS level, bypassing the cache-root constraint.
- response.Error(c, response.ErrFlowFilesInvalidData,
- fmt.Errorf("source must be a regular file or a directory"))
+ dedupSources := flowfiles.DeduplicatePaths(rawSources)
+ if len(dedupSources) == 0 {
+ response.Error(c, response.ErrFlowFilesInvalidRequest,
+ errors.New("at least one source path is required (use 'source' or 'sources')"))
return
}
+ // ── Sanitize destination ──────────────────────────────────────────────────
destPath, err := resources.SanitizeResourcePath(req.Destination)
if err != nil {
logger.FromContext(c).WithError(err).Error("invalid destination path for add resource from flow")
@@ -1644,7 +1651,59 @@ func (s *FlowFileService) AddResourceFromFlow(c *gin.Context) {
return
}
- saved, ok := s.promoteToResources(c, uid, absPath, destPath, info.IsDir(), req.Force)
+ multiSource := len(dedupSources) > 1
+
+ // ── Validate and build source entries ─────────────────────────────────────
+ entries := make([]sourceEntry, 0, len(dedupSources))
+ for _, rawSrc := range dedupSources {
+ absPath, resolveErr := flowfiles.ResolveCachedPath(s.dataDir, flowID, rawSrc)
+ if resolveErr != nil {
+ logger.FromContext(c).WithError(resolveErr).Errorf("invalid source path %q", rawSrc)
+ response.Error(c, response.ErrFlowFilesInvalidData, resolveErr)
+ return
+ }
+
+ info, statErr := os.Lstat(absPath)
+ if statErr != nil {
+ if os.IsNotExist(statErr) {
+ response.Error(c, response.ErrFlowFilesNotFound, statErr)
+ return
+ }
+ logger.FromContext(c).WithError(statErr).Errorf("error stating flow source %q", rawSrc)
+ response.Error(c, response.ErrInternal, statErr)
+ return
+ }
+ if !info.IsDir() && !info.Mode().IsRegular() {
+ // Reject symlinks and other special files.
+ response.Error(c, response.ErrFlowFilesInvalidData,
+ fmt.Errorf("source %q must be a regular file or a directory", rawSrc))
+ return
+ }
+
+ var entryDest string
+ if multiSource {
+ // Multi-source: each entry lands under destination/<basename>.
+ baseName := path.Base(absPath)
+ var sanitizeErr error
+ entryDest, sanitizeErr = resources.SanitizeResourcePath(destPath + "/" + baseName)
+ if sanitizeErr != nil {
+ logger.FromContext(c).WithError(sanitizeErr).Errorf("invalid derived destination for source %q", rawSrc)
+ response.Error(c, response.ErrFlowFilesInvalidData, sanitizeErr)
+ return
+ }
+ } else {
+ // Single source: destination is used exactly as specified.
+ entryDest = destPath
+ }
+
+ entries = append(entries, sourceEntry{
+ absPath: absPath,
+ destPath: entryDest,
+ isDir: info.IsDir(),
+ })
+ }
+
+ saved, ok := s.promoteToResources(c, uid, entries, req.Force)
if !ok {
return
}
@@ -1652,20 +1711,23 @@ func (s *FlowFileService) AddResourceFromFlow(c *gin.Context) {
models.ResourceList{Items: saved, Total: uint64(len(saved))})
}
-// promoteToResources promotes a single regular file or a directory tree from
-// the flow cache into the user's resource store. Mirrors the three-phase
-// pattern used by UploadResources:
-// 1. walk and stream every regular file to a temporary blob (MD5-keyed)
-// 2. atomically commit blobs into the content-addressed store
-// 3. persist all directory and file rows inside one DB transaction
+// promoteToResources promotes one or more flow cache files / directory trees
+// into the user's resource store using a single three-phase transaction.
+//
+// Phase 1 – walk all sources and stream every regular file to a temporary blob.
+// Phase 2 – atomically commit each temp blob (idempotent on duplicate hashes).
+// Phase 3 – persist all directory and file rows in a single DB transaction.
+//
+// A seenVPaths map detects within-batch destination conflicts early (before
+// any DB work is done). The top-level destination directory of every directory
+// source is ensured even when the directory is empty.
//
-// Returns the slice of resulting entries (newly-created dirs, added files,
-// updated files in that order) on success, or false after writing an error
-// response on failure.
+// Returns the slice of resulting entries (created dirs → added files → updated
+// files in that order) on success, or false after writing an error response.
func (s *FlowFileService) promoteToResources(
c *gin.Context, uid uint64,
- absSourceRoot, destPath string,
- sourceIsDir, force bool,
+ sources []sourceEntry,
+ force bool,
) ([]models.ResourceEntry, bool) {
log := logger.FromContext(c)
ctx := c.Request.Context()
@@ -1677,73 +1739,96 @@ func (s *FlowFileService) promoteToResources(
}
blobsDir := resources.ResourcesDir(s.dataDir)
- // ── Phase 1: stream every regular file to a temporary blob ────────────────
+ // ── Phase 1: walk all sources, stream every regular file to a temp blob ───
+ //
+ // seenVPaths detects destination collisions within this single promotion
+ // batch (two different sources mapping to the same virtual path).
+ // topLevelDirs collects the root destination dirs of directory sources so
+ // that empty directories still get a row in the DB.
var pending []pendingResourceUpload
- walkErr := filepath.Walk(absSourceRoot, func(filePath string, fi os.FileInfo, err error) error {
- if err != nil {
- return err
- }
- // filepath.Walk uses Lstat → symlinks and special files are NOT regular
- // and are skipped here (defense-in-depth against symlinked-target reads).
- if !fi.Mode().IsRegular() {
- return nil
+ seenVPaths := make(map[string]bool)
+ var topLevelDirs []string
+
+ for _, src := range sources {
+ if src.isDir {
+ topLevelDirs = append(topLevelDirs, src.destPath)
}
- var virtPath string
- if sourceIsDir {
- rel, relErr := filepath.Rel(absSourceRoot, filePath)
- if relErr != nil {
- return fmt.Errorf("relative path: %w", relErr)
+ walkErr := filepath.Walk(src.absPath, func(filePath string, fi os.FileInfo, err error) error {
+ if err != nil {
+ return err
}
- sanitized, sanitizeErr := resources.SanitizeResourcePath(destPath + "/" + filepath.ToSlash(rel))
- if sanitizeErr != nil {
- log.WithError(sanitizeErr).Warnf("skipping unsafe file name %q", rel)
+ // filepath.Walk uses Lstat → symlinks and special files are NOT
+ // regular and are skipped here (defense-in-depth).
+ if !fi.Mode().IsRegular() {
return nil
}
- virtPath = sanitized
- } else {
- virtPath = destPath
- }
- // Phase 1 conflict pre-check: avoid IO when the destination obviously
- // conflicts. Phase 3 re-checks inside the TX as the source of truth.
- if !force {
- _, exists, dbErr := findResourceByPath(s.db, uid, virtPath)
- if dbErr != nil {
- return fmt.Errorf("checking %s: %w", virtPath, dbErr)
+ var virtPath string
+ if src.isDir {
+ rel, relErr := filepath.Rel(src.absPath, filePath)
+ if relErr != nil {
+ return fmt.Errorf("relative path: %w", relErr)
+ }
+ sanitized, sanitizeErr := resources.SanitizeResourcePath(
+ src.destPath + "/" + filepath.ToSlash(rel),
+ )
+ if sanitizeErr != nil {
+ log.WithError(sanitizeErr).Warnf("skipping unsafe file name %q", rel)
+ return nil
+ }
+ virtPath = sanitized
+ } else {
+ virtPath = src.destPath
}
- if exists {
- return fmt.Errorf("%w: resource already exists at %q", errResourceConflict, virtPath)
+
+ // Within-batch collision check: two sources mapping to the same
+ // virtual destination path is always an error.
+ if seenVPaths[virtPath] {
+ return fmt.Errorf("%w: two sources both target %q", errResourceConflict, virtPath)
}
- }
+ seenVPaths[virtPath] = true
- f, openErr := os.Open(filePath)
- if openErr != nil {
- return fmt.Errorf("open %s: %w", filePath, openErr)
- }
- tmpPath, hash, size, saveErr := resources.SaveToTemp(f, blobsDir)
- f.Close()
- if saveErr != nil {
- return fmt.Errorf("save temp for %s: %w", filePath, saveErr)
- }
- pending = append(pending, pendingResourceUpload{
- name: path.Base(virtPath),
- vPath: virtPath,
- tmpPath: tmpPath,
- hash: hash,
- size: size,
+ // Phase 1 conflict pre-check: avoid IO when the destination
+ // obviously conflicts. Phase 3 re-checks inside the TX.
+ if !force {
+ _, exists, dbErr := findResourceByPath(s.db, uid, virtPath)
+ if dbErr != nil {
+ return fmt.Errorf("checking %s: %w", virtPath, dbErr)
+ }
+ if exists {
+ return fmt.Errorf("%w: resource already exists at %q", errResourceConflict, virtPath)
+ }
+ }
+
+ f, openErr := os.Open(filePath)
+ if openErr != nil {
+ return fmt.Errorf("open %s: %w", filePath, openErr)
+ }
+ tmpPath, hash, size, saveErr := resources.SaveToTemp(f, blobsDir)
+ f.Close()
+ if saveErr != nil {
+ return fmt.Errorf("save temp for %s: %w", filePath, saveErr)
+ }
+ pending = append(pending, pendingResourceUpload{
+ name: path.Base(virtPath),
+ vPath: virtPath,
+ tmpPath: tmpPath,
+ hash: hash,
+ size: size,
+ })
+ return nil
})
- return nil
- })
- if walkErr != nil {
- cleanupResourceUploads(pending)
- if errors.Is(walkErr, errResourceConflict) {
- response.Error(c, response.ErrFlowFilesAlreadyExists, walkErr)
- } else {
- log.WithError(walkErr).Error("error reading source files for promotion")
- response.Error(c, response.ErrInternal, walkErr)
+ if walkErr != nil {
+ cleanupResourceUploads(pending)
+ if errors.Is(walkErr, errResourceConflict) {
+ response.Error(c, response.ErrFlowFilesAlreadyExists, walkErr)
+ } else {
+ log.WithError(walkErr).Errorf("error reading source files for promotion")
+ response.Error(c, response.ErrInternal, walkErr)
+ }
+ return nil, false
}
- return nil, false
}
// ── Phase 2: commit blobs (atomic rename; idempotent on duplicate hashes) ─
@@ -1768,18 +1853,6 @@ func (s *FlowFileService) promoteToResources(
p.newBlob = !existed
}
- // Determine the directory chain to ensure: the destination itself for a
- // directory promotion, or the parent of the file otherwise. May be empty
- // when promoting a single file at the resource root.
- parentDir := destPath
- if !sourceIsDir {
- if d := path.Dir(destPath); d != "." && d != "/" {
- parentDir = d
- } else {
- parentDir = ""
- }
- }
-
// ── Phase 3: persist all rows in a single DB transaction ──────────────────
tx := s.db.Begin()
if tx.Error != nil {
@@ -1793,21 +1866,47 @@ func (s *FlowFileService) promoteToResources(
var orphanHashes []string
var txErr error
- if parentDir != "" {
- rootDirs, _, rootOrphans, dirErr := ensureResourceDirs(tx, uid, parentDir, force)
+ // ensuredDirs tracks every directory path already ensured in this TX to
+ // avoid redundant DB calls for shared ancestor chains.
+ ensuredDirs := make(map[string]bool)
+
+ // Ensure top-level destination dirs of directory sources first. This
+ // guarantees a DB row even when the source directory is empty.
+ for _, dir := range topLevelDirs {
+ if ensuredDirs[dir] {
+ continue
+ }
+ ensuredDirs[dir] = true
+ rootDirs, _, rootOrphans, dirErr := ensureResourceDirs(tx, uid, dir, force)
if dirErr != nil {
txErr = dirErr
- } else {
- allDirs = append(allDirs, rootDirs...)
- orphanHashes = append(orphanHashes, rootOrphans...)
+ break
}
+ allDirs = append(allDirs, rootDirs...)
+ orphanHashes = append(orphanHashes, rootOrphans...)
}
- // Ensure each unique parent directory chain only once across all files.
- ensuredDirs := make(map[string]bool, len(pending))
- if parentDir != "" {
- ensuredDirs[parentDir] = true
+ // For single-file sources that land inside a directory, ensure the parent.
+ for _, src := range sources {
+ if txErr != nil {
+ break
+ }
+ if src.isDir {
+ continue // top-level already ensured above
+ }
+ if parentDir := path.Dir(src.destPath); parentDir != "." && parentDir != "/" && !ensuredDirs[parentDir] {
+ ensuredDirs[parentDir] = true
+ parentDirs, _, parentOrphans, dirErr := ensureResourceDirs(tx, uid, parentDir, force)
+ if dirErr != nil {
+ txErr = dirErr
+ break
+ }
+ allDirs = append(allDirs, parentDirs...)
+ orphanHashes = append(orphanHashes, parentOrphans...)
+ }
}
+
+ // Persist every pending file, ensuring any additional nested directories.
for _, p := range pending {
if txErr != nil {
break
diff --git a/backend/pkg/server/services/flow_files_test.go b/backend/pkg/server/services/flow_files_test.go
index ff19eaa9..4d5e27d7 100644
--- a/backend/pkg/server/services/flow_files_test.go
+++ b/backend/pkg/server/services/flow_files_test.go
@@ -3884,6 +3884,184 @@ func TestFlowFileService_AddResourceFromFlowScenarios(t *testing.T) {
},
wantEventChannel: "added",
},
+
+ // ── multi-source (sources []) tests ──────────────────────────────────
+ {
+ name: "multi-source: two files promoted to a common base directory",
+ flowOwner: 1, uid: 1, flowID: 1,
+ privs: []string{"resources.upload", "flow_files.view"},
+ sourceFiles: []sourceFile{
+ {relPath: "uploads/hosts.txt", content: "10.0.0.1"},
+ {relPath: "container/ports.txt", content: "80,443"},
+ },
+ body: map[string]any{
+ "sources": []string{"uploads/hosts.txt", "container/ports.txt"},
+ "destination": "scan-results",
+ },
+ wantStatus: http.StatusOK,
+ wantResourcePaths: []string{
+ "scan-results/hosts.txt",
+ "scan-results/ports.txt",
+ },
+ wantEventChannel: "added",
+ },
+ {
+ name: "multi-source: source and sources are merged and deduplicated",
+ flowOwner: 1, uid: 1, flowID: 1,
+ privs: []string{"resources.upload", "flow_files.view"},
+ sourceFiles: []sourceFile{
+ {relPath: "uploads/a.txt", content: "aaa"},
+ {relPath: "uploads/b.txt", content: "bbb"},
+ },
+ body: map[string]any{
+ // 'source' and 'sources' both provide uploads/a.txt → dedup to one
+ "source": "uploads/a.txt",
+ "sources": []string{"uploads/a.txt", "uploads/b.txt"},
+ "destination": "merged",
+ },
+ wantStatus: http.StatusOK,
+ wantResourcePaths: []string{
+ "merged/a.txt",
+ "merged/b.txt",
+ },
+ wantEventChannel: "added",
+ },
+ {
+ name: "multi-source: two directories promoted to a common base",
+ flowOwner: 1, uid: 1, flowID: 1,
+ privs: []string{"resources.upload", "flow_files.view"},
+ sourceFiles: []sourceFile{
+ {relPath: "container/web/index.html", content: "<html/>"},
+ {relPath: "container/web/style.css", content: "body{}"},
+ {relPath: "uploads/docs/readme.md", content: "# doc"},
+ },
+ body: map[string]any{
+ "sources": []string{"container/web", "uploads/docs"},
+ "destination": "artifacts",
+ },
+ wantStatus: http.StatusOK,
+ wantResourcePaths: []string{
+ "artifacts/web",
+ "artifacts/web/index.html",
+ "artifacts/web/style.css",
+ "artifacts/docs",
+ "artifacts/docs/readme.md",
+ },
+ wantEventChannel: "added",
+ },
+ {
+ name: "multi-source: mixed file and directory",
+ flowOwner: 1, uid: 1, flowID: 1,
+ privs: []string{"resources.upload", "flow_files.view"},
+ sourceFiles: []sourceFile{
+ {relPath: "uploads/report.txt", content: "report"},
+ {relPath: "container/scan/out.txt", content: "scan output"},
+ },
+ body: map[string]any{
+ "sources": []string{"uploads/report.txt", "container/scan"},
+ "destination": "bundle",
+ },
+ wantStatus: http.StatusOK,
+ wantResourcePaths: []string{
+ "bundle/report.txt",
+ "bundle/scan",
+ "bundle/scan/out.txt",
+ },
+ wantEventChannel: "added",
+ },
+ {
+ name: "multi-source: force overwrites existing resource",
+ flowOwner: 1, uid: 1, flowID: 1,
+ privs: []string{"resources.upload", "flow_files.view"},
+ sourceFiles: []sourceFile{
+ {relPath: "uploads/a.txt", content: "new-a"},
+ {relPath: "uploads/b.txt", content: "new-b"},
+ },
+ existingResource: &models.UserResource{
+ Hash: md5HexForFlowFiles("old-a"), Name: "a.txt", Path: "out/a.txt", Size: 5,
+ },
+ body: map[string]any{
+ "sources": []string{"uploads/a.txt", "uploads/b.txt"},
+ "destination": "out",
+ "force": true,
+ },
+ wantStatus: http.StatusOK,
+ wantResourcePaths: []string{
+ "out/a.txt",
+ "out/b.txt",
+ },
+ wantEventChannel: "added",
+ },
+ {
+ name: "multi-source: without force returns conflict when destination exists",
+ flowOwner: 1, uid: 1, flowID: 1,
+ privs: []string{"resources.upload", "flow_files.view"},
+ sourceFiles: []sourceFile{
+ {relPath: "uploads/a.txt", content: "new"},
+ {relPath: "uploads/extra.txt", content: "extra"}, // second source makes multiSource=true
+ },
+ existingResource: &models.UserResource{
+ Hash: md5HexForFlowFiles("old"), Name: "a.txt", Path: "out/a.txt", Size: 3,
+ },
+ body: map[string]any{
+ // two sources → multiSource=true → "out" + "/" + "a.txt" = "out/a.txt" → conflict
+ "sources": []string{"uploads/a.txt", "uploads/extra.txt"},
+ "destination": "out",
+ },
+ wantStatus: http.StatusConflict,
+ },
+ {
+ name: "multi-source: empty sources returns bad request",
+ flowOwner: 1, uid: 1, flowID: 1,
+ privs: []string{"resources.upload", "flow_files.view"},
+ body: map[string]any{
+ "sources": []string{},
+ "destination": "out",
+ },
+ wantStatus: http.StatusBadRequest,
+ },
+ {
+ name: "multi-source: sources with blank entries deduplicated to none returns bad request",
+ flowOwner: 1, uid: 1, flowID: 1,
+ privs: []string{"resources.upload", "flow_files.view"},
+ body: map[string]any{
+ "sources": []string{" ", ""},
+ "destination": "out",
+ },
+ wantStatus: http.StatusBadRequest,
+ },
+ {
+ name: "multi-source: one missing source returns not found",
+ flowOwner: 1, uid: 1, flowID: 1,
+ privs: []string{"resources.upload", "flow_files.view"},
+ sourceFiles: []sourceFile{
+ {relPath: "uploads/good.txt", content: "ok"},
+ },
+ body: map[string]any{
+ "sources": []string{"uploads/good.txt", "uploads/missing.txt"},
+ "destination": "out",
+ },
+ wantStatus: http.StatusNotFound,
+ },
+ {
+ name: "multi-source: empty directory in sources creates dir entry",
+ flowOwner: 1, uid: 1, flowID: 1,
+ privs: []string{"resources.upload", "flow_files.view"},
+ sourceDirs: []string{"uploads/empty-dir"},
+ sourceFiles: []sourceFile{
+ {relPath: "uploads/note.txt", content: "hi"},
+ },
+ body: map[string]any{
+ "sources": []string{"uploads/empty-dir", "uploads/note.txt"},
+ "destination": "multi-out",
+ },
+ wantStatus: http.StatusOK,
+ wantResourcePaths: []string{
+ "multi-out/empty-dir",
+ "multi-out/note.txt",
+ },
+ wantEventChannel: "added",
+ },
}
for _, tt := range tests {
diff --git a/backend/pkg/server/services/resources.go b/backend/pkg/server/services/resources.go
index c4daee16..2fed11a8 100644
--- a/backend/pkg/server/services/resources.go
+++ b/backend/pkg/server/services/resources.go
@@ -532,8 +532,23 @@ func (s *ResourceService) MkdirResource(c *gin.Context) {
// ---- PUT /resources/move ---------------------------------------------------
-// MoveResource renames or moves a file or directory.
-// @Summary Move or rename a resource (file or directory)
+// MoveResource moves or renames one or more resource files / directories.
+//
+// Single-source behaviour (exactly one unique source after dedup):
+//
+// Destination is the exact target path, inheriting existing trailing-slash
+// and existing-directory semantics (unchanged from original behaviour).
+//
+// Multi-source behaviour (two or more unique sources after dedup):
+//
+// Destination is always treated as a base directory. Each source lands at
+// destination/<basename>. All moves are executed in a single DB transaction
+// so the operation is atomic: either all succeed or none do.
+//
+// Response includes every Added (e.g. newly created parent directories) and
+// every Updated (moved items) entry so the Apollo cache can be updated correctly.
+//
+// @Summary Move or rename resource(s) (files or directories)
// @Tags Resources
// @Accept json
// @Produce json
@@ -561,45 +576,71 @@ func (s *ResourceService) MoveResource(c *gin.Context) {
return
}
- srcPath, err := resources.SanitizeResourcePath(req.Source)
- if err != nil {
- response.Error(c, response.ErrResourcesInvalidRequest, fmt.Errorf("invalid source: %w", err))
+ // ── Merge + deduplicate source paths ─────────────────────────────────────
+ rawSources := req.Sources
+ if req.Source != "" {
+ rawSources = append(rawSources, req.Source)
+ }
+ // reuse the same dedup helper used elsewhere (trims blanks, normalises, deduplicates)
+ dedupSources := deduplicateResourcePaths(rawSources)
+ if len(dedupSources) == 0 {
+ response.Error(c, response.ErrResourcesInvalidRequest,
+ errors.New("at least one source path is required (use 'source' or 'sources')"))
return
}
+
+ // ── Sanitize destination ──────────────────────────────────────────────────
dstPath, err := resources.SanitizeResourcePath(req.Destination)
if err != nil {
response.Error(c, response.ErrResourcesInvalidRequest, fmt.Errorf("invalid destination: %w", err))
return
}
- if srcPath == dstPath {
- response.Error(c, response.ErrResourcesInvalidRequest, errors.New("source and destination are the same"))
- return
+
+ // ── Sanitize all source paths ─────────────────────────────────────────────
+ srcPaths := make([]string, 0, len(dedupSources))
+ for _, raw := range dedupSources {
+ sp, sanitizeErr := resources.SanitizeResourcePath(raw)
+ if sanitizeErr != nil {
+ response.Error(c, response.ErrResourcesInvalidRequest, fmt.Errorf("invalid source %q: %w", raw, sanitizeErr))
+ return
+ }
+ srcPaths = append(srcPaths, sp)
}
- var src models.UserResource
- if err := s.db.Where("user_id = ? AND path = ?", uid, srcPath).First(&src).Error; err != nil {
- if gorm.IsRecordNotFoundError(err) {
- response.Error(c, response.ErrResourcesNotFound, fmt.Errorf("resource %q not found", srcPath))
+ // ── Route to single-source or multi-source path ───────────────────────────
+ var result moveResourceResult
+ if len(srcPaths) == 1 {
+ srcPath := srcPaths[0]
+ if srcPath == dstPath {
+ response.Error(c, response.ErrResourcesInvalidRequest, errors.New("source and destination are the same"))
return
}
- logger.FromContext(c).WithError(err).Error("error finding source resource for move")
- response.Error(c, response.ErrInternal, err)
- return
+ var src models.UserResource
+ if err := s.db.Where("user_id = ? AND path = ?", uid, srcPath).First(&src).Error; err != nil {
+ if gorm.IsRecordNotFoundError(err) {
+ response.Error(c, response.ErrResourcesNotFound, fmt.Errorf("resource %q not found", srcPath))
+ return
+ }
+ logger.FromContext(c).WithError(err).Error("error finding source resource for move")
+ response.Error(c, response.ErrInternal, err)
+ return
+ }
+ result, err = s.moveResource(uid, src, srcPath, dstPath, req.Force, pathHasTrailingSeparator(req.Destination))
+ } else {
+ result, err = s.moveMultipleSources(uid, srcPaths, dstPath, req.Force)
}
- result, moveErr := s.moveResource(uid, src, srcPath, dstPath, req.Force, pathHasTrailingSeparator(req.Destination))
- if moveErr != nil {
+ if err != nil {
switch {
- case errors.Is(moveErr, errResourceInvalid):
- response.Error(c, response.ErrResourcesInvalidRequest, moveErr)
- case errors.Is(moveErr, errResourceConflict):
- response.Error(c, response.ErrResourcesConflict,
- fmt.Errorf("destination %q already exists; move items individually", dstPath))
- case errors.Is(moveErr, errResourceNotFound):
- response.Error(c, response.ErrResourcesNotFound, fmt.Errorf("resource %q not found", srcPath))
+ case errors.Is(err, errResourceInvalid):
+ response.Error(c, response.ErrResourcesInvalidRequest, err)
+ case errors.Is(err, errResourceConflict):
+ response.Error(c, response.ErrResourcesConflict, err)
+ case errors.Is(err, errResourceNotFound):
+ response.Error(c, response.ErrResourcesNotFound, err)
default:
- logger.FromContext(c).WithError(moveErr).Error("error moving resource")
- response.Error(c, response.ErrInternal, moveErr)
+ logger.FromContext(c).WithError(err).Error("error moving resource(s)")
+ response.Error(c, response.ErrInternal, err)
}
return
}
@@ -609,7 +650,144 @@ func (s *ResourceService) MoveResource(c *gin.Context) {
s.publishResourcesAdded(c.Request.Context(), uid, result.Added)
s.publishResourcesUpdated(c.Request.Context(), uid, result.Updated)
s.publishResourcesDeleted(c.Request.Context(), uid, result.DeletedAfter)
- response.Success(c, http.StatusOK, models.ResourceList{Items: result.Updated, Total: uint64(len(result.Updated))})
+
+ // Return Added + Updated: the frontend Apollo cache needs both newly created
+ // parent directories (Added) and the moved items themselves (Updated) to
+ // reflect the full post-move state.
+ all := append(result.Added, result.Updated...)
+ response.Success(c, http.StatusOK, models.ResourceList{Items: all, Total: uint64(len(all))})
+}
+
+// moveMultipleSources moves every source path to destination/<source.Name>
+// inside a single DB transaction for full atomicity.
+//
+// Optimisations vs calling moveResource N times:
+// - One TX for all moves (atomic: all-or-nothing).
+// - Batch source lookup (one query regardless of N).
+// - Within-batch duplicate-basename detection before any DB writes.
+// - ensureResourceDirs for the destination dir is called once; inner
+// per-source calls are no-ops because the dir already exists.
+func (s *ResourceService) moveMultipleSources(
+ uid uint64,
+ srcPaths []string,
+ dstPath string,
+ force bool,
+) (moveResourceResult, error) {
+ result := moveResourceResult{}
+
+ tx := s.db.Begin()
+ if tx.Error != nil {
+ return result, tx.Error
+ }
+
+ // ── Batch-load all source records in one query ────────────────────────────
+ srcs, err := findResourcesByPaths(tx, uid, srcPaths)
+ if err != nil {
+ tx.Rollback()
+ return result, err
+ }
+
+ // Verify every source exists.
+ if len(srcs) != len(srcPaths) {
+ tx.Rollback()
+ found := resourcesByPath(srcs)
+ for _, sp := range srcPaths {
+ if _, ok := found[sp]; !ok {
+ return result, fmt.Errorf("%w: resource %q not found", errResourceNotFound, sp)
+ }
+ }
+ }
+
+ // ── Within-batch target-basename conflict check ───────────────────────────
+ // Two sources sharing a basename would both land at the same target path.
+ basenameToSrc := make(map[string]string, len(srcs))
+ for _, src := range srcs {
+ if prev, conflict := basenameToSrc[src.Name]; conflict {
+ tx.Rollback()
+ return result, fmt.Errorf(
+ "%w: sources %q and %q share the same base name %q",
+ errResourceConflict, prev, src.Path, src.Name,
+ )
+ }
+ basenameToSrc[src.Name] = src.Path
+ }
+
+ // Self-move guard: no source may be a directory that contains dstPath.
+ for _, src := range srcs {
+ if src.IsDir && resources.PathHasPrefix(dstPath, src.Path) {
+ tx.Rollback()
+ return result, fmt.Errorf(
+ "%w: cannot move directory %q into itself", errResourceInvalid, src.Path,
+ )
+ }
+ if resources.FilePath(dstPath, src.Name) == src.Path {
+ tx.Rollback()
+ return result, fmt.Errorf(
+ "%w: source and destination are the same for %q", errResourceInvalid, src.Path,
+ )
+ }
+ }
+
+ // ── Ensure destination directory ──────────────────────────────────────────
+ dest, destExists, err := findResourceByPath(tx, uid, dstPath)
+ if err != nil {
+ tx.Rollback()
+ return result, err
+ }
+ if destExists && !dest.IsDir {
+ tx.Rollback()
+ return result, fmt.Errorf(
+ "%w: destination %q is a file; cannot move multiple sources into it",
+ errResourceConflict, dstPath,
+ )
+ }
+ if !destExists {
+ createdDirs, deletedDirs, orphanHashes, dirErr := ensureResourceDirs(tx, uid, dstPath, force)
+ if dirErr != nil {
+ tx.Rollback()
+ return result, dirErr
+ }
+ result.Added = append(result.Added, convertResources(createdDirs)...)
+ result.DeletedBefore = append(result.DeletedBefore, convertResources(deletedDirs)...)
+ result.OrphanHashes = append(result.OrphanHashes, orphanHashes...)
+ }
+
+ // ── Move each source into destination/<basename> ──────────────────────────
+ // The inner move functions (moveFileResource / moveDirResource) call
+ // ensureResourceDirs for the parent of the target path. Since dstPath is
+ // already ensured above, those calls are idempotent no-ops.
+ srcByPath := resourcesByPath(srcs)
+ for _, sp := range srcPaths { // preserve original request order
+ src, ok := srcByPath[sp]
+ if !ok {
+ continue // guarded by existence check above
+ }
+ targetPath := resources.FilePath(dstPath, src.Name)
+
+ var moveResult moveResourceResult
+ if !src.IsDir {
+ // Pass dstIsDirHint=false: targetPath is the exact file destination.
+ moveResult, err = s.moveFileResource(tx, uid, src, targetPath, force, false)
+ } else {
+ moveResult, err = s.moveDirResource(tx, uid, src.Path, targetPath, force)
+ }
+ if err != nil {
+ tx.Rollback()
+ return result, err
+ }
+
+ result.Added = append(result.Added, moveResult.Added...)
+ result.Updated = append(result.Updated, moveResult.Updated...)
+ result.DeletedBefore = append(result.DeletedBefore, moveResult.DeletedBefore...)
+ result.DeletedAfter = append(result.DeletedAfter, moveResult.DeletedAfter...)
+ result.OrphanHashes = append(result.OrphanHashes, moveResult.OrphanHashes...)
+ }
+
+ if err := tx.Commit().Error; err != nil {
+ tx.Rollback()
+ return result, err
+ }
+ return result, nil
}
var errResourceConflict = errors.New("resource conflict")
@@ -984,8 +1162,20 @@ func updateMovedResource(tx *gorm.DB, rec models.UserResource, newPath string, n
// ---- POST /resources/copy --------------------------------------------------
-// CopyResource copies a file or directory to a new path.
-// @Summary Copy a resource (file or directory)
+// CopyResource copies one or more resource files / directories to a new path.
+//
+// Single-source behaviour (exactly one unique source after dedup):
+//
+// Destination is the exact target path, inheriting existing trailing-slash
+// and existing-directory semantics (unchanged from original behaviour).
+//
+// Multi-source behaviour (two or more unique sources after dedup):
+//
+// Destination is always treated as a base directory. Each source lands at
+// destination/<basename>. All copies are executed in a single DB transaction
+// so the operation is atomic: either all succeed or none do.
+//
+// @Summary Copy resource(s) (files or directories)
// @Tags Resources
// @Accept json
// @Produce json
@@ -1013,50 +1203,75 @@ func (s *ResourceService) CopyResource(c *gin.Context) {
return
}
- srcPath, err := resources.SanitizeResourcePath(req.Source)
- if err != nil {
- response.Error(c, response.ErrResourcesInvalidRequest, fmt.Errorf("invalid source: %w", err))
+ // ── Merge + deduplicate source paths ─────────────────────────────────────
+ rawSources := req.Sources
+ if req.Source != "" {
+ rawSources = append(rawSources, req.Source)
+ }
+ dedupSources := deduplicateResourcePaths(rawSources)
+ if len(dedupSources) == 0 {
+ response.Error(c, response.ErrResourcesInvalidRequest,
+ errors.New("at least one source path is required (use 'source' or 'sources')"))
return
}
+
+ // ── Sanitize destination ──────────────────────────────────────────────────
dstPath, err := resources.SanitizeResourcePath(req.Destination)
if err != nil {
response.Error(c, response.ErrResourcesInvalidRequest, fmt.Errorf("invalid destination: %w", err))
return
}
- if srcPath == dstPath {
- response.Error(c, response.ErrResourcesInvalidRequest, errors.New("source and destination are the same"))
- return
+
+ // ── Sanitize all source paths ─────────────────────────────────────────────
+ srcPaths := make([]string, 0, len(dedupSources))
+ for _, raw := range dedupSources {
+ sp, sanitizeErr := resources.SanitizeResourcePath(raw)
+ if sanitizeErr != nil {
+ response.Error(c, response.ErrResourcesInvalidRequest, fmt.Errorf("invalid source %q: %w", raw, sanitizeErr))
+ return
+ }
+ srcPaths = append(srcPaths, sp)
}
- var src models.UserResource
- if err := s.db.Where("user_id = ? AND path = ?", uid, srcPath).First(&src).Error; err != nil {
- if gorm.IsRecordNotFoundError(err) {
- response.Error(c, response.ErrResourcesNotFound, fmt.Errorf("resource %q not found", srcPath))
+ // ── Route to single-source or multi-source path ───────────────────────────
+ var result copyResourceResult
+ if len(srcPaths) == 1 {
+ srcPath := srcPaths[0]
+ if srcPath == dstPath {
+ response.Error(c, response.ErrResourcesInvalidRequest, errors.New("source and destination are the same"))
return
}
- logger.FromContext(c).WithError(err).Error("error finding source resource for copy")
- response.Error(c, response.ErrInternal, err)
- return
+ var src models.UserResource
+ if err := s.db.Where("user_id = ? AND path = ?", uid, srcPath).First(&src).Error; err != nil {
+ if gorm.IsRecordNotFoundError(err) {
+ response.Error(c, response.ErrResourcesNotFound, fmt.Errorf("resource %q not found", srcPath))
+ return
+ }
+ logger.FromContext(c).WithError(err).Error("error finding source resource for copy")
+ response.Error(c, response.ErrInternal, err)
+ return
+ }
+ result, err = s.copyResource(uid, src, srcPath, dstPath, req.Force, pathHasTrailingSeparator(req.Destination))
+ } else {
+ result, err = s.copyMultipleSources(uid, srcPaths, dstPath, req.Force)
}
- result, copyErr := s.copyResource(uid, src, srcPath, dstPath, req.Force, pathHasTrailingSeparator(req.Destination))
- if copyErr != nil {
+ if err != nil {
switch {
- case errors.Is(copyErr, errResourceInvalid):
- response.Error(c, response.ErrResourcesInvalidRequest, copyErr)
- case errors.Is(copyErr, errResourceConflict):
- response.Error(c, response.ErrResourcesConflict,
- fmt.Errorf("destination already exists; use force=true to merge/overwrite"))
+ case errors.Is(err, errResourceInvalid):
+ response.Error(c, response.ErrResourcesInvalidRequest, err)
+ case errors.Is(err, errResourceConflict):
+ response.Error(c, response.ErrResourcesConflict, err)
+ case errors.Is(err, errResourceNotFound):
+ response.Error(c, response.ErrResourcesNotFound, err)
default:
- logger.FromContext(c).WithError(copyErr).Error("error copying resource")
- response.Error(c, response.ErrInternal, copyErr)
+ logger.FromContext(c).WithError(err).Error("error copying resource(s)")
+ response.Error(c, response.ErrInternal, err)
}
return
}
- // Orphan-check for overwritten blobs (after TX committed).
s.cleanupOrphanBlobs(c.Request.Context(), result.OrphanHashes)
-
s.publishResourcesDeleted(c.Request.Context(), uid, result.Deleted)
s.publishResourcesAdded(c.Request.Context(), uid, result.Added)
s.publishResourcesUpdated(c.Request.Context(), uid, result.Updated)
@@ -1065,6 +1280,133 @@ func (s *ResourceService) CopyResource(c *gin.Context) {
response.Success(c, http.StatusOK, models.ResourceList{Items: all, Total: uint64(len(all))})
}
+// copyMultipleSources copies every source path to destination/<source.Name>
+// inside a single DB transaction for full atomicity.
+//
+// Optimisations vs calling copyResource N times:
+// - One TX for all copies (atomic: all-or-nothing).
+// - Batch source lookup (one query regardless of N).
+// - Within-batch duplicate-basename detection before any DB writes.
+// - ensureResourceDirs for the destination dir is called once; inner
+// per-source calls are no-ops because the dir already exists.
+func (s *ResourceService) copyMultipleSources(
+ uid uint64,
+ srcPaths []string,
+ dstPath string,
+ force bool,
+) (copyResourceResult, error) {
+ result := copyResourceResult{}
+
+ tx := s.db.Begin()
+ if tx.Error != nil {
+ return result, tx.Error
+ }
+
+ // ── Batch-load all source records ─────────────────────────────────────────
+ srcs, err := findResourcesByPaths(tx, uid, srcPaths)
+ if err != nil {
+ tx.Rollback()
+ return result, err
+ }
+
+ // Verify every source exists.
+ if len(srcs) != len(srcPaths) {
+ tx.Rollback()
+ found := resourcesByPath(srcs)
+ for _, sp := range srcPaths {
+ if _, ok := found[sp]; !ok {
+ return result, fmt.Errorf("%w: resource %q not found", errResourceNotFound, sp)
+ }
+ }
+ }
+
+ // ── Within-batch target-basename conflict check ───────────────────────────
+ basenameToSrc := make(map[string]string, len(srcs))
+ for _, src := range srcs {
+ if prev, conflict := basenameToSrc[src.Name]; conflict {
+ tx.Rollback()
+ return result, fmt.Errorf(
+ "%w: sources %q and %q share the same base name %q",
+ errResourceConflict, prev, src.Path, src.Name,
+ )
+ }
+ basenameToSrc[src.Name] = src.Path
+ }
+
+ // Self-copy guard: copying a directory into itself.
+ for _, src := range srcs {
+ if src.IsDir && resources.PathHasPrefix(dstPath, src.Path) {
+ tx.Rollback()
+ return result, fmt.Errorf(
+ "%w: cannot copy directory %q into itself", errResourceInvalid, src.Path,
+ )
+ }
+ if resources.FilePath(dstPath, src.Name) == src.Path {
+ tx.Rollback()
+ return result, fmt.Errorf(
+ "%w: source and destination are the same for %q", errResourceInvalid, src.Path,
+ )
+ }
+ }
+
+ // ── Ensure destination directory ──────────────────────────────────────────
+ dest, destExists, err := findResourceByPath(tx, uid, dstPath)
+ if err != nil {
+ tx.Rollback()
+ return result, err
+ }
+ if destExists && !dest.IsDir {
+ tx.Rollback()
+ return result, fmt.Errorf(
+ "%w: destination %q is a file; cannot copy multiple sources into it",
+ errResourceConflict, dstPath,
+ )
+ }
+ if !destExists {
+ createdDirs, deletedDirs, orphanHashes, dirErr := ensureResourceDirs(tx, uid, dstPath, force)
+ if dirErr != nil {
+ tx.Rollback()
+ return result, dirErr
+ }
+ result.Added = append(result.Added, convertResources(createdDirs)...)
+ result.Deleted = append(result.Deleted, convertResources(deletedDirs)...)
+ result.OrphanHashes = append(result.OrphanHashes, orphanHashes...)
+ }
+
+ // ── Copy each source into destination/<basename> ──────────────────────────
+ srcByPath := resourcesByPath(srcs)
+ for _, sp := range srcPaths { // preserve original request order
+ src, ok := srcByPath[sp]
+ if !ok {
+ continue
+ }
+ targetPath := resources.FilePath(dstPath, src.Name)
+
+ var copyResult copyResourceResult
+ if !src.IsDir {
+ // Pass dstIsDirHint=false: targetPath is the exact file destination.
+ copyResult, err = s.copyFileResource(tx, uid, src, targetPath, force, false)
+ } else {
+ copyResult, err = s.copyDirResource(tx, uid, src.Path, targetPath, force)
+ }
+ if err != nil {
+ tx.Rollback()
+ return result, err
+ }
+
+ result.Added = append(result.Added, copyResult.Added...)
+ result.Updated = append(result.Updated, copyResult.Updated...)
+ result.Deleted = append(result.Deleted, copyResult.Deleted...)
+ result.OrphanHashes = append(result.OrphanHashes, copyResult.OrphanHashes...)
+ }
+
+ if err := tx.Commit().Error; err != nil {
+ tx.Rollback()
+ return result, err
+ }
+ return result, nil
+}
+
type copyResourceResult struct {
Added []models.ResourceEntry
Updated []models.ResourceEntry
@@ -1788,6 +2130,26 @@ func cleanupResourceUploads(pending []pendingResourceUpload) {
}
}
+// deduplicateResourcePaths removes blank and duplicate virtual resource paths,
+// preserving the first occurrence of each unique (cleaned) path.
+func deduplicateResourcePaths(paths []string) []string {
+ seen := make(map[string]struct{}, len(paths))
+ result := make([]string, 0, len(paths))
+ for _, p := range paths {
+ trimmed := strings.TrimSpace(p)
+ if trimmed == "" {
+ continue
+ }
+ normalized := path.Clean(trimmed)
+ if _, ok := seen[normalized]; ok {
+ continue
+ }
+ seen[normalized] = struct{}{}
+ result = append(result, trimmed)
+ }
+ return result
+}
+
func pathHasTrailingSeparator(p string) bool {
trimmed := strings.TrimSpace(p)
return strings.HasSuffix(trimmed, "/") || strings.HasSuffix(trimmed, "\\")
diff --git a/backend/pkg/server/services/resources_test.go b/backend/pkg/server/services/resources_test.go
index 0a009d0a..7ce19779 100644
--- a/backend/pkg/server/services/resources_test.go
+++ b/backend/pkg/server/services/resources_test.go
@@ -1706,9 +1706,10 @@ func TestResourceService_CopyResourceScenarios(t *testing.T) {
content string
}
type copyRequest struct {
- Source string `json:"source"`
- Destination string `json:"destination"`
- Force bool `json:"force,omitempty"`
+ Source string `json:"source,omitempty"`
+ Sources []string `json:"sources,omitempty"`
+ Destination string `json:"destination"`
+ Force bool `json:"force,omitempty"`
}
tests := []struct {
@@ -1975,6 +1976,184 @@ func TestResourceService_CopyResourceScenarios(t *testing.T) {
wantStatus: http.StatusBadRequest,
wantPaths: []string{"a.txt"},
},
+
+ // ── multi-source (sources []) ─────────────────────────────────────────
+ {
+ name: "multi-source: two files copied to a common base directory",
+ seeds: []seed{
+ {path: "a.txt", content: "aaa"},
+ {path: "b.txt", content: "bbb"},
+ },
+ req: copyRequest{Sources: []string{"a.txt", "b.txt"}, Destination: "backup"},
+ wantStatus: http.StatusOK,
+ wantPaths: []string{"a.txt", "b.txt", "backup", "backup/a.txt", "backup/b.txt"},
+ wantResponsePaths: []string{"backup", "backup/a.txt", "backup/b.txt"},
+ wantEvents: []resourceEvent{
+ {action: "added", path: "backup"},
+ {action: "added", path: "backup/a.txt"},
+ {action: "added", path: "backup/b.txt"},
+ },
+ },
+ {
+ name: "multi-source: source and sources merged and deduplicated",
+ seeds: []seed{
+ {path: "a.txt", content: "aaa"},
+ {path: "b.txt", content: "bbb"},
+ },
+ req: copyRequest{Source: "a.txt", Sources: []string{"a.txt", "b.txt"}, Destination: "backup"},
+ wantStatus: http.StatusOK,
+ wantPaths: []string{"a.txt", "b.txt", "backup", "backup/a.txt", "backup/b.txt"},
+ wantResponsePaths: []string{"backup", "backup/a.txt", "backup/b.txt"},
+ wantEvents: []resourceEvent{
+ {action: "added", path: "backup"},
+ {action: "added", path: "backup/a.txt"},
+ {action: "added", path: "backup/b.txt"},
+ },
+ },
+ {
+ name: "multi-source: file and directory copied to existing base directory",
+ seeds: []seed{
+ {path: "report.txt", content: "r"},
+ {path: "docs", isDir: true},
+ {path: "docs/readme.md", content: "readme"},
+ {path: "dest", isDir: true},
+ },
+ req: copyRequest{Sources: []string{"report.txt", "docs"}, Destination: "dest"},
+ wantStatus: http.StatusOK,
+ wantPaths: []string{"report.txt", "docs", "docs/readme.md", "dest", "dest/report.txt", "dest/docs", "dest/docs/readme.md"},
+ wantResponsePaths: []string{
+ "dest/report.txt",
+ "dest/docs",
+ "dest/docs/readme.md",
+ },
+ wantEvents: []resourceEvent{
+ {action: "added", path: "dest/report.txt"},
+ {action: "added", path: "dest/docs"},
+ {action: "added", path: "dest/docs/readme.md"},
+ },
+ },
+ {
+ name: "multi-source: force overwrites existing file at target",
+ seeds: []seed{
+ {path: "a.txt", content: "new-a"},
+ {path: "b.txt", content: "new-b"},
+ {path: "backup", isDir: true},
+ {path: "backup/a.txt", content: "old-a"},
+ },
+ req: copyRequest{Sources: []string{"a.txt", "b.txt"}, Destination: "backup", Force: true},
+ wantStatus: http.StatusOK,
+ wantPaths: []string{"a.txt", "b.txt", "backup", "backup/a.txt", "backup/b.txt"},
+ wantResponsePaths: []string{
+ "backup/a.txt",
+ "backup/b.txt",
+ },
+ // Publish order: Deleted → Added → Updated.
+ wantEvents: []resourceEvent{
+ {action: "deleted", path: "backup/a.txt"},
+ {action: "added", path: "backup/b.txt"},
+ {action: "updated", path: "backup/a.txt"},
+ },
+ wantDeletedBlobTexts: []string{"old-a"},
+ },
+ {
+ name: "multi-source: without force returns conflict when target exists",
+ seeds: []seed{
+ {path: "a.txt", content: "a"},
+ {path: "b.txt", content: "b"},
+ {path: "backup", isDir: true},
+ {path: "backup/a.txt", content: "old"},
+ },
+ req: copyRequest{Sources: []string{"a.txt", "b.txt"}, Destination: "backup"},
+ wantStatus: http.StatusConflict,
+ wantPaths: []string{"a.txt", "b.txt", "backup", "backup/a.txt"},
+ },
+ {
+ name: "multi-source: duplicate basenames returns conflict",
+ seeds: []seed{
+ {path: "dir1/x.txt", content: "x1"},
+ {path: "dir2/x.txt", content: "x2"},
+ },
+ req: copyRequest{Sources: []string{"dir1/x.txt", "dir2/x.txt"}, Destination: "backup"},
+ wantStatus: http.StatusConflict,
+ wantPaths: []string{"dir1/x.txt", "dir2/x.txt"},
+ },
+ {
+ name: "multi-source: one missing source returns not found",
+ seeds: []seed{
+ {path: "a.txt", content: "a"},
+ },
+ req: copyRequest{Sources: []string{"a.txt", "ghost.txt"}, Destination: "backup"},
+ wantStatus: http.StatusNotFound,
+ wantPaths: []string{"a.txt"},
+ },
+ {
+ name: "multi-source: empty sources returns bad request",
+ req: copyRequest{Sources: []string{}, Destination: "backup"},
+ wantStatus: http.StatusBadRequest,
+ },
+ {
+ name: "multi-source: blank entries only returns bad request",
+ req: copyRequest{Sources: []string{" ", ""}, Destination: "backup"},
+ wantStatus: http.StatusBadRequest,
+ },
+ {
+ name: "multi-source: destination is a file returns conflict",
+ seeds: []seed{
+ {path: "a.txt", content: "a"},
+ {path: "b.txt", content: "b"},
+ {path: "dest.file", content: "file"},
+ },
+ req: copyRequest{Sources: []string{"a.txt", "b.txt"}, Destination: "dest.file"},
+ wantStatus: http.StatusConflict,
+ wantPaths: []string{"a.txt", "b.txt", "dest.file"},
+ },
+ {
+ name: "multi-source: directory into itself returns bad request",
+ seeds: []seed{
+ {path: "docs", isDir: true},
+ {path: "a.txt", content: "a"},
+ },
+ req: copyRequest{Sources: []string{"docs", "a.txt"}, Destination: "docs/sub"},
+ wantStatus: http.StatusBadRequest,
+ wantPaths: []string{"a.txt", "docs"},
+ },
+ {
+ name: "multi-source: two directories copied to common base",
+ seeds: []seed{
+ {path: "src1", isDir: true},
+ {path: "src1/file1.txt", content: "f1"},
+ {path: "src2", isDir: true},
+ {path: "src2/file2.txt", content: "f2"},
+ },
+ req: copyRequest{Sources: []string{"src1", "src2"}, Destination: "all"},
+ wantStatus: http.StatusOK,
+ wantPaths: []string{
+ "src1", "src1/file1.txt",
+ "src2", "src2/file2.txt",
+ "all", "all/src1", "all/src1/file1.txt",
+ "all/src2", "all/src2/file2.txt",
+ },
+ wantResponsePaths: []string{
+ "all", "all/src1", "all/src1/file1.txt",
+ "all/src2", "all/src2/file2.txt",
+ },
+ wantEvents: []resourceEvent{
+ {action: "added", path: "all"},
+ {action: "added", path: "all/src1"},
+ {action: "added", path: "all/src1/file1.txt"},
+ {action: "added", path: "all/src2"},
+ {action: "added", path: "all/src2/file2.txt"},
+ },
+ },
+ {
+ name: "multi-source: invalid source path returns bad request",
+ seeds: []seed{
+ {path: "a.txt", content: "a"},
+ },
+ req: copyRequest{Sources: []string{"../escape.txt", "a.txt"}, Destination: "backup"},
+ wantStatus: http.StatusBadRequest,
+ wantPaths: []string{"a.txt"},
+ },
}
for _, tt := range tests {
@@ -2082,9 +2261,10 @@ func TestResourceService_MoveResourceScenarios(t *testing.T) {
content string
}
type moveRequest struct {
- Source string `json:"source"`
- Destination string `json:"destination"`
- Force bool `json:"force,omitempty"`
+ Source string `json:"source,omitempty"`
+ Sources []string `json:"sources,omitempty"`
+ Destination string `json:"destination"`
+ Force bool `json:"force,omitempty"`
}
tests := []struct {
@@ -2123,7 +2303,7 @@ func TestResourceService_MoveResourceScenarios(t *testing.T) {
req: moveRequest{Source: "a.txt", Destination: "docs/"},
wantStatus: http.StatusOK,
wantPaths: []string{"docs", "docs/a.txt"},
- wantResponsePaths: []string{"docs/a.txt"},
+ wantResponsePaths: []string{"docs", "docs/a.txt"},
wantEvents: []resourceEvent{{action: "added", path: "docs"}, {action: "updated", path: "docs/a.txt"}},
},
{
@@ -2148,7 +2328,7 @@ func TestResourceService_MoveResourceScenarios(t *testing.T) {
req: moveRequest{Source: "a.txt", Destination: "docs/", Force: true},
wantStatus: http.StatusOK,
wantPaths: []string{"docs", "docs/a.txt"},
- wantResponsePaths: []string{"docs/a.txt"},
+ wantResponsePaths: []string{"docs", "docs/a.txt"},
wantEvents: []resourceEvent{{action: "deleted", path: "docs"}, {action: "added", path: "docs"}, {action: "updated", path: "docs/a.txt"}},
wantDeletedBlobTexts: []string{"blocking"},
},
@@ -2186,7 +2366,7 @@ func TestResourceService_MoveResourceScenarios(t *testing.T) {
req: moveRequest{Source: "a.txt", Destination: "one/two/three/a.txt"},
wantStatus: http.StatusOK,
wantPaths: []string{"one", "one/two", "one/two/three", "one/two/three/a.txt"},
- wantResponsePaths: []string{"one/two/three/a.txt"},
+ wantResponsePaths: []string{"one", "one/two", "one/two/three", "one/two/three/a.txt"},
wantEvents: []resourceEvent{
{action: "added", path: "one"},
{action: "added", path: "one/two"},
@@ -2255,7 +2435,7 @@ func TestResourceService_MoveResourceScenarios(t *testing.T) {
req: moveRequest{Source: "docs", Destination: "archive/docs"},
wantStatus: http.StatusOK,
wantPaths: []string{"archive", "archive/docs", "archive/docs/a.txt", "archive/docs/sub", "archive/docs/sub/b.txt"},
- wantResponsePaths: []string{"archive/docs", "archive/docs/a.txt", "archive/docs/sub", "archive/docs/sub/b.txt"},
+ wantResponsePaths: []string{"archive", "archive/docs", "archive/docs/a.txt", "archive/docs/sub", "archive/docs/sub/b.txt"},
wantEvents: []resourceEvent{
{action: "added", path: "archive"},
{action: "updated", path: "archive/docs"},
@@ -2356,6 +2536,160 @@ func TestResourceService_MoveResourceScenarios(t *testing.T) {
wantStatus: http.StatusBadRequest,
wantPaths: []string{"a.txt"},
},
+
+ // ── multi-source (sources []) ─────────────────────────────────────────
+ {
+ name: "multi-source: two files moved to a common base directory",
+ seeds: []seed{
+ {path: "a.txt", content: "aaa"},
+ {path: "b.txt", content: "bbb"},
+ },
+ req: moveRequest{Sources: []string{"a.txt", "b.txt"}, Destination: "archive"},
+ wantStatus: http.StatusOK,
+ wantPaths: []string{"archive", "archive/a.txt", "archive/b.txt"},
+ wantResponsePaths: []string{"archive", "archive/a.txt", "archive/b.txt"},
+ wantEvents: []resourceEvent{
+ {action: "added", path: "archive"},
+ {action: "updated", path: "archive/a.txt"},
+ {action: "updated", path: "archive/b.txt"},
+ },
+ },
+ {
+ name: "multi-source: source and sources merged and deduplicated",
+ seeds: []seed{
+ {path: "a.txt", content: "aaa"},
+ {path: "b.txt", content: "bbb"},
+ },
+ // a.txt appears in both source and sources → deduplicated to one
+ req: moveRequest{Source: "a.txt", Sources: []string{"a.txt", "b.txt"}, Destination: "archive"},
+ wantStatus: http.StatusOK,
+ wantPaths: []string{"archive", "archive/a.txt", "archive/b.txt"},
+ wantResponsePaths: []string{"archive", "archive/a.txt", "archive/b.txt"},
+ wantEvents: []resourceEvent{
+ {action: "added", path: "archive"},
+ {action: "updated", path: "archive/a.txt"},
+ {action: "updated", path: "archive/b.txt"},
+ },
+ },
+ {
+ name: "multi-source: file and directory moved to existing directory",
+ seeds: []seed{
+ {path: "report.txt", content: "r"},
+ {path: "docs", isDir: true},
+ {path: "docs/readme.md", content: "readme"},
+ {path: "dest", isDir: true},
+ },
+ req: moveRequest{Sources: []string{"report.txt", "docs"}, Destination: "dest"},
+ wantStatus: http.StatusOK,
+ wantPaths: []string{"dest", "dest/report.txt", "dest/docs", "dest/docs/readme.md"},
+ wantResponsePaths: []string{
+ "dest/report.txt",
+ "dest/docs",
+ "dest/docs/readme.md",
+ },
+ wantEvents: []resourceEvent{
+ {action: "updated", path: "dest/report.txt"},
+ {action: "updated", path: "dest/docs"},
+ {action: "updated", path: "dest/docs/readme.md"},
+ },
+ },
+ {
+ name: "multi-source: force overwrites existing file at target",
+ seeds: []seed{
+ {path: "a.txt", content: "new-a"},
+ {path: "b.txt", content: "new-b"},
+ // "archive" dir record is intentionally absent; ensureResourceDirs creates it.
+ {path: "archive/a.txt", content: "old-a"},
+ },
+ req: moveRequest{Sources: []string{"a.txt", "b.txt"}, Destination: "archive", Force: true},
+ wantStatus: http.StatusOK,
+ wantPaths: []string{"archive", "archive/a.txt", "archive/b.txt"},
+ // "archive" is Added by ensureResourceDirs; Updated contains moved files.
+ wantResponsePaths: []string{"archive", "archive/a.txt", "archive/b.txt"},
+ // Publish order: DeletedBefore → Added → Updated → DeletedAfter.
+ // archive/a.txt is in DeletedBefore (overwritten), archive dir is in Added.
+ wantEvents: []resourceEvent{
+ {action: "deleted", path: "archive/a.txt"},
+ {action: "added", path: "archive"},
+ {action: "updated", path: "archive/a.txt"},
+ {action: "updated", path: "archive/b.txt"},
+ },
+ wantDeletedBlobTexts: []string{"old-a"},
+ },
+ {
+ name: "multi-source: without force returns conflict when target exists",
+ seeds: []seed{
+ {path: "a.txt", content: "a"},
+ {path: "b.txt", content: "b"},
+ // "archive" dir record absent; "archive/a.txt" causes conflict.
+ {path: "archive/a.txt", content: "old"},
+ },
+ req: moveRequest{Sources: []string{"a.txt", "b.txt"}, Destination: "archive"},
+ wantStatus: http.StatusConflict,
+ // TX rolled back: "archive" dir record was never committed.
+ wantPaths: []string{"a.txt", "archive/a.txt", "b.txt"},
+ },
+ {
+ name: "multi-source: duplicate basenames returns conflict",
+ seeds: []seed{
+ {path: "dir1/x.txt", content: "x1"},
+ {path: "dir2/x.txt", content: "x2"},
+ },
+ // both sources have basename "x.txt" → conflict
+ req: moveRequest{Sources: []string{"dir1/x.txt", "dir2/x.txt"}, Destination: "archive"},
+ wantStatus: http.StatusConflict,
+ wantPaths: []string{"dir1/x.txt", "dir2/x.txt"},
+ },
+ {
+ name: "multi-source: one missing source returns not found",
+ seeds: []seed{
+ {path: "a.txt", content: "a"},
+ },
+ req: moveRequest{Sources: []string{"a.txt", "ghost.txt"}, Destination: "archive"},
+ wantStatus: http.StatusNotFound,
+ wantPaths: []string{"a.txt"},
+ },
+ {
+ name: "multi-source: empty sources returns bad request",
+ req: moveRequest{Sources: []string{}, Destination: "archive"},
+ wantStatus: http.StatusBadRequest,
+ },
+ {
+ name: "multi-source: blank entries only returns bad request",
+ req: moveRequest{Sources: []string{" ", ""}, Destination: "archive"},
+ wantStatus: http.StatusBadRequest,
+ },
+ {
+ name: "multi-source: destination is a file returns conflict",
+ seeds: []seed{
+ {path: "a.txt", content: "a"},
+ {path: "b.txt", content: "b"},
+ {path: "dest.file", content: "file"},
+ },
+ req: moveRequest{Sources: []string{"a.txt", "b.txt"}, Destination: "dest.file"},
+ wantStatus: http.StatusConflict,
+ wantPaths: []string{"a.txt", "b.txt", "dest.file"},
+ },
+ {
+ name: "multi-source: directory into itself returns bad request",
+ seeds: []seed{
+ {path: "docs", isDir: true},
+ {path: "a.txt", content: "a"},
+ },
+ // moving "docs" to "docs/sub" would move it into itself
+ req: moveRequest{Sources: []string{"docs", "a.txt"}, Destination: "docs/sub"},
+ wantStatus: http.StatusBadRequest,
+ wantPaths: []string{"a.txt", "docs"},
+ },
+ {
+ name: "multi-source: invalid source path returns bad request",
+ seeds: []seed{
+ {path: "a.txt", content: "a"},
+ },
+ req: moveRequest{Sources: []string{"../escape.txt", "a.txt"}, Destination: "archive"},
+ wantStatus: http.StatusBadRequest,
+ wantPaths: []string{"a.txt"},
+ },
}
for _, tt := range tests {
diff --git a/backend/pkg/server/services/roles.go b/backend/pkg/server/services/roles.go
index 9106d89d..9db66490 100644
--- a/backend/pkg/server/services/roles.go
+++ b/backend/pkg/server/services/roles.go
@@ -112,7 +112,7 @@ func (s *RoleService) GetRoles(c *gin.Context) {
// @Summary Retrieve role by id
// @Tags Roles
// @Produce json
-// @Param id path uint64 true "role id"
+// @Param roleID path uint64 true "role id"
// @Success 200 {object} response.successResp{data=models.RolePrivileges} "role received successful"
// @Failure 400 {object} response.errorResp "invalid query request data"
// @Failure 403 {object} response.errorResp "getting role not permitted"