You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
to 3.0: supporting data branch diff as file with stage. - #23189
create stage stage02 url = 's3://.../' credentials = {"aws_key_id"='...',"aws_secret_key"='...',"AWS_REGION"='...','PROVIDER'='...', 'ENDPOINT'='...'};
data branch diff t2 against t1 output 'stage://stage02';
PR Type
Enhancement
Description
Add stage path decoding support for data branch diff output
Refactor file path handling to support both local and stage paths
Implement pipe-based file writing for improved performance
Add context cancellation checks in diff operations
Diagram Walkthrough
flowchart LR
A["Data Branch Diff"] -->|"Output to stage or local"| B["tryDecodeStagePath"]
B -->|"Stage path detected"| C["prepareFSForDiffAsFile"]
B -->|"Local path"| D["Standard file handling"]
C -->|"Mutable FS"| E["Direct mutator write"]
C -->|"Immutable FS"| F["newSingleWriteAppender"]
F -->|"Pipe-based writing"| G["File output"]
Loading
File Walkthrough
Relevant files
Refactoring
authenticate.go
Extract stage path decoding into helper function
pkg/frontend/authenticate.go
Extract stage path decoding logic into new tryDecodeStagePath function
Refactor doCheckFilePath to use the new helper function
Below is a summary of compliance checks for this PR:
Security Compliance
⚪
Disabled validation
Description: The validate function for DataBranchDiff now unconditionally returns nil, disabling directory/path validation and potentially allowing unintended file paths or stage targets to be accepted without checks. data_branch.go [319-326]
Description: The pipe-based writer streams data to fileservice without explicit size limits or sanitization, which could enable large unbounded writes to external storage if upstream controls are weak. data_branch.go [1128-1165]
Generic: Robust Error Handling and Edge Case Management
Objective: Ensure comprehensive error handling that provides meaningful context and graceful degradation
Status: Disabled validation: The validate function was changed to unconditionally return nil, disabling directory/path validations and potentially allowing invalid or insecure output paths without checks.
Generic: Security-First Input Validation and Data Handling
Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent vulnerabilities
Status: Path validation off: By returning nil immediately, input validation for output directories is bypassed and stage/local path handling proceeds without verifying existence/permissions or sanitizing user-provided paths.
Objective: To create a detailed and reliable record of critical system actions for security analysis and compliance.
Status: Missing audit logs: Newly added file output and deletion operations (including stage path handling and streaming writes) perform critical I/O without any added auditing/logging of who performed the action, when, and the outcome.
Objective: To ensure logs are useful for debugging and auditing without exposing sensitive information like PII, PHI, or cardholder data.
Status: Stage path secrecy: New stage path decoding and file path resolution handle potentially sensitive endpoint/credentials indirectly, but there is no evidence of redaction or assurance logs won’t include sensitive paths if logged elsewhere.
Referred Code
functryDecodeStagePath(
ses*Session,
filePathstring,
) (retPathstring, okbool, errerror) {
var (
s stage.StageDef
)
ifstrings.HasPrefix(filePath, stage.STAGE_PROTOCOL+"://") {
// stage:// URLifs, err=stageutil.UrlToStageDef(filePath, ses.proc); err!=nil {
return
}
// s.ToPath() returns the fileservice filepath, i.e. s3,...:/path for S3 or /path for local fileifretPath, _, err=s.ToPath(); err!=nil {
return
}
ok=true... (clipped27lines)
Fix a potential deadlock in the newSingleWriteAppender goroutine. If targetFS.Write fails, add a return after sending the error to prevent the goroutine from blocking on a subsequent channel send.
if err = worker.Submit(func() {
defer close(done)
vec := fileservice.IOVector{
FilePath: targetPath,
Entries: []fileservice.IOEntry{
{
ReaderForWrite: pr,
Size: -1,
},
},
}
if wErr := targetFS.Write(ctx, vec); wErr != nil {
+ // The reader is closed by the fileservice on write error,+ // but we close it with the error to unblock the writer.
_ = pr.CloseWithError(wErr)
done <- wErr
return
}
done <- pr.Close()
}); err != nil {
_ = pr.Close()
_ = pw.Close()
return
}
Apply / Chat
Suggestion importance[1-10]: 8
__
Why: The suggestion correctly identifies a potential deadlock in the worker goroutine if a write error occurs, and provides a correct fix by adding a return statement.
Medium
✅ Restore validation for non-stage pathsSuggestion Impact:The commit reintroduced validation logic for the diff output directory, adding a new validate function that selectively validates local and fileservice paths while handling stage paths appropriately. It replaced the previous no-op validate and expanded checks beyond simple os.Stat, aligning with the suggestion’s intent.
code diff:
- if err = validate(stmt); err != nil {+ if err = validate(execCtx.reqCtx, ses, stmt); err != nil {
return err
}
@@ -985,6 +964,101 @@
srcName, baseName,
time.Now().UTC().Format("20060102_150405"),
)
+}++func validate(+ ctx context.Context,+ ses *Session,+ stmt tree.Statement,+) error {+ if stmt == nil {+ return nil+ }++ var (+ ok bool+ diffStmt *tree.DataBranchDiff+ )++ if diffStmt, ok = stmt.(*tree.DataBranchDiff); !ok {+ return nil+ }++ if diffStmt.OutputOpt != nil && len(diffStmt.OutputOpt.DirPath) > 0 {+ if err := validateOutputDirPath(ctx, ses, diffStmt.OutputOpt.DirPath); err != nil {+ return err+ }+ }++ return nil+}++func validateOutputDirPath(ctx context.Context, ses *Session, dirPath string) (err error) {+ if len(dirPath) == 0 {+ return nil+ }++ var (+ stagePath string+ ok bool+ inputDirPath = dirPath+ )++ if stagePath, ok, err = tryDecodeStagePath(ses, dirPath); err != nil {+ return+ } else if ok {+ dirPath = stagePath+ }++ var fsPath fileservice.Path+ if fsPath, err = fileservice.ParsePath(dirPath); err != nil {+ return+ }++ if fsPath.Service == "" {+ var info os.FileInfo+ if info, err = os.Stat(dirPath); err != nil {+ if os.IsNotExist(err) {+ return moerr.NewInvalidInputNoCtxf("output directory %s does not exist", inputDirPath)+ }+ return+ }+ if !info.IsDir() {+ return moerr.NewInvalidInputNoCtxf("output directory %s is not a directory", inputDirPath)+ }+ return nil+ }++ var (+ targetFS fileservice.FileService+ targetPath string+ entry *fileservice.DirEntry+ )++ if fsPath.Service == defines.SharedFileServiceName {+ targetFS = getPu(ses.GetService()).FileService+ targetPath = dirPath+ } else {+ var etlFS fileservice.ETLFileService+ if etlFS, targetPath, err = fileservice.GetForETL(ctx, nil, dirPath); err != nil {+ return+ }+ targetFS = etlFS+ defer targetFS.Close(ctx)+ }++ if entry, err = targetFS.StatFile(ctx, targetPath); err != nil {+ if moerr.IsMoErrCode(err, moerr.ErrFileNotFound) {+ return moerr.NewInvalidInputNoCtxf("output directory %s does not exist", inputDirPath)+ }+ return+ }++ if !entry.IsDir {+ return moerr.NewInvalidInputNoCtxf("output directory %s is not a directory", inputDirPath)+ }++ return nil
}
Restore path validation for non-stage paths in the validate function. The current implementation disables all validation to support stage paths, but this reintroduces checks for regular file paths.
func validate(stmt tree.Statement) error {
- return nil
switch s := stmt.(type) {
case *tree.DataBranchDiff:
if s.OutputOpt != nil && len(s.OutputOpt.DirPath) != 0 {
+ // Skip validation for stage paths, as os.Stat will fail.+ if strings.HasPrefix(s.OutputOpt.DirPath, stage.STAGE_PROTOCOL+"://") {+ return nil+ }
info, err := os.Stat(s.OutputOpt.DirPath)
if err != nil {
if os.IsNotExist(err) {
return moerr.NewInternalErrorNoCtxf("diff output directory does not exist: %s", s.OutputOpt.DirPath)
}
return moerr.NewInternalErrorNoCtxf("diff output directory check failed: %v", err)
}
if !info.IsDir() {
return moerr.NewInternalErrorNoCtxf("diff output file only accept a directory path")
}
return nil
}
}
return nil
}
[Suggestion processed]
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies that completely removing path validation is a regression and proposes a sound fix to selectively validate only non-stage paths, improving robustness.
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
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.
User description
What type of PR is this?
Which issue(s) this PR fixes:
issue ##21979
What this PR does / why we need it:
PR Type
Enhancement
Description
Add stage path decoding support for data branch diff output
Refactor file path handling to support both local and stage paths
Implement pipe-based file writing for improved performance
Add context cancellation checks in diff operations
Diagram Walkthrough
File Walkthrough
authenticate.go
Extract stage path decoding into helper functionpkg/frontend/authenticate.go
tryDecodeStagePathfunctiondoCheckFilePathto use the new helper functiondata_branch.go
Add stage path support and pipe-based file writingpkg/frontend/data_branch.go
iopackage import for pipe-based file writingdiffOnBasecall fromexecCtx.reqCtxtoctxprepareFSForDiffAsFileto support stage paths with propercleanup handling
newSingleWriteAppenderfunction usingio.Pipefor efficientstreaming writes
writeCSVto handle both stage and local file paths withappropriate cleanup
diffDataHelperto prevent resourceleaks