Skip to content

Commit 68d3846

Browse files
authored
Sync file to disk before attempting attachment upload (#331)
1 parent bffe20c commit 68d3846

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

webhookbot/webhookbot/http.go

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,26 @@ func (h *HTTPSrv) getMessage(r *http.Request) (string, error) {
6363
return "`Error: no body found. To use a webhook URL, supply a 'msg' URL parameter, or a JSON POST body with a field 'msg'`", nil
6464
}
6565

66+
func (h *HTTPSrv) safeWriteToFile(hookName, content string) (string, error) {
67+
pattern := fmt.Sprintf("webhookbot-%s-*.txt", hookName)
68+
file, err := os.CreateTemp("", pattern)
69+
if err != nil {
70+
return "", fmt.Errorf("failed to create temp file: %w", err)
71+
}
72+
defer file.Close()
73+
74+
if _, err := file.Write([]byte(content)); err != nil {
75+
return "", fmt.Errorf("failed to write file: %w", err)
76+
}
77+
78+
// Explicitly sync to ensure all data is written to disk before upload
79+
if err := file.Sync(); err != nil {
80+
return "", fmt.Errorf("failed to sync file: %w", err)
81+
}
82+
83+
return file.Name(), nil
84+
}
85+
6686
func (h *HTTPSrv) handleHook(w http.ResponseWriter, r *http.Request) {
6787
vars := mux.Vars(r)
6888
id := vars["id"]
@@ -89,10 +109,9 @@ func (h *HTTPSrv) handleHook(w http.ResponseWriter, r *http.Request) {
89109

90110
// error created in https://github.com/keybase/client/blob/7d6aa64f3fba66adba7a5dd1cc7c523d5086a548/go/chat/msgchecker/plaintext_checker.go#L50
91111
if strings.Contains(err.Error(), "exceeds the maximum length") {
92-
fileName := fmt.Sprintf("webhookbot-%s-%d.txt", hook.Name, time.Now().Unix())
93-
filePath := fmt.Sprintf("/tmp/%s", fileName)
94-
if err := os.WriteFile(filePath, []byte(msg), 0644); err != nil {
95-
h.Errorf("failed to write %s: %s", filePath, err)
112+
filePath, err := h.safeWriteToFile(hook.Name, msg)
113+
if err != nil {
114+
h.Errorf("failed to write attachment file: %s", err)
96115
return
97116
}
98117
base.GoWithRecover(h.DebugOutput, func() {

0 commit comments

Comments
 (0)