Repository navigation
fix(mail): preserve literal attachment paths and support bounded PDF stdin #2822
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jrwut
wants to merge
1
commit into
larksuite:main
Choose a base branch
from
jrwut:fix/mail-literal-attachments-stdin
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| # Mail attachment input | ||
|
|
||
| `--attach` is a repeated literal path, not a comma-separated list. Quote each | ||
| argument and repeat the flag for each file. Commas and spaces within a filename | ||
| are preserved through validation, classification and MIME construction. This | ||
| also applies to mail template attachment flags. Previously undocumented | ||
| comma-list splitting is intentionally removed to avoid attaching unintended | ||
| files. Recipient comma-list parsing is unchanged. | ||
|
|
||
| ## PDF bytes from stdin | ||
|
|
||
| `+draft-create`, `+send`, `+reply`, `+reply-all` and `+forward` additionally accept: | ||
|
|
||
| ``` | ||
| --attach-stdin-name 'Invoice 521,625.00.pdf' --attach-stdin-type application/pdf | ||
| ``` | ||
|
|
||
| These flags read one binary PDF from stdin during Execute, with a hard 10 MiB | ||
| limit (the reader consumes at most limit + 1 bytes). The explicit filename must | ||
| be a basename ending in `.pdf`, not a path, and must have no controls, separators | ||
| or colon. The explicit type must be exactly `application/pdf`. The bytes must | ||
| begin `%PDF-`; this is a format marker check, **not** structural PDF validation | ||
| or a malware scan. Bytes, including NUL and non-UTF-8 bytes, are preserved. | ||
|
|
||
| Only feed bytes you are authorized to disclose, from an authorized producer. | ||
| This interface does not open, copy, relocate or grant access to any original | ||
| file. All existing `--attach`, inline, body-file and other path validation, | ||
| including the built-in `/root` denylist, remains intact. Never move protected | ||
| files to evade that policy. The caller remains responsible for source access | ||
| and disclosure authorization; stdin cannot prove provenance. | ||
|
|
||
| The command shares a single-use stdin claim with framework text inputs. The | ||
| stdin PDF is held in memory, not written to a temporary file. Its size/count | ||
| contribute to existing attachment limits/classification. It remains a normal | ||
| attachment using `application/octet-stream` on the wire, matching the mail | ||
| backend's attachment-versus-inline behavior. If combined attachments require | ||
| large-attachment upload, existing policy still applies to the path attachments. | ||
|
|
||
| Dry-run validates metadata without reading stdin or claiming byte validation. | ||
| The existing default draft behavior and explicit send confirmation are unchanged. | ||
| This is CLI code only; no deployment or live send is required to test it. | ||
|
|
||
| ## Offline verification | ||
|
|
||
| ``` | ||
| go test ./shortcuts/mail ./shortcuts/common -run 'TestStdinAttachment|TestComposeStdinAttachment|TestComposeAttachment|TestReadStdinBytes|TestAttachmentProtected' -count=1 -v | ||
| go build . | ||
| ``` | ||
|
|
||
| The mounted-command MIME tests use the repository HTTP mock transport, not a | ||
| real mailbox. Literal filename parsing tests use a test-only injected metadata | ||
| backend because the checkout and test scratch live inside protected `/root`. | ||
| Production path behavior is separately tested to remain denied. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| # Multiple PDF attachments from binary stdin | ||
|
|
||
| All five compose shortcuts (`mail +draft-create`, `+send`, `+reply`, `+reply-all`, | ||
| `+forward`) accept `--attach-stdin-manifest` as a **literal JSON argv value**: | ||
|
|
||
| ```json | ||
| [{"filename":"Invoice 521,625.00.pdf","size":12345},{"filename":"Receipt.pdf","size":67890}] | ||
| ``` | ||
|
|
||
| Write the original binary PDF payloads to stdin, concatenated in the same order. | ||
| `size` is the exact number of bytes for that entry, not an encoded length. | ||
| Do not base64-encode, add separators, or append a newline. The manifest is not | ||
| an `@file` or stdin input and never opens attachment paths. | ||
|
|
||
| Rules: | ||
|
|
||
| - 1–250 entries; at most 10 MiB (10,485,760 bytes) **combined** payload. | ||
| - Each entry has exactly one `filename` and one integer `size` (at least 5). | ||
| Unknown, duplicate, case-aliased keys and trailing JSON are rejected. | ||
| - Filenames must be valid UTF-8 PDF basenames (case-insensitive `.pdf`), with no | ||
| slash, backslash, colon, control characters, or surrounding whitespace. | ||
| Commas and non-ASCII names are preserved. Filenames need not be unique. | ||
| - Each declared segment must begin `%PDF-`. Truncated streams, trailing bytes, | ||
| and non-PDF segments fail before the compose draft is created. | ||
| - Exclusive with `--attach-stdin-name` / `--attach-stdin-type` and any other | ||
| stdin consumer. Existing single-file flags remain supported unchanged. | ||
| - PDF-only type is implicit in this manifest format; attachments are emitted as | ||
| `application/octet-stream` with attachment disposition for backend compatibility. | ||
| - Existing attachment count and EML limits include every stdin PDF. Regular | ||
| `--attach` paths still use the unchanged literal-path guard and denylist. | ||
| - `--dry-run` validates metadata only, not stdin bytes. PDF magic validation is | ||
| not malware scanning or authorization. Only supply user-authorized bytes. | ||
| - Commands remain draft-first. This flag never implies `--confirm-send`. | ||
|
|
||
| Example: Python caller with four authorized original PDF byte buffers, no | ||
| intermediate copies or relocated files (no account call occurs until you run it): | ||
|
|
||
| ```python | ||
| import json | ||
| import subprocess | ||
|
|
||
| # attachments = [(basename, original_pdf_bytes), ...] # all four PDFs | ||
| manifest = json.dumps([ | ||
| {"filename": name, "size": len(data)} for name, data in attachments | ||
| ], ensure_ascii=False) | ||
| subprocess.run([ | ||
| "/path/to/lark-cli-multi-stdin", "mail", "+draft-create", | ||
| "--to", "recipient@example.com", "--subject", "Payment request", | ||
| "--body", "Please review the attached payment documents.", | ||
| "--attach-stdin-manifest", manifest, | ||
| ], input=b"".join(data for _, data in attachments), check=True) | ||
| ``` | ||
|
|
||
| Do not add `--confirm-send`. Signature behavior is unchanged by this patch. | ||
| Mounted HTTP-mock tests decode the EML for all five compose paths and verify | ||
| four attachment filenames (including comma and Thai names), octet-stream MIME, | ||
| attachment disposition, exact binary bytes, and count. No account/network | ||
| requests or deployment are needed for these tests. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| // Copyright (c) 2026 Lark Technologies Pte. Ltd. | ||
| // SPDX-License-Identifier: MIT | ||
|
|
||
| package common | ||
|
|
||
| import "io" | ||
|
|
||
| // ReadStdinBytesOnce claims the command's single stdin for bounded binary input. | ||
| // It shares the claim with text Input flags and never trims or decodes bytes. | ||
| func (ctx *RuntimeContext) ReadStdinBytesOnce(flag string, limit int64) ([]byte, error) { | ||
| if ctx.stdinConsumed { | ||
| return nil, ValidationErrorf("%s: stdin can only be used by one flag", flag).WithParam(flag) | ||
| } | ||
| if limit <= 0 { | ||
| return nil, ValidationErrorf("%s: invalid stdin byte limit", flag).WithParam(flag) | ||
| } | ||
| ctx.stdinConsumed = true | ||
| if ctx.IO() == nil || ctx.IO().In == nil { | ||
| return nil, ValidationErrorf("%s: stdin is unavailable", flag).WithParam(flag) | ||
| } | ||
| data, err := io.ReadAll(io.LimitReader(ctx.IO().In, limit+1)) | ||
| if err != nil { | ||
| return nil, ValidationErrorf("%s: failed to read stdin: %v", flag, err).WithParam(flag).WithCause(err) | ||
| } | ||
| if int64(len(data)) > limit { | ||
| return nil, ValidationErrorf("%s: stdin exceeds %d bytes", flag, limit).WithParam(flag) | ||
| } | ||
| return data, nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| package common | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestReadStdinBytesOnceBounded(t *testing.T) { | ||
| r := newTestRuntimeWithStdin(nil, "%PDF-1.4\x00\xff\n") | ||
| got, err := r.ReadStdinBytesOnce("--attach-stdin-name", 32) | ||
| if err != nil || !bytes.Equal(got, []byte("%PDF-1.4\x00\xff\n")) { | ||
| t.Fatalf("bytes=%q err=%v", got, err) | ||
| } | ||
| if _, err := r.ReadStdinBytesOnce("--other", 32); err == nil { | ||
| t.Fatal("stdin must be single use") | ||
| } | ||
| } | ||
| func TestReadStdinBytesRejectsOverflow(t *testing.T) { | ||
| r := newTestRuntimeWithStdin(nil, "12345") | ||
| if _, err := r.ReadStdinBytesOnce("--attach-stdin-name", 4); err == nil { | ||
| t.Fatal("expected bounded read rejection") | ||
| } | ||
| } | ||
| func TestReadStdinBytesRejectsPriorTextConsumer(t *testing.T) { | ||
| r := newTestRuntimeWithStdin(map[string]string{"body": "-"}, "body") | ||
| if err := resolveInputFlags(r, []Flag{{Name: "body", Input: []string{Stdin}}}); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if _, err := r.ReadStdinBytesOnce("--attach-stdin-name", 32); err == nil { | ||
| t.Fatal("must reject stdin already consumed by body") | ||
| } | ||
| } | ||
|
|
||
| func TestReadStdinBytesAcceptsExactLimit(t *testing.T) { | ||
| r := newTestRuntimeWithStdin(nil, "1234") | ||
| got, err := r.ReadStdinBytesOnce("--attach-stdin-name", 4) | ||
| if err != nil || string(got) != "1234" { | ||
| t.Fatalf("got=%q err=%v", got, err) | ||
| } | ||
| } | ||
| func TestReadStdinBytesBlocksSubsequentTextConsumer(t *testing.T) { | ||
| r := newTestRuntimeWithStdin(map[string]string{"body": "-"}, "1234") | ||
| if _, err := r.ReadStdinBytesOnce("--attach-stdin-name", 4); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| if err := resolveInputFlags(r, []Flag{{Name: "body", Input: []string{Stdin}}}); err == nil { | ||
| t.Fatal("text flag reused binary stdin") | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| package mail | ||
|
|
||
| import ( | ||
| "context" | ||
| "github.com/larksuite/cli/extension/fileio" | ||
| "github.com/larksuite/cli/internal/cmdutil" | ||
| "github.com/larksuite/cli/shortcuts/common" | ||
| "github.com/spf13/cobra" | ||
| "os" | ||
| "strings" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestComposeAttachmentPreservesCommaFilename(t *testing.T) { | ||
| for _, shortcut := range []common.Shortcut{MailSend, MailDraftCreate, MailReply, MailReplyAll, MailForward} { | ||
| t.Run(shortcut.Command, func(t *testing.T) { | ||
| chdirTemp(t) | ||
| names := []string{"Example Vendor Campaign THB 521,625.00 Invoice.pdf", "second, report.pdf"} | ||
| for _, name := range names { | ||
| if err := os.WriteFile(name, []byte("%PDF-1.4\n"), 0600); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| } | ||
| cmd := &cobra.Command{} | ||
| cmd.Flags().StringArray("attach", names, "") | ||
| cmd.Flags().StringArray("to", []string{"recipient@example.com"}, "") | ||
| for k, v := range map[string]string{"subject": "subject", "body": "body", "message-id": "123"} { | ||
| cmd.Flags().String(k, v, "") | ||
| } | ||
| runtime := &common.RuntimeContext{Cmd: cmd, Factory: &cmdutil.Factory{FileIOProvider: attachmentTestProvider{}}} | ||
| if err := shortcut.Validate(context.Background(), runtime); err != nil { | ||
| t.Fatalf("literal repeated --attach filenames must validate: %v", err) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestComposeAttachmentDoesNotInterpretCommaAsList(t *testing.T) { | ||
| chdirTemp(t) | ||
| for _, name := range []string{"a.pdf", "b.pdf"} { | ||
| if err := os.WriteFile(name, []byte("data"), 0600); err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| } | ||
| cmd := &cobra.Command{} | ||
| cmd.Flags().StringArray("attach", []string{"a.pdf,b.pdf"}, "") | ||
| cmd.Flags().String("body", "body", "") | ||
| cmd.Flags().String("subject", "subject", "") | ||
| cmd.Flags().StringArray("to", []string{"recipient@example.com"}, "") | ||
| runtime := &common.RuntimeContext{Cmd: cmd, Factory: &cmdutil.Factory{FileIOProvider: attachmentTestProvider{}}} | ||
| err := MailSend.Validate(context.Background(), runtime) | ||
| if err == nil { | ||
| t.Fatal("must not silently attach two different files for one literal path") | ||
| } | ||
| if !strings.Contains(err.Error(), "a.pdf,b.pdf") { | ||
| t.Fatalf("error should identify exact path: %v", err) | ||
| } | ||
| } | ||
|
|
||
| // An injected, test-only storage backend isolates parsing from host /root policy. | ||
| type attachmentTestProvider struct{} | ||
|
|
||
| func (attachmentTestProvider) Name() string { return "attachment-test" } | ||
| func (attachmentTestProvider) ResolveFileIO(context.Context) fileio.FileIO { return attachmentTestIO{} } | ||
|
|
||
| type attachmentTestIO struct{ fileio.FileIO } | ||
|
|
||
| func (attachmentTestIO) Stat(name string) (fileio.FileInfo, error) { return os.Stat(name) } | ||
|
|
||
| func TestAttachmentProtectedPathsRemainDenied(t *testing.T) { | ||
| for _, path := range []string{"/root/never-open.pdf", "../../../root/never-open.pdf", "/proc/self/environ", "/etc/shadow"} { | ||
| r := &common.RuntimeContext{} | ||
| if _, err := statAttachmentFiles(r.FileIO(), []string{path}); err == nil { | ||
| t.Fatalf("protected path accepted: %q", path) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: larksuite/cli
Length of output: 6898
Use the built CLI name in the example.
The build configuration produces
lark-cli, notlark-cli-multi-stdin. Following the documented build guidance therefore leaves the example pointing to a nonexistent executable.Suggested fix
📝 Committable suggestion
🤖 Prompt for AI Agents