Repository navigation
fix(cli): stream encrypt and decrypt instead of buffering whole payload #3921
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
Closed
dmihalcik-virtru
wants to merge
3
commits into
feat/DSPX-2604-createtdf-chunked
from
DSPX-4499-streaming-codec
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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 |
|---|---|---|
| @@ -1,6 +1,8 @@ | ||
| package tdf | ||
|
|
||
| import ( | ||
| "bufio" | ||
| "errors" | ||
| "io" | ||
| "log/slog" | ||
| "os" | ||
|
|
@@ -11,8 +13,8 @@ import ( | |
| "github.com/opentdf/platform/lib/ocrypto" | ||
| "github.com/opentdf/platform/otdfctl/cmd/common" | ||
| "github.com/opentdf/platform/otdfctl/pkg/cli" | ||
| "github.com/opentdf/platform/otdfctl/pkg/handlers" | ||
| "github.com/opentdf/platform/otdfctl/pkg/man" | ||
| "github.com/opentdf/platform/otdfctl/pkg/utils" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
|
|
@@ -24,6 +26,38 @@ var ( | |
| EncryptCmd = &encryptDoc.Command | ||
| ) | ||
|
|
||
| // detectMimeType sniffs the payload's type from its head, and returns a reader | ||
| // that still yields the whole payload. | ||
| // | ||
| // Detection needs only the first megabyte, and Peek does not consume, so those | ||
| // bytes stay in the buffer and reach the encoder. The payload is never held in | ||
| // memory in full. Wrapping is uniform across files and pipes and needs no seek. | ||
| func detectMimeType(in io.Reader, fileExt string) (string, io.Reader, error) { | ||
| buffered, ok := in.(*bufio.Reader) | ||
| if !ok { | ||
| buffered = bufio.NewReaderSize(in, Size1MB) | ||
| in = buffered | ||
| } | ||
|
|
||
| mimetype.SetLimit(Size1MB) // limit to 1MB | ||
| head, err := buffered.Peek(Size1MB) | ||
| // A payload shorter than the peek window is the common case, not an error. | ||
| if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, bufio.ErrBufferFull) { | ||
| return "", in, err | ||
| } | ||
|
|
||
| // defaults to application/octet-stream if nothing is recognized | ||
| detected := mimetype.Detect(head).String() | ||
| if detected == "application/octet-stream" && fileExt != "" { | ||
| // Lookup returns nil for an extension it does not know, which is not an | ||
| // error — octet-stream remains the right answer. | ||
| if byExt := mimetype.Lookup(fileExt); byExt != nil { | ||
| detected = byExt.String() | ||
| } | ||
| } | ||
| return detected, in, nil | ||
| } | ||
|
Comment on lines
+29
to
+59
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't this be moved to a helper library rather than embedded in the command? |
||
|
|
||
| func encryptRun(cmd *cobra.Command, args []string) { | ||
| c := cli.New(cmd, args, cli.WithPrintJSON()) | ||
| h := common.NewHandler(c) | ||
|
|
@@ -57,13 +91,13 @@ func encryptRun(cmd *cobra.Command, args []string) { | |
| wrappingKeyAlgorithm = ocrypto.RSA2048Key | ||
| } | ||
|
|
||
| piped := readPipedStdin() | ||
| piped, hasPiped := stdinReader() | ||
|
|
||
| inputCount := 0 | ||
| if filePath != "" { | ||
| inputCount++ | ||
| } | ||
| if len(piped) > 0 { | ||
| if hasPiped { | ||
| inputCount++ | ||
| } | ||
|
|
||
|
|
@@ -77,70 +111,86 @@ func encryptRun(cmd *cobra.Command, args []string) { | |
| } | ||
|
|
||
| // prefer filepath argument over stdin input | ||
| bytesSlice := piped | ||
| var err error | ||
| var in io.Reader = piped | ||
| inputSize := handlers.InputSizeUnknown | ||
| if filePath != "" { | ||
| bytesSlice, err = utils.ReadBytesFromFile(filePath, MaxFileSize) | ||
| f, err := os.Open(filePath) | ||
| if err != nil { | ||
| cli.ExitWithError("Failed to read file:", err) | ||
| } | ||
| defer f.Close() | ||
| // Declaring the length keeps the SDK off its unknown-size path, which | ||
| // must assume ZIP64 because the choice is baked into the header of the | ||
| // first segment. Without this, wrapping the file for MIME detection | ||
| // below would hide its Seeker and silently change the output format. | ||
| if fi, err := f.Stat(); err == nil && fi.Mode().IsRegular() { | ||
| inputSize = fi.Size() | ||
| } | ||
| in = f | ||
| } | ||
|
|
||
| // auto-detect mime type if not provided | ||
| if fileMimeType == "" { | ||
| slog.Debug("detecting mime type of file") | ||
| // get the mime type of the file | ||
| mimetype.SetLimit(Size1MB) // limit to 1MB | ||
| m := mimetype.Detect(bytesSlice) | ||
| // default to application/octet-stream if no mime type is detected | ||
| fileMimeType = m.String() | ||
|
|
||
| if fileMimeType == "application/octet-stream" { | ||
| if fileExt != "" { | ||
| fileMimeType = mimetype.Lookup(fileExt).String() | ||
| } | ||
| var err error | ||
| fileMimeType, in, err = detectMimeType(in, fileExt) | ||
| if err != nil { | ||
| cli.ExitWithError("Failed to read file:", err) | ||
| } | ||
| } | ||
| slog.Debug("encrypting file", | ||
| slog.Int("file_len", len(bytesSlice)), | ||
| slog.Int64("file_len", inputSize), | ||
| slog.String("mime_type", fileMimeType), | ||
| ) | ||
|
|
||
| // Do the encryption | ||
| encrypted, err := h.EncryptBytes( | ||
| tdfType, | ||
| bytesSlice, | ||
| attrValues, | ||
| fileMimeType, | ||
| kasURLPath, | ||
| assertions, | ||
| wrappingKeyAlgorithm, | ||
| targetMode, | ||
| ) | ||
| if err != nil { | ||
| cli.ExitWithError("Failed to encrypt", err) | ||
| } | ||
|
|
||
| // Find the destination as the output flag filename or stdout | ||
| var dest *os.File | ||
| // Resolve the destination before encrypting, so that the payload streams | ||
| // straight to it rather than accumulating in memory first. | ||
| var dest io.Writer | ||
| var tdfFile *outputFile | ||
| if out != "" { | ||
| // make sure output ends in .tdf extension | ||
| if !strings.HasSuffix(out, ".tdf") { | ||
| out += ".tdf" | ||
| } | ||
| tdfFile, err := os.Create(out) | ||
| var err error | ||
| tdfFile, err = newOutputFile(out) | ||
| if err != nil { | ||
| cli.ExitWithError("Failed to write encrypted file "+out, err) | ||
| } | ||
| defer tdfFile.Close() | ||
| defer tdfFile.Cleanup() | ||
| dest = tdfFile | ||
| } else { | ||
| dest = os.Stdout | ||
| } | ||
|
|
||
| _, e := io.Copy(dest, encrypted) | ||
| if e != nil { | ||
| cli.ExitWithError("Failed to write encrypted data to stdout", e) | ||
| // cli.ExitWithError calls os.Exit, which skips deferred functions, so the | ||
| // partial output has to be discarded before handing off to it. | ||
| fail := func(msg string, err error) { | ||
| if tdfFile != nil { | ||
| tdfFile.Cleanup() | ||
| } | ||
| cli.ExitWithError(msg, err) | ||
| } | ||
|
Comment on lines
+166
to
+173
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same callout as in the decrypt. |
||
|
|
||
| // Do the encryption | ||
| err := h.Encrypt(c.Context(), dest, in, handlers.EncryptOptions{ | ||
| TDFType: tdfType, | ||
| Attributes: attrValues, | ||
| MimeType: fileMimeType, | ||
| KASURLPath: kasURLPath, | ||
| Assertions: assertions, | ||
| WrappingKeyAlgorithm: wrappingKeyAlgorithm, | ||
| TargetMode: targetMode, | ||
| InputSize: inputSize, | ||
| }) | ||
| if err != nil { | ||
| fail("Failed to encrypt", err) | ||
| } | ||
|
|
||
| if tdfFile != nil { | ||
| if err := tdfFile.Commit(); err != nil { | ||
| fail("Failed to write encrypted file "+out, err) | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
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
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.
@dmihalcik-virtru can you move this into the helper? There are other cases where we pipe results through and it seems like this should be reusable.