-
-
Notifications
You must be signed in to change notification settings - Fork 115
feat: add post-download actions (on-complete and on-error shell hooks) #323
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
mvanhorn
wants to merge
8
commits into
SurgeDM:main
Choose a base branch
from
mvanhorn:feat/post-download-actions
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
Show all changes
8 commits
Select commit
Hold shift + click to select a range
9be0afa
feat: add post-download actions (on-complete and on-error shell hooks)
mvanhorn 7de5a0d
fix(post-actions): shell-escape template variables to prevent injection
mvanhorn f5f21de
chore: fix tests and address P2 issue
SuperCoolPencil 57e2b7a
test(post-actions): derive expected quoting from shellEscape for Windows
mvanhorn e5adac8
fix: escape duration template var and fix error command routing
mvanhorn e3a9798
fix: use resolved destPath in error post-action hook
mvanhorn 071d26e
fix: address greptile P1/P2 findings on post-download actions
mvanhorn 1429f84
fix(events): add OnCompleteCommand guard + fix error hook comment
mvanhorn 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
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,92 @@ | ||
| package processing | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "os/exec" | ||
| "runtime" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/SurgeDM/Surge/internal/config" | ||
| "github.com/SurgeDM/Surge/internal/utils" | ||
| ) | ||
|
|
||
| // postActionTimeout caps shell-command runtime so a hung user command can't | ||
| // leak goroutines on headless deployments. | ||
| const postActionTimeout = 30 * time.Second | ||
|
|
||
| // PostActionContext holds information about a completed download for template substitution. | ||
| type PostActionContext struct { | ||
| Filename string | ||
| FilePath string | ||
| Size int64 | ||
| Speed float64 | ||
| Duration time.Duration | ||
| ID string | ||
| Error string | ||
| } | ||
|
|
||
| // shellEscape quotes a string so it is safe to embed in a shell command. | ||
| // On Unix it wraps the value in single quotes and escapes internal single | ||
| // quotes with the standard shell single-quote escaping idiom. On Windows | ||
| // it wraps in double quotes and escapes internal double quotes with "". | ||
| func shellEscape(s string) string { | ||
| if runtime.GOOS == "windows" { | ||
| return `"` + strings.ReplaceAll(s, `"`, `""`) + `"` | ||
| } | ||
| return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" | ||
| } | ||
|
|
||
| // expandTemplate replaces {variable} placeholders with shell-escaped values. | ||
| func expandTemplate(template string, ctx PostActionContext) string { | ||
| r := strings.NewReplacer( | ||
| "{filename}", shellEscape(ctx.Filename), | ||
| "{filepath}", shellEscape(ctx.FilePath), | ||
| "{size}", fmt.Sprintf("%d", ctx.Size), | ||
| "{speed}", fmt.Sprintf("%.2f", ctx.Speed), | ||
| "{duration}", shellEscape(ctx.Duration.Truncate(time.Second).String()), | ||
| "{id}", shellEscape(ctx.ID), | ||
| "{error}", shellEscape(ctx.Error), | ||
| ) | ||
| return r.Replace(template) | ||
|
greptile-apps[bot] marked this conversation as resolved.
|
||
| } | ||
|
|
||
| // RunPostActions runs configured post-download actions. | ||
| // Errors are logged but never propagated to prevent post-action failures from | ||
| // corrupting the download lifecycle. | ||
| func RunPostActions(settings config.PostDownloadActions, ctx PostActionContext, isError bool) { | ||
| var cmd string | ||
| if isError { | ||
| cmd = settings.OnErrorCommand | ||
| } else { | ||
| cmd = settings.OnCompleteCommand | ||
| } | ||
| if cmd == "" { | ||
| return | ||
| } | ||
|
|
||
| expanded := expandTemplate(cmd, ctx) | ||
| utils.Debug("PostAction: executing %q", expanded) | ||
|
|
||
| ctxTimeout, cancel := context.WithTimeout(context.Background(), postActionTimeout) | ||
| defer cancel() | ||
|
|
||
| var c *exec.Cmd | ||
| if runtime.GOOS == "windows" { | ||
| c = exec.CommandContext(ctxTimeout, "cmd", "/C", expanded) | ||
| } else { | ||
| c = exec.CommandContext(ctxTimeout, "sh", "-c", expanded) | ||
| } | ||
|
|
||
| output, err := c.CombinedOutput() | ||
| if ctxTimeout.Err() == context.DeadlineExceeded { | ||
| utils.Debug("PostAction: command timed out after %s (output: %s)", postActionTimeout, string(output)) | ||
| return | ||
| } | ||
| if err != nil { | ||
| utils.Debug("PostAction: command failed: %v (output: %s)", err, string(output)) | ||
| } else { | ||
| utils.Debug("PostAction: command succeeded (output: %s)", string(output)) | ||
| } | ||
| } | ||
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,112 @@ | ||
| package processing | ||
|
|
||
| import ( | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/SurgeDM/Surge/internal/config" | ||
| "github.com/stretchr/testify/assert" | ||
| ) | ||
|
|
||
| func TestExpandTemplate(t *testing.T) { | ||
| ctx := PostActionContext{ | ||
| Filename: "test.zip", | ||
| FilePath: "/downloads/test.zip", | ||
| Size: 1048576, | ||
| Speed: 524288.0, | ||
| Duration: 2 * time.Second, | ||
| ID: "abc123", | ||
| Error: "", | ||
| } | ||
|
|
||
| // Build expected values using shellEscape so the quoting style matches | ||
| // the current platform (single quotes on Unix, double quotes on Windows). | ||
| filename := shellEscape("test.zip") | ||
| filepath := shellEscape("/downloads/test.zip") | ||
| id := shellEscape("abc123") | ||
| duration := shellEscape("2s") | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| template string | ||
| want string | ||
| }{ | ||
| {"filename", "echo {filename}", "echo " + filename}, | ||
| {"filepath", "mv {filepath} /done/", "mv " + filepath + " /done/"}, | ||
| {"all vars", "{id}: {filename} ({size} bytes, {speed} B/s, {duration})", id + ": " + filename + " (1048576 bytes, 524288.00 B/s, " + duration + ")"}, | ||
| {"no vars", "echo done", "echo done"}, | ||
| {"empty", "", ""}, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| got := expandTemplate(tt.template, ctx) | ||
| assert.Equal(t, tt.want, got) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestExpandTemplate_ShellEscapeEdgeCases(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| template string | ||
| ctx PostActionContext | ||
| want string | ||
| }{ | ||
| { | ||
| "filename with spaces and quotes", | ||
| "echo {filename}", | ||
| PostActionContext{Filename: "my file's (1).zip"}, | ||
| "echo " + shellEscape("my file's (1).zip"), | ||
| }, | ||
| { | ||
| "filename with semicolon (injection attempt)", | ||
| "echo {filename}", | ||
| PostActionContext{Filename: "test; rm -rf /"}, | ||
| "echo " + shellEscape("test; rm -rf /"), | ||
| }, | ||
| { | ||
| "filepath with dollar sign (env var expansion attempt)", | ||
| "mv {filepath} /out/", | ||
| PostActionContext{FilePath: "/downloads/$HOME/.ssh"}, | ||
| "mv " + shellEscape("/downloads/$HOME/.ssh") + " /out/", | ||
| }, | ||
| { | ||
| "error with backtick (command substitution attempt)", | ||
| "notify {error}", | ||
| PostActionContext{Error: "failed: `id`"}, | ||
| "notify " + shellEscape("failed: `id`"), | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| got := expandTemplate(tt.template, tt.ctx) | ||
| assert.Equal(t, tt.want, got) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestRunPostActions_EmptyCommand(t *testing.T) { | ||
| // Should not panic or error with empty commands | ||
| RunPostActions(config.PostDownloadActions{}, PostActionContext{ | ||
| Filename: "test.zip", | ||
| }, false) | ||
| } | ||
|
|
||
| func TestRunPostActions_ValidCommand(t *testing.T) { | ||
| RunPostActions(config.PostDownloadActions{ | ||
| OnCompleteCommand: "echo {filename}", | ||
| }, PostActionContext{ | ||
| Filename: "test.zip", | ||
| }, false) | ||
| } | ||
|
|
||
| func TestRunPostActions_ErrorPath(t *testing.T) { | ||
| RunPostActions(config.PostDownloadActions{ | ||
| OnErrorCommand: "echo error: {error}", | ||
| }, PostActionContext{ | ||
| Filename: "test.zip", | ||
| Error: "connection reset", | ||
| }, true) | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.