feat(cli): scaffold weknora CLI module foundation (PR-1)
Empty cli/ Go module with Factory + Options skeleton that all v0.x commands plug into. Foundation packages (10 internal/): - cmdutil: Factory(3 closure: Config/Client/Prompter) + Options + Errors with namespaced ErrorCode + typed predicates (IsAuthError / IsNotFound / IsTransient / IsAuthExpired) + Exporter + AddJSONFlags + ExitCode/PrintError - iostreams: package singleton with TTY detection; ColorEnabled honors NO_COLOR / TERM=dumb on demand - agent: mode + detect + annotations (Stripe pkg/useragent pattern; CLAUDECODE / CURSOR_AGENT / CODEX_* / AIDER_* / CONTINUE_* / OPENCODE_* / GEMINICODER env detection) - build: ldflags-injected version/commit/date - safepaths: separator-aware path-traversal protection - config: yaml.v3 schema + atomic save 0600 (XDG-style) - format: success/failure envelope (code/hint/request_id/risk/retryable/ console_url) with typed RiskLevel - prompt: Prompter interface + AgentPrompter (rejects in agent mode) - secrets: file 0600 store with weknora:<context>:<key> namespace - testutil: XDGTempDir(t) test helper Smoke command: weknora version (-/--json). Build/test/vet matrix in .github/workflows/cli.yml across linux x macos x windows x Go 1.24. Factory.Client returns CodeLocalUnimplemented until PR-3 wires the SDK adapter; PR-1 commands (version) don't need it.
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
// Package safepaths provides path-traversal protection for file inputs to
|
||||
// commands such as `weknora doc upload`.
|
||||
//
|
||||
// Two primary checks:
|
||||
// - Validate(path): reject empty, ".", "..", or paths containing embedded ".." segments.
|
||||
// - WithinRoot(path, root): both are made absolute and compared with a
|
||||
// separator-aware prefix check, so a directory named "..foo" cannot
|
||||
// masquerade as escaping ".." (the lexical strings.HasPrefix(rel, "..")
|
||||
// trap).
|
||||
//
|
||||
// Symlinks are NOT resolved; callers needing realpath semantics must
|
||||
// pre-resolve. Modeled on the same pattern as `internal/utils/security.go`
|
||||
// SafePathUnderBase in the server module.
|
||||
package safepaths
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ErrPathEscapes signals that the given path resolves outside the allowed root.
|
||||
var ErrPathEscapes = errors.New("path escapes allowed root")
|
||||
|
||||
// ErrEmptyPath signals an empty input.
|
||||
var ErrEmptyPath = errors.New("path is empty")
|
||||
|
||||
// ErrSuspiciousPath signals a "."/".." or embedded ".." traversal.
|
||||
var ErrSuspiciousPath = errors.New("path contains suspicious traversal segment")
|
||||
|
||||
// Validate cleans path and rejects empty inputs, "." / "..", or any path that
|
||||
// contains an embedded ".." segment after cleaning. It does not resolve symlinks.
|
||||
func Validate(path string) (string, error) {
|
||||
if path == "" {
|
||||
return "", ErrEmptyPath
|
||||
}
|
||||
cleaned := filepath.Clean(path)
|
||||
if cleaned == "" || cleaned == "." || cleaned == ".." {
|
||||
return "", fmt.Errorf("%w: %q", ErrSuspiciousPath, path)
|
||||
}
|
||||
for _, seg := range strings.Split(cleaned, string(filepath.Separator)) {
|
||||
if seg == ".." {
|
||||
return "", fmt.Errorf("%w: %q", ErrSuspiciousPath, path)
|
||||
}
|
||||
}
|
||||
return cleaned, nil
|
||||
}
|
||||
|
||||
// WithinRoot reports whether path lies inside root after both are made
|
||||
// absolute. Comparison is separator-aware: a path "/srv/data..foo" is NOT
|
||||
// treated as escaping "/srv/data" just because "..foo" textually starts
|
||||
// with "..".
|
||||
func WithinRoot(path, root string) error {
|
||||
absPath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve path: %w", err)
|
||||
}
|
||||
absRoot, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve root: %w", err)
|
||||
}
|
||||
// Equal paths count as "within"; otherwise require a separator-bounded prefix.
|
||||
if absPath == absRoot {
|
||||
return nil
|
||||
}
|
||||
withSep := absRoot + string(filepath.Separator)
|
||||
if !strings.HasPrefix(absPath, withSep) {
|
||||
return fmt.Errorf("%w: %s not under %s", ErrPathEscapes, absPath, absRoot)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package safepaths
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
t.Run("rejects empty", func(t *testing.T) {
|
||||
_, err := Validate("")
|
||||
require.ErrorIs(t, err, ErrEmptyPath)
|
||||
})
|
||||
t.Run("rejects bare dot", func(t *testing.T) {
|
||||
_, err := Validate(".")
|
||||
require.ErrorIs(t, err, ErrSuspiciousPath)
|
||||
})
|
||||
t.Run("rejects bare double-dot", func(t *testing.T) {
|
||||
_, err := Validate("..")
|
||||
require.ErrorIs(t, err, ErrSuspiciousPath)
|
||||
})
|
||||
t.Run("rejects relative path that ascends past start", func(t *testing.T) {
|
||||
// "../foo" preserves the ".." after Clean.
|
||||
_, err := Validate("../foo")
|
||||
require.ErrorIs(t, err, ErrSuspiciousPath)
|
||||
})
|
||||
t.Run("cleans benign relative", func(t *testing.T) {
|
||||
// "a/b/../c" cleans to "a/c" — fine.
|
||||
got, err := Validate("a/b/../c")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, filepath.Clean("a/c"), got)
|
||||
})
|
||||
t.Run("cleans cancelling relative", func(t *testing.T) {
|
||||
// "a/../b" cleans to "b" — also fine; the ascent fully resolves.
|
||||
got, err := Validate("a/../b")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "b", got)
|
||||
})
|
||||
}
|
||||
|
||||
func TestWithinRoot(t *testing.T) {
|
||||
t.Run("inside root", func(t *testing.T) {
|
||||
err := WithinRoot("/srv/data/file.md", "/srv/data")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
t.Run("equal to root", func(t *testing.T) {
|
||||
err := WithinRoot("/srv/data", "/srv/data")
|
||||
require.NoError(t, err)
|
||||
})
|
||||
t.Run("escapes via parent", func(t *testing.T) {
|
||||
err := WithinRoot("/srv/data/../../etc/passwd", "/srv/data")
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, ErrPathEscapes))
|
||||
})
|
||||
t.Run("sibling outside", func(t *testing.T) {
|
||||
err := WithinRoot("/srv/other", "/srv/data")
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, ErrPathEscapes))
|
||||
})
|
||||
t.Run("dotdot-prefix sibling is not within", func(t *testing.T) {
|
||||
// /srv/data..foo lexically starts with "/srv/data" but is a different dir.
|
||||
// Without separator-awareness this would be a false negative.
|
||||
err := WithinRoot("/srv/data..foo/x", "/srv/data")
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, ErrPathEscapes))
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user