Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,7 @@ func TestApplyNeedAuthorizationHint_ShortcutUsesDeclaredScopesWhenNoUAT(t *testi
t.Errorf("Subtype = %q, want %q", problem.Subtype, errs.SubtypeUnknown)
}

if !strings.Contains(problem.Hint, `auth login --scope "docx:document:create" --no-wait --json`) {
if !strings.Contains(problem.Hint, `auth login --scope "docx:document:create docs:document.media:upload docx:document:write_only docx:document:readonly" --no-wait --json`) {
t.Errorf("expected shortcut scoped recovery, got %q", problem.Hint)
}
}
Expand Down Expand Up @@ -699,7 +699,12 @@ func TestApplyNeedAuthorizationHint_AppendsExistingHint(t *testing.T) {
t.Errorf("rendered error lost need-authorization cause %v: %v", authErr.Cause, rendered)
}

want := "existing hint\n" + recovery.UserAuthorization("docx:document:create").String()
want := "existing hint\n" + recovery.UserAuthorization(
"docx:document:create",
"docs:document.media:upload",
"docx:document:write_only",
"docx:document:readonly",
).String()
if problem.Hint != want {
t.Errorf("expected appended hint %q, got %q", want, problem.Hint)
}
Expand Down
9 changes: 9 additions & 0 deletions extension/fileio/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ type FileIO interface {
Save(path string, opts SaveOptions, body io.Reader) (SaveResult, error)
}

// WorkspaceFileIO is an optional extension for commands that own temporary
// workspace entries. RemoveWorkspaceEntry must remove exactly one file or one
// empty directory, never recursively, and must apply the same path validation
// and storage backend as the embedded FileIO methods.
type WorkspaceFileIO interface {
FileIO
RemoveWorkspaceEntry(path string) error
}

// FileInfo is a minimal subset of os.FileInfo covering actual CLI usage.
// os.FileInfo satisfies this interface.
type FileInfo interface {
Expand Down
5 changes: 3 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ require (
github.com/stretchr/testify v1.11.1
github.com/tidwall/gjson v1.18.0
github.com/zalando/go-keyring v0.2.8
golang.org/x/image v0.30.0
golang.org/x/net v0.33.0
golang.org/x/sync v0.15.0
golang.org/x/sync v0.16.0
golang.org/x/sys v0.33.0
golang.org/x/term v0.27.0
golang.org/x/text v0.23.0
golang.org/x/text v0.28.0
gopkg.in/yaml.v3 v3.0.1
)

Expand Down
10 changes: 6 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/image v0.30.0 h1:jD5RhkmVAnjqaCUXfbGBrn3lpxbknfN9w2UhHHU+5B4=
golang.org/x/image v0.30.0/go.mod h1:SAEUTxCCMWSrJcCy/4HwavEsfZZJlYxeHLc6tTiAe/c=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
Expand All @@ -150,8 +152,8 @@ golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand All @@ -163,8 +165,8 @@ golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
Expand Down
12 changes: 12 additions & 0 deletions internal/vfs/localfileio/localfileio.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ func init() {
// and atomic writes are handled internally.
type LocalFileIO struct{}

var _ fileio.WorkspaceFileIO = (*LocalFileIO)(nil)

// Open opens a local file for reading after validating the path.
func (l *LocalFileIO) Open(name string) (fileio.File, error) {
safePath, err := SafeInputPath(name)
Expand Down Expand Up @@ -79,3 +81,13 @@ func (l *LocalFileIO) Save(path string, _ fileio.SaveOptions, body io.Reader) (f
}
return &saveResult{size: n}, nil
}

// RemoveWorkspaceEntry removes one workspace file or one empty workspace
// directory after applying the same output-path validation as Save.
func (l *LocalFileIO) RemoveWorkspaceEntry(path string) error {
safePath, err := SafeOutputPath(path)
if err != nil {
return &fileio.PathValidationError{Err: err}
}
return vfs.Remove(safePath)
}
39 changes: 39 additions & 0 deletions internal/vfs/localfileio/localfileio_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package localfileio

import (
"errors"
"io"
"os"
"path/filepath"
Expand Down Expand Up @@ -212,6 +213,44 @@ func TestLocalFileIO_Save_RejectsAbsolutePath(t *testing.T) {
}
}

func TestLocalFileIO_RemoveWorkspaceEntry_IsValidatedAndNonRecursive(t *testing.T) {
dir := t.TempDir()
testChdir(t, dir)

fio := &LocalFileIO{}
workspace := "draft_workspace"
decisionPath := filepath.Join(workspace, ".presentation-decision.json")
keepPath := filepath.Join(workspace, "keep.txt")
if _, err := fio.Save(decisionPath, fileio.SaveOptions{}, strings.NewReader("{}")); err != nil {
t.Fatalf("Save decision: %v", err)
}
if _, err := fio.Save(keepPath, fileio.SaveOptions{}, strings.NewReader("keep")); err != nil {
t.Fatalf("Save retained entry: %v", err)
}

if err := fio.RemoveWorkspaceEntry(decisionPath); err != nil {
t.Fatalf("RemoveWorkspaceEntry file: %v", err)
}
if _, err := os.Stat(decisionPath); !os.IsNotExist(err) {
t.Fatalf("removed decision still exists or stat failed unexpectedly: %v", err)
}
if err := fio.RemoveWorkspaceEntry(workspace); err == nil {
t.Fatal("RemoveWorkspaceEntry recursively removed a non-empty directory")
}
if _, err := os.Stat(keepPath); err != nil {
t.Fatalf("non-recursive removal deleted retained entry: %v", err)
}
if err := fio.RemoveWorkspaceEntry(keepPath); err != nil {
t.Fatalf("RemoveWorkspaceEntry retained file: %v", err)
}
if err := fio.RemoveWorkspaceEntry(workspace); err != nil {
t.Fatalf("RemoveWorkspaceEntry empty directory: %v", err)
}
if err := fio.RemoveWorkspaceEntry("../outside"); !errors.Is(err, fileio.ErrPathValidation) {
t.Fatalf("traversal error = %v, want fileio.ErrPathValidation", err)
}
}

// ── ResolvePath ──

func TestLocalFileIO_ResolvePath_ReturnsAbsolute(t *testing.T) {
Expand Down
7 changes: 7 additions & 0 deletions shortcuts/common/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,13 @@ func (ctx *RuntimeContext) handleEmitterError(err error) {
ctx.outputErrOnce.Do(func() { ctx.outputErr = err })
}

// OutputError returns the first deferred output failure captured by Out,
// OutRaw, or OutFormat. Commands that create local artifacts can use it to
// roll those artifacts back before returning the final command error.
func (ctx *RuntimeContext) OutputError() error {
return ctx.outputErr
}

func wrapLegacyPrettyRenderer(prettyFn func(w io.Writer)) output.PrettyRenderer {
if prettyFn == nil {
return nil
Expand Down
1 change: 1 addition & 0 deletions shortcuts/doc/doc_media_ext.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ var docMediaMimeToExt = map[string]string{
"image/jpeg": ".jpg",
"image/png": ".png",
"image/svg+xml": ".svg",
"image/tiff": ".tiff",
"image/webp": ".webp",
"text/csv": ".csv",
"text/html": ".html",
Expand Down
25 changes: 19 additions & 6 deletions shortcuts/doc/doc_media_insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
"path/filepath"
"strings"

_ "golang.org/x/image/bmp"
_ "golang.org/x/image/tiff"
_ "golang.org/x/image/webp"

"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/validate"
Expand Down Expand Up @@ -531,7 +535,7 @@
case "docx":
return docRef.Token, nil
case "doc":
return "", errs.NewValidationError(errs.SubtypeInvalidArgument, "docs +media-insert only supports docx documents; use a docx token/URL or a wiki URL that resolves to docx").WithParam("--doc")
return "", errs.NewValidationError(errs.SubtypeInvalidArgument, "this document operation only supports docx documents; use a docx token/URL or a wiki URL that resolves to docx").WithParam("--doc")

Check warning on line 538 in shortcuts/doc/doc_media_insert.go

View check run for this annotation

Codecov / codecov/patch

shortcuts/doc/doc_media_insert.go#L538

Added line #L538 was not covered by tests
case "wiki":
fmt.Fprintf(runtime.IO().ErrOut, "Resolving wiki node: %s\n", common.MaskToken(docRef.Token))
data, err := runtime.CallAPITyped(
Expand All @@ -551,13 +555,13 @@
return "", errs.NewInternalError(errs.SubtypeInvalidResponse, "wiki get_node returned incomplete node data")
}
if objType != "docx" {
return "", errs.NewValidationError(errs.SubtypeInvalidArgument, "wiki resolved to %q, but docs +media-insert only supports docx documents", objType).WithParam("--doc")
return "", errs.NewValidationError(errs.SubtypeInvalidArgument, "wiki resolved to %q, but this document operation only supports docx documents", objType).WithParam("--doc")

Check warning on line 558 in shortcuts/doc/doc_media_insert.go

View check run for this annotation

Codecov / codecov/patch

shortcuts/doc/doc_media_insert.go#L558

Added line #L558 was not covered by tests
}

fmt.Fprintf(runtime.IO().ErrOut, "Resolved wiki to docx: %s\n", common.MaskToken(objToken))
return objToken, nil
default:
return "", errs.NewValidationError(errs.SubtypeInvalidArgument, "docs +media-insert only supports docx documents").WithParam("--doc")
return "", errs.NewValidationError(errs.SubtypeInvalidArgument, "this document operation only supports docx documents").WithParam("--doc")

Check warning on line 564 in shortcuts/doc/doc_media_insert.go

View check run for this annotation

Codecov / codecov/patch

shortcuts/doc/doc_media_insert.go#L564

Added line #L564 was not covered by tests
}
}

Expand Down Expand Up @@ -594,15 +598,24 @@
}

func detectImageDimensionsFromPath(fio fileio.FileIO, filePath string) (int, int, error) {
width, height, _, err := detectImageConfigFromPath(fio, filePath)
return width, height, err
}

func detectImageConfigFromPath(fio fileio.FileIO, filePath string) (int, int, string, error) {
if _, err := validate.SafeInputPath(filePath); err != nil {
return 0, 0, err
return 0, 0, "", err

Check warning on line 607 in shortcuts/doc/doc_media_insert.go

View check run for this annotation

Codecov / codecov/patch

shortcuts/doc/doc_media_insert.go#L607

Added line #L607 was not covered by tests
}
f, err := fio.Open(filePath)
if err != nil {
return 0, 0, err
return 0, 0, "", err

Check warning on line 611 in shortcuts/doc/doc_media_insert.go

View check run for this annotation

Codecov / codecov/patch

shortcuts/doc/doc_media_insert.go#L611

Added line #L611 was not covered by tests
}
defer f.Close()
return detectImageDimensions(f)
cfg, format, err := image.DecodeConfig(f)
if err != nil {
return 0, 0, "", err
}
return cfg.Width, cfg.Height, format, nil
}

func buildBatchUpdateData(blockID, mediaType, fileToken, alignStr, caption string, width, height int) map[string]interface{} {
Expand Down
96 changes: 96 additions & 0 deletions shortcuts/doc/doc_media_insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
package doc

import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"fmt"
"reflect"
Expand All @@ -18,6 +20,100 @@ import (
"github.com/larksuite/cli/shortcuts/common"
)

func TestDetectImageDimensionsSupportsBMPAndTIFF(t *testing.T) {
t.Parallel()

tests := []struct {
name string
image []byte
width int
height int
}{
{name: "BMP", image: testBMPImage(2, 3), width: 2, height: 3},
{name: "TIFF", image: testTIFFImage(4, 5), width: 4, height: 5},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
width, height, err := detectImageDimensions(bytes.NewReader(tt.image))
if err != nil {
t.Fatalf("detectImageDimensions() error: %v", err)
}
if width != tt.width || height != tt.height {
t.Fatalf("dimensions = %dx%d, want %dx%d", width, height, tt.width, tt.height)
}
})
}
}

func TestDocumentImageMIMETypesAndExtensions(t *testing.T) {
t.Parallel()

tests := []struct {
contentType string
ext string
}{
{contentType: "image/bmp", ext: ".bmp"},
{contentType: "image/gif", ext: ".gif"},
{contentType: "image/jpeg", ext: ".jpg"},
{contentType: "image/png", ext: ".png"},
{contentType: "image/tiff", ext: ".tiff"},
{contentType: "image/webp", ext: ".webp"},
}
for _, tt := range tests {
t.Run(tt.contentType, func(t *testing.T) {
if got := docCoverAllowedContentTypes[tt.contentType]; got != tt.ext {
t.Fatalf("allowed extension = %q, want %q", got, tt.ext)
}
resolution := docMediaExtensionByContentType(tt.contentType + "; charset=binary")
if resolution == nil || resolution.Ext != tt.ext {
t.Fatalf("extension resolution = %#v, want %q", resolution, tt.ext)
}
})
}
}

func testBMPImage(width, height int) []byte {
rowSize := (width*3 + 3) &^ 3
pixelBytes := rowSize * height
data := make([]byte, 54+pixelBytes)
copy(data[:2], "BM")
binary.LittleEndian.PutUint32(data[2:6], uint32(len(data)))
binary.LittleEndian.PutUint32(data[10:14], 54)
binary.LittleEndian.PutUint32(data[14:18], 40)
binary.LittleEndian.PutUint32(data[18:22], uint32(width))
binary.LittleEndian.PutUint32(data[22:26], uint32(height))
binary.LittleEndian.PutUint16(data[26:28], 1)
binary.LittleEndian.PutUint16(data[28:30], 24)
binary.LittleEndian.PutUint32(data[34:38], uint32(pixelBytes))
return data
}

func testTIFFImage(width, height int) []byte {
const entryCount = 4
data := make([]byte, 8+2+entryCount*12)
copy(data[:4], []byte{'I', 'I', 42, 0})
binary.LittleEndian.PutUint32(data[4:8], 8)
binary.LittleEndian.PutUint16(data[8:10], entryCount)

entries := []struct {
tag, fieldType uint16
value uint32
}{
{tag: 256, fieldType: 4, value: uint32(width)}, // ImageWidth, LONG
{tag: 257, fieldType: 4, value: uint32(height)}, // ImageLength, LONG
{tag: 258, fieldType: 3, value: 8}, // BitsPerSample, SHORT
{tag: 262, fieldType: 3, value: 1}, // PhotometricInterpretation, SHORT
}
for i, entry := range entries {
offset := 10 + i*12
binary.LittleEndian.PutUint16(data[offset:offset+2], entry.tag)
binary.LittleEndian.PutUint16(data[offset+2:offset+4], entry.fieldType)
binary.LittleEndian.PutUint32(data[offset+4:offset+8], 1)
binary.LittleEndian.PutUint32(data[offset+8:offset+12], entry.value)
}
return data
}

func TestBuildCreateBlockDataUsesConcreteAppendIndex(t *testing.T) {
t.Parallel()

Expand Down
4 changes: 3 additions & 1 deletion shortcuts/doc/doc_resource_cover.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ func (c docCoverHTTPStatusCause) Error() string {
}

var docCoverAllowedContentTypes = map[string]string{
"image/bmp": ".bmp",
"image/gif": ".gif",
"image/jpeg": ".jpg",
"image/png": ".png",
"image/tiff": ".tiff",
"image/webp": ".webp",
}

Expand Down Expand Up @@ -566,7 +568,7 @@ func downloadDocCoverURL(ctx context.Context, runtime *common.RuntimeContext, ra
mediaType = strings.ToLower(mediaType)
ext, ok := docCoverAllowedContentTypes[mediaType]
if !ok {
return nil, "", errs.NewValidationError(errs.SubtypeInvalidArgument, "cover URL Content-Type %q is not supported; expected image/png, image/jpeg, image/gif or image/webp", mediaType).WithParam("--url")
return nil, "", errs.NewValidationError(errs.SubtypeInvalidArgument, "cover URL Content-Type %q is not supported; expected image/bmp, image/gif, image/jpeg, image/png, image/tiff, or image/webp", mediaType).WithParam("--url")
}

limited := io.LimitReader(resp.Body, docCoverURLMaxBytes+1)
Expand Down
Loading
Loading