Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix: prevent command and path injection (#21539)

buua436e4070b48baea
diff --git a/docker/.env b/docker/.env
index 30c7d535c2..b9e3d64fc0 100644
--- a/docker/.env
+++ b/docker/.env
@@ -404,7 +404,7 @@ RERANK_TOKEN_LIMIT_MODE=${RERANK_TOKEN_LIMIT_MODE:-truncate}
# Bound how long a provider call may wait for response headers before the attempt fails.
# A hung endpoint otherwise blocks every retry for the full client default (20m).
# Accepts Go durations such as `45s` or `5m`. Unset keeps the default.
-# LLM_HTTP_RESPONSE_HEADER_TIMEOUT=60s
+# LLM_HTTP_RESPONSE_HEADER_TIMEOUT=20m
# aliyun OSS configuration
# STORAGE_IMPL=OSS
diff --git a/internal/agent/sandbox/local_test.go b/internal/agent/sandbox/local_test.go
index 1aef96b776..5a0e998f09 100644
--- a/internal/agent/sandbox/local_test.go
+++ b/internal/agent/sandbox/local_test.go
@@ -464,13 +464,13 @@ func TestLocal_CollectArtifacts_AllowsCSVRoundTrip(t *testing.T) {
func TestShq(t *testing.T) {
t.Parallel()
- // shq replaces ' with \', wraps the result in single quotes.
- // "o'clock" -> 'o\'clock' (raw bytes: ', o, \, ', c, l, o, c, k, ').
+ // shq uses the POSIX single-quote escape sequence for embedded apostrophes.
+ // "o'clock" -> 'o'\''clock'.
cases := []struct {
in, want string
}{
{"foo", "'foo'"},
- {"o'clock", `'o\'clock'`},
+ {"o'clock", `'o'\''clock'`},
{"a b c", "'a b c'"},
{"", "''"},
}
diff --git a/internal/agent/sandbox/ssh.go b/internal/agent/sandbox/ssh.go
index 332c24f2bf..ec1caed114 100644
--- a/internal/agent/sandbox/ssh.go
+++ b/internal/agent/sandbox/ssh.go
@@ -31,7 +31,7 @@
// <script_path>`. The `__RAGFLOW_RESULT__:` marker extraction
// works identically across all providers.
//
-// File ops use SSH exec (cat heredoc / find / cat | base64) rather
+// File ops use SSH exec (cat / find / cat | base64) rather
// than the SFTP subsystem. This avoids the
// `github.com/pkg/sftp` dependency and keeps the import surface
// at just `golang.org/x/crypto/ssh` (already a transitive dep).
@@ -46,6 +46,7 @@ import (
"encoding/base64"
"errors"
"fmt"
+ "io"
"mime"
"net"
"os"
@@ -305,7 +306,7 @@ func (p *SSHProvider) ExecuteCode(
return nil, fmt.Errorf("ssh: unknown instance id %q", inst.InstanceID)
}
- // Wrap the code + write to remote via heredoc.
+ // Wrap the code and write it to the remote file through SSH stdin.
argsJSON, err := argsToJSON(args)
if err != nil {
return nil, err
@@ -536,11 +537,22 @@ func (p *SSHProvider) hostKeyCallback() (ssh.HostKeyCallback, error) {
// tricked into re-interpreting it (see remoteMkdirAll,
// remoteRemoveAll, remoteReadFile, remoteWriteFile, etc).
func (p *SSHProvider) runRemoteCommand(ctx context.Context, client *ssh.Client, command string, timeoutSec int) (string, string, int, error) {
+ return p.runRemoteCommandWithInput(ctx, client, command, timeoutSec, nil)
+}
+
+func (p *SSHProvider) runRemoteCommandWithInput(ctx context.Context, client *ssh.Client, command string, timeoutSec int, input io.Reader) (string, string, int, error) {
sess, err := client.NewSession()
if err != nil {
return "", "", -1, fmt.Errorf("ssh: open session: %w", err)
}
defer sess.Close()
+ var stdin io.WriteCloser
+ if input != nil {
+ stdin, err = sess.StdinPipe()
+ if err != nil {
+ return "", "", -1, fmt.Errorf("ssh: open stdin: %w", err)
+ }
+ }
stdoutBuf, stderrBuf := &strings.Builder{}, &strings.Builder{}
sess.Stdout = stdoutBuf
sess.Stderr = stderrBuf
@@ -556,29 +568,57 @@ func (p *SSHProvider) runRemoteCommand(ctx context.Context, client *ssh.Client,
runCtx, cancel = context.WithTimeout(ctx, time.Duration(timeoutSec)*time.Second)
}
defer cancel()
- done := make(chan error, 1)
- go func() { done <- sess.Wait() }()
-
- select {
- case err = <-done:
- case <-runCtx.Done():
- // Closing the SSH session interrupts Wait and asks the remote server to
- // terminate the associated command channel. Wait for the goroutine so
- // the output builders are no longer being written before returning.
- _ = sess.Signal(ssh.SIGKILL)
- _ = sess.Close()
- <-done
- return stdoutBuf.String(), stderrBuf.String(), -1, runCtx.Err()
+ waitDone := make(chan error, 1)
+ go func() { waitDone <- sess.Wait() }()
+ var writeDone chan error
+ if stdin != nil {
+ writeDone = make(chan error, 1)
+ go func() {
+ _, writeErr := io.Copy(stdin, input)
+ closeErr := stdin.Close()
+ if writeErr == nil {
+ writeErr = closeErr
+ }
+ writeDone <- writeErr
+ }()
+ }
+
+ var waitErr, writeErr error
+ waitComplete, writeComplete := false, stdin == nil
+ for !waitComplete || !writeComplete {
+ select {
+ case waitErr = <-waitDone:
+ waitComplete = true
+ waitDone = nil
+ case writeErr = <-writeDone:
+ writeComplete = true
+ writeDone = nil
+ case <-runCtx.Done():
+ // Closing the SSH session interrupts Wait and the stdin writer.
+ // Wait for both goroutines before reading their output buffers.
+ _ = sess.Signal(ssh.SIGKILL)
+ _ = sess.Close()
+ if !waitComplete {
+ <-waitDone
+ }
+ if !writeComplete {
+ <-writeDone
+ }
+ return stdoutBuf.String(), stderrBuf.String(), -1, runCtx.Err()
+ }
}
- if err != nil {
+ if waitErr != nil {
// ssh.ExitError carries the remote exit code; we surface
// it as a normal non-zero exit (the caller can branch on
// the ExitCode field).
var exitErr *ssh.ExitError
- if errors.As(err, &exitErr) {
+ if errors.As(waitErr, &exitErr) {
return stdoutBuf.String(), stderrBuf.String(), exitErr.ExitStatus(), nil
}
- return stdoutBuf.String(), stderrBuf.String(), -1, err
+ return stdoutBuf.String(), stderrBuf.String(), -1, waitErr
+ }
+ if writeErr != nil {
+ return stdoutBuf.String(), stderrBuf.String(), -1, fmt.Errorf("ssh: write stdin: %w", writeErr)
}
return stdoutBuf.String(), stderrBuf.String(), 0, nil
}
@@ -600,20 +640,11 @@ func (p *SSHProvider) remoteMkdirAll(ctx context.Context, client *ssh.Client, re
return nil
}
-// remoteWriteFile writes content to remotePath via a
-// `cat > file <<'__RAGFLOW_SSH_EOF__' ... EOF` heredoc. The
-// heredoc tag is unique enough to never collide with user
-// code (it includes the package name). For very large scripts
-// (>1 MiB) this is inefficient vs. SFTP; the threshold is
-// intentionally not implemented here — Python's paramiko
-// also writes via SFTP for the same reason.
+// remoteWriteFile writes content to remotePath through the SSH
+// session's stdin so file contents are never interpreted by the shell.
func (p *SSHProvider) remoteWriteFile(ctx context.Context, client *ssh.Client, remotePath, content string) error {
- const tag = "__RAGFLOW_SSH_EOF__"
- cmd := fmt.Sprintf(
- "cat > %s <<'%s'\n%s\n%s",
- shq(remotePath), tag, content, tag,
- )
- _, stderr, exitCode, err := p.runRemoteCommand(ctx, client, cmd, p.timeout)
+ cmd := fmt.Sprintf("cat > %s", shq(remotePath))
+ _, stderr, exitCode, err := p.runRemoteCommandWithInput(ctx, client, cmd, p.timeout, strings.NewReader(content))
if err != nil {
return err
}
@@ -738,13 +769,11 @@ func (p *SSHProvider) collectArtifacts(ctx context.Context, client *ssh.Client,
return out, nil
}
-// shq single-quotes a string for shell-safe inclusion. Matches
-// the Python `shlex.quote` behavior the SSH provider uses for
-// building `cd <work_dir> && <bin> <script>` commands. The
-// escape sequence for an embedded single quote is `\'` (a
-// backslash followed by a single quote).
+// shq single-quotes a string for POSIX shell inclusion. Embedded
+// single quotes are represented by ending the quoted string,
+// emitting a quoted single quote, then starting a new quoted string.
func shq(s string) string {
- return "'" + strings.ReplaceAll(s, "'", `\'`) + "'"
+ return "'" + strings.ReplaceAll(s, "'", "'\\''") + "'"
}
// minTimeout returns the smaller of a and b, with a floor of 1.
diff --git a/internal/agent/sandbox/ssh_test.go b/internal/agent/sandbox/ssh_test.go
index 697f2d8bc7..bc6c214a11 100644
--- a/internal/agent/sandbox/ssh_test.go
+++ b/internal/agent/sandbox/ssh_test.go
@@ -22,6 +22,8 @@ import (
"crypto/rand"
"encoding/pem"
"fmt"
+ "io"
+ "os/exec"
"path/filepath"
"golang.org/x/crypto/ssh"
@@ -318,6 +320,138 @@ func TestShq_Extra(t *testing.T) {
}
}
+func TestShqDoesNotInterpretSingleQuote(t *testing.T) {
+ shell, err := exec.LookPath("sh")
+ if err != nil {
+ t.Skip("POSIX shell is not available")
+ }
+ marker := filepath.Join(t.TempDir(), "injected")
+ argument := "safe'; touch " + marker + "; #"
+ command := "printf %s " + shq(argument)
+ output, err := exec.Command(shell, "-c", command).CombinedOutput()
+ if err != nil {
+ t.Fatalf("run quoted shell argument: %v; output: %s", err, output)
+ }
+ if string(output) != argument {
+ t.Fatalf("shell output = %q, want %q", output, argument)
+ }
+ if _, err := os.Stat(marker); !os.IsNotExist(err) {
+ t.Fatalf("quoted argument executed injected command; marker stat error = %v", err)
+ }
+}
+
+func TestSSHRemoteWriteFileStreamsContentAsStdin(t *testing.T) {
+ commands := make(chan string, 1)
+ contents := make(chan string, 1)
+ client := newSSHExecTestClient(t, func(command string, stdin io.Reader) error {
+ commands <- command
+ content, err := io.ReadAll(stdin)
+ if err != nil {
+ return err
+ }
+ contents <- string(content)
+ return nil
+ })
+ provider := &SSHProvider{timeout: 5}
+ remotePath := filepath.Join(t.TempDir(), "uploaded.py")
+ content := "print('safe')\n__RAGFLOW_SSH_EOF__\nprintf injected\n"
+ if err := provider.remoteWriteFile(t.Context(), client, remotePath, content); err != nil {
+ t.Fatalf("remoteWriteFile: %v", err)
+ }
+ if got, want := <-commands, "cat > "+shq(remotePath); got != want {
+ t.Fatalf("remote command = %q, want %q", got, want)
+ }
+ if got := <-contents; got != content {
+ t.Fatalf("stdin content = %q, want %q", got, content)
+ }
+}
+
+func newSSHExecTestClient(t *testing.T, execute func(string, io.Reader) error) *ssh.Client {
+ t.Helper()
+ _, hostKey, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatalf("generate SSH host key: %v", err)
+ }
+ signer, err := ssh.NewSignerFromKey(hostKey)
+ if err != nil {
+ t.Fatalf("create SSH host signer: %v", err)
+ }
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("listen for SSH test server: %v", err)
+ }
+ serverConfig := &ssh.ServerConfig{PasswordCallback: func(ssh.ConnMetadata, []byte) (*ssh.Permissions, error) {
+ return nil, nil
+ }}
+ serverConfig.AddHostKey(signer)
+ go func() {
+ conn, err := listener.Accept()
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+ server, channels, requests, err := ssh.NewServerConn(conn, serverConfig)
+ if err != nil {
+ return
+ }
+ defer server.Close()
+ go ssh.DiscardRequests(requests)
+ for newChannel := range channels {
+ if newChannel.ChannelType() != "session" {
+ _ = newChannel.Reject(ssh.UnknownChannelType, "unsupported channel")
+ continue
+ }
+ channel, channelRequests, err := newChannel.Accept()
+ if err != nil {
+ continue
+ }
+ go func() {
+ defer channel.Close()
+ for request := range channelRequests {
+ if request.Type != "exec" {
+ _ = request.Reply(false, nil)
+ continue
+ }
+ var payload struct{ Command string }
+ if err := ssh.Unmarshal(request.Payload, &payload); err != nil {
+ _ = request.Reply(false, nil)
+ return
+ }
+ _ = request.Reply(true, nil)
+ status := uint32(0)
+ if err := execute(payload.Command, channel); err != nil {
+ status = 1
+ }
+ _, _ = channel.SendRequest("exit-status", false, ssh.Marshal(struct{ ExitStatus uint32 }{status}))
+ return
+ }
+ }()
+ }
+ }()
+
+ conn, err := net.Dial("tcp", listener.Addr().String())
+ if err != nil {
+ listener.Close()
+ t.Fatalf("connect to SSH test server: %v", err)
+ }
+ clientConn, channels, requests, err := ssh.NewClientConn(conn, listener.Addr().String(), &ssh.ClientConfig{
+ User: "test",
+ Auth: []ssh.AuthMethod{ssh.Password("test")},
+ HostKeyCallback: ssh.InsecureIgnoreHostKey(),
+ })
+ if err != nil {
+ conn.Close()
+ listener.Close()
+ t.Fatalf("SSH client handshake: %v", err)
+ }
+ client := ssh.NewClient(clientConn, channels, requests)
+ t.Cleanup(func() {
+ _ = client.Close()
+ _ = listener.Close()
+ })
+ return client
+}
+
func TestMinTimeout(t *testing.T) {
if got := minTimeout(10, 5); got != 5 {
t.Errorf("minTimeout(10, 5) = %d, want 5", got)
diff --git a/internal/channels/whatsapp-gateway/index.js b/internal/channels/whatsapp-gateway/index.js
index b87e647e6b..195e1dfc3f 100644
--- a/internal/channels/whatsapp-gateway/index.js
+++ b/internal/channels/whatsapp-gateway/index.js
@@ -3,6 +3,7 @@ import crypto from 'node:crypto';
import os from 'node:os';
import path from 'node:path';
import { mkdir } from 'node:fs/promises';
+import { decodeSessionKey, resolveSessionDir } from './session-path.js';
import makeWASocket, {
Browsers,
@@ -108,7 +109,7 @@ function isAuthorized(req) {
class WhatsAppSession {
constructor(sessionKey) {
this.sessionKey = sessionKey;
- this.sessionDir = path.join(DATA_DIR, sessionKey);
+ this.sessionDir = resolveSessionDir(DATA_DIR, sessionKey);
this.status = 'stopped';
this.lastError = '';
this.qrDataUrl = '';
@@ -434,7 +435,10 @@ const server = http.createServer(async (req, res) => {
return sendError(res, 401, 'unauthorized');
}
- const sessionKey = decodeURIComponent(parts[1]);
+ const sessionKey = decodeSessionKey(parts[1]);
+ if (sessionKey === null) {
+ return sendError(res, 400, 'invalid session key');
+ }
if (req.method === 'POST' && parts.length === 3 && parts[2] === 'start') {
const session = getSession(sessionKey);
@@ -492,7 +496,11 @@ server.on('upgrade', (req, socket) => {
socket.destroy();
return;
}
- const sessionKey = decodeURIComponent(parts[1]);
+ const sessionKey = decodeSessionKey(parts[1]);
+ if (sessionKey === null) {
+ socket.destroy();
+ return;
+ }
const key = req.headers['sec-websocket-key'];
if (!key) {
socket.destroy();
diff --git a/internal/channels/whatsapp-gateway/package.json b/internal/channels/whatsapp-gateway/package.json
index e14da7e753..a13772058f 100644
--- a/internal/channels/whatsapp-gateway/package.json
+++ b/internal/channels/whatsapp-gateway/package.json
@@ -3,7 +3,8 @@
"private": true,
"type": "module",
"scripts": {
- "start": "node index.js"
+ "start": "node index.js",
+ "test": "node --test"
},
"dependencies": {
"baileys": "7.0.0-rc13",
diff --git a/internal/channels/whatsapp-gateway/session-path.js b/internal/channels/whatsapp-gateway/session-path.js
new file mode 100644
index 0000000000..e9d8f87c33
--- /dev/null
+++ b/internal/channels/whatsapp-gateway/session-path.js
@@ -0,0 +1,39 @@
+import path from 'node:path';
+
+function isSafeSessionKey(sessionKey) {
+ return (
+ typeof sessionKey === 'string' &&
+ sessionKey.length > 0 &&
+ sessionKey !== '.' &&
+ sessionKey !== '..' &&
+ !sessionKey.includes('/') &&
+ !sessionKey.includes('\\') &&
+ !sessionKey.includes('\0')
+ );
+}
+
+export function decodeSessionKey(encodedKey) {
+ let sessionKey;
+ try {
+ sessionKey = decodeURIComponent(encodedKey);
+ } catch {
+ return null;
+ }
+
+ sessionKey = sessionKey.trim();
+ return isSafeSessionKey(sessionKey) ? sessionKey : null;
+}
+
+export function resolveSessionDir(dataDir, sessionKey) {
+ if (!isSafeSessionKey(sessionKey)) {
+ throw new TypeError('invalid session key');
+ }
+
+ const root = path.resolve(dataDir);
+ const sessionDir = path.resolve(root, sessionKey);
+ const relative = path.relative(root, sessionDir);
+ if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
+ throw new TypeError('session directory escapes the data directory');
+ }
+ return sessionDir;
+}
diff --git a/internal/channels/whatsapp-gateway/session-path.test.js b/internal/channels/whatsapp-gateway/session-path.test.js
new file mode 100644
index 0000000000..9b01ea21a2
--- /dev/null
+++ b/internal/channels/whatsapp-gateway/session-path.test.js
@@ -0,0 +1,26 @@
+import assert from 'node:assert/strict';
+import path from 'node:path';
+import test from 'node:test';
+
+import { decodeSessionKey, resolveSessionDir } from './session-path.js';
+
+test('decodes ordinary session keys', () => {
+ assert.equal(decodeSessionKey('tenant-123_user-456'), 'tenant-123_user-456');
+ assert.equal(decodeSessionKey('tenant%2D123'), 'tenant-123');
+});
+
+test('rejects encoded path separators and malformed escapes', () => {
+ const requestURL = new URL('/whatsapp/..%2f..%2foutside/start', 'http://localhost');
+ const segment = requestURL.pathname.split('/').filter(Boolean)[1];
+ assert.equal(decodeSessionKey(segment), null);
+ assert.equal(decodeSessionKey('%5c..%5coutside'), null);
+ assert.equal(decodeSessionKey('%E0%A4%A'), null);
+});
+
+test('keeps session directories beneath the configured data directory', () => {
+ const dataDir = path.resolve('tmp', 'whatsapp-data', 'sessions');
+ const sessionDir = resolveSessionDir(dataDir, 'account-123');
+ assert.equal(sessionDir, path.join(dataDir, 'account-123'));
+ assert.throws(() => resolveSessionDir(dataDir, '../../outside'), /invalid session key/);
+ assert.throws(() => resolveSessionDir(dataDir, '..'), /invalid session key/);
+});
diff --git a/internal/cli/filesystem/skill_install.go b/internal/cli/filesystem/skill_install.go
index dbc50d2c7f..ef9c31333a 100644
--- a/internal/cli/filesystem/skill_install.go
+++ b/internal/cli/filesystem/skill_install.go
@@ -179,6 +179,9 @@ func (c *SkillInstallCommand) Execute(args []string) error {
if parsedArgs.SkillName != "" {
bundle.Name = parsedArgs.SkillName
}
+ if !isValidSkillName(bundle.Name) {
+ return fmt.Errorf("invalid skill name %q", bundle.Name)
+ }
// 3. Check if skill already exists
exists, err := c.skillExists(ctx, parsedArgs.SpaceID, bundle.Name)
@@ -206,6 +209,14 @@ func (c *SkillInstallCommand) Execute(args []string) error {
fmt.Printf("✓ Security check passed: %s\n\n", reason)
}
+ // Stage and validate every bundle file before --force can remove the
+ // existing skill.
+ tempDir, skillDir, err := stageSkillBundle(bundle)
+ if err != nil {
+ return fmt.Errorf("failed to stage skill: %w", err)
+ }
+ defer os.RemoveAll(tempDir)
+
// 5. Force mode: delete existing skill first
if parsedArgs.Force && exists {
fmt.Printf("Force mode: removing existing skill '%s'...\n", bundle.Name)
@@ -217,7 +228,7 @@ func (c *SkillInstallCommand) Execute(args []string) error {
// 6. Install skill
fmt.Printf("Installing skill '%s' to space '%s'...\n", bundle.Name, parsedArgs.SpaceID)
- if err := c.installSkill(ctx, parsedArgs.SpaceID, bundle, parsedArgs.Force); err != nil {
+ if err := c.installStagedSkill(ctx, parsedArgs.SpaceID, bundle, skillDir, parsedArgs.Force); err != nil {
return fmt.Errorf("failed to install skill: %w", err)
}
@@ -264,38 +275,90 @@ func (c *SkillInstallCommand) uninstallSkill(ctx stdctx.Context, spaceID, skillN
return nil
}
-// installSkill installs a skill bundle using existing SkillUploader
+// installSkill installs a skill bundle using existing SkillUploader.
func (c *SkillInstallCommand) installSkill(ctx stdctx.Context, spaceID string, bundle *source.SkillBundle, force bool) error {
- // Create a temporary directory to hold the skill files
- tempDir, err := os.MkdirTemp("", "skill-install-*")
+ tempDir, skillDir, err := stageSkillBundle(bundle)
if err != nil {
- return fmt.Errorf("failed to create temp directory: %w", err)
+ return err
}
defer os.RemoveAll(tempDir)
- // Write files to temp directory
- skillDir := filepath.Join(tempDir, bundle.Name)
- if err := os.MkdirAll(skillDir, 0755); err != nil {
- return fmt.Errorf("failed to create skill directory: %w", err)
+ return c.installStagedSkill(ctx, spaceID, bundle, skillDir, force)
+}
+
+func stageSkillBundle(bundle *source.SkillBundle) (string, string, error) {
+ if bundle == nil {
+ return "", "", fmt.Errorf("skill bundle is required")
+ }
+ if !isValidSkillName(bundle.Name) {
+ return "", "", fmt.Errorf("invalid skill name %q", bundle.Name)
+ }
+
+ tempDir, err := os.MkdirTemp("", "skill-install-*")
+ if err != nil {
+ return "", "", fmt.Errorf("failed to create temp directory: %w", err)
+ }
+ fail := func(err error) (string, string, error) {
+ _ = os.RemoveAll(tempDir)
+ return "", "", err
}
+ skillDir := filepath.Join(tempDir, bundle.Name)
+ type stagedFile struct {
+ path string
+ content []byte
+ }
+ stagedFiles := make([]stagedFile, 0, len(bundle.Files))
for relPath, content := range bundle.Files {
- filePath := filepath.Join(skillDir, relPath)
- dir := filepath.Dir(filePath)
- if err := os.MkdirAll(dir, 0755); err != nil {
- return fmt.Errorf("failed to create directory %s: %w", dir, err)
+ filePath, err := resolveSkillFilePath(skillDir, relPath)
+ if err != nil {
+ return fail(err)
+ }
+ stagedFiles = append(stagedFiles, stagedFile{path: filePath, content: content})
+ }
+
+ if err := os.MkdirAll(skillDir, 0755); err != nil {
+ return fail(fmt.Errorf("failed to create skill directory: %w", err))
+ }
+ for _, file := range stagedFiles {
+ if err := os.MkdirAll(filepath.Dir(file.path), 0755); err != nil {
+ return fail(fmt.Errorf("failed to create directory for skill file: %w", err))
}
- if err := os.WriteFile(filePath, content, 0644); err != nil {
- return fmt.Errorf("failed to write file %s: %w", relPath, err)
+ if err := os.WriteFile(file.path, file.content, 0644); err != nil {
+ return fail(fmt.Errorf("failed to write skill file: %w", err))
}
}
+ if err := validateStagedSkill(skillDir, bundle); err != nil {
+ return fail(err)
+ }
+
+ return tempDir, skillDir, nil
+}
- // Use existing SkillUploader to upload the skill
+func validateStagedSkill(skillDir string, bundle *source.SkillBundle) error {
+ version := ""
+ if bundle.Metadata != nil {
+ version = bundle.Metadata.Version
+ }
+ result, _, err := ValidateSkillDirectory(skillDir, version, bundle.Name)
+ if err != nil {
+ return fmt.Errorf("failed to validate staged skill: %w", err)
+ }
+ if !result.Valid {
+ return fmt.Errorf("failed to validate staged skill: %s", GetValidationErrorMessage(result))
+ }
+ return nil
+}
+
+func (c *SkillInstallCommand) installStagedSkill(ctx stdctx.Context, spaceID string, bundle *source.SkillBundle, skillDir string, force bool) error {
uploader := NewSkillUploader(c.client, c.fileProvider)
uploader.SetSkillProvider(c.skillProvider)
uploader.SetForce(force)
- version := bundle.Metadata.Version
+ version := ""
+ if bundle.Metadata != nil {
+ version = bundle.Metadata.Version
+ }
if version == "" {
version = "1.0.0"
}
@@ -303,6 +366,29 @@ func (c *SkillInstallCommand) installSkill(ctx stdctx.Context, spaceID string, b
return uploader.UploadSkill(ctx, skillDir, version, fmt.Sprintf("skills/%s", spaceID), bundle.Name)
}
+func resolveSkillFilePath(root, relPath string) (string, error) {
+ if relPath == "" {
+ return "", fmt.Errorf("invalid skill file path %q", relPath)
+ }
+ // Bundle paths may use Windows separators when fetched from a local
+ // source. Normalize them before the local-path and containment checks.
+ relPath = strings.ReplaceAll(relPath, "\\", "/")
+ localPath := filepath.Clean(filepath.FromSlash(relPath))
+ if localPath == "." || !filepath.IsLocal(localPath) {
+ return "", fmt.Errorf("invalid skill file path %q", relPath)
+ }
+ root, err := filepath.Abs(root)
+ if err != nil {
+ return "", fmt.Errorf("resolve skill directory: %w", err)
+ }
+ filePath := filepath.Join(root, localPath)
+ relativePath, err := filepath.Rel(root, filePath)
+ if err != nil || !filepath.IsLocal(relativePath) {
+ return "", fmt.Errorf("skill file path %q escapes the skill directory", relPath)
+ }
+ return filePath, nil
+}
+
// skillExists checks if a skill already exists
func (c *SkillInstallCommand) skillExists(ctx stdctx.Context, spaceID, skillName string) (bool, error) {
folderPath := fmt.Sprintf("skills/%s/%s", spaceID, skillName)
diff --git a/internal/cli/filesystem/skill_install_test.go b/internal/cli/filesystem/skill_install_test.go
new file mode 100644
index 0000000000..ec376461a2
--- /dev/null
+++ b/internal/cli/filesystem/skill_install_test.go
@@ -0,0 +1,104 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package filesystem
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "ragflow/internal/cli/filesystem/skill_hub/source"
+)
+
+func TestInstallSkillRejectsUnsafeNameBeforeCreatingFiles(t *testing.T) {
+ tmpDir, err := os.MkdirTemp("", "skill-install-test-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(tmpDir)
+ t.Setenv("TMPDIR", tmpDir)
+
+ command := &SkillInstallCommand{}
+ bundle := &source.SkillBundle{Name: "../outside", Files: map[string][]byte{"SKILL.md": []byte("content")}}
+ if err := command.installSkill(context.Background(), "default", bundle, false); err == nil {
+ t.Fatal("installSkill accepted a path-traversal skill name")
+ }
+ entries, err := os.ReadDir(tmpDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 0 {
+ t.Fatalf("installSkill created files before rejecting the name: %v", entries)
+ }
+}
+
+func TestStageSkillBundleRejectsInvalidMetadataBeforeReturning(t *testing.T) {
+ tmpDir := t.TempDir()
+ t.Setenv("TMPDIR", tmpDir)
+
+ bundle := &source.SkillBundle{
+ Name: "sample-skill",
+ Metadata: &source.SkillMetadata{Version: "banana"},
+ Files: map[string][]byte{
+ "SKILL.md": []byte("---\nname: sample-skill\ndescription: test skill\n---\ncontent\n"),
+ },
+ }
+ if _, _, err := stageSkillBundle(bundle); err == nil {
+ t.Fatal("stageSkillBundle accepted an invalid skill version")
+ }
+ entries, err := os.ReadDir(tmpDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 0 {
+ t.Fatalf("invalid skill left staged files behind: %v", entries)
+ }
+}
+
+func TestResolveSkillFilePathRejectsTraversal(t *testing.T) {
+ root := filepath.Join(t.TempDir(), "skill")
+ for _, relPath := range []string{"../outside", "../../tmp/outside", "/tmp/outside", `..\outside`, ""} {
+ t.Run(relPath, func(t *testing.T) {
+ if _, err := resolveSkillFilePath(root, relPath); err == nil {
+ t.Fatalf("resolveSkillFilePath(%q) succeeded", relPath)
+ }
+ })
+ }
+}
+
+func TestResolveSkillFilePathAllowsNestedFiles(t *testing.T) {
+ root := filepath.Join(t.TempDir(), "skill")
+ got, err := resolveSkillFilePath(root, "references/guide.md")
+ if err != nil {
+ t.Fatalf("resolveSkillFilePath: %v", err)
+ }
+ if want := filepath.Join(root, "references", "guide.md"); got != want {
+ t.Fatalf("resolveSkillFilePath = %q, want %q", got, want)
+ }
+}
+
+func TestResolveSkillFilePathNormalizesWindowsSeparators(t *testing.T) {
+ root := filepath.Join(t.TempDir(), "skill")
+ got, err := resolveSkillFilePath(root, `references\guide.md`)
+ if err != nil {
+ t.Fatalf("resolveSkillFilePath: %v", err)
+ }
+ if want := filepath.Join(root, "references", "guide.md"); got != want {
+ t.Fatalf("resolveSkillFilePath = %q, want %q", got, want)
+ }
+}