Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8117: fix(wecom): preserve streaming media on Windows (#9395)

Multica Eve76b274e898c2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 74147b80bf..b5aab464af 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -533,6 +533,12 @@ jobs:
check-latest: true
cache-dependency-path: server/go.sum
+ - name: Test Windows WeCom media streaming and plaintext cleanup
+ working-directory: server
+ # These tests need no database. Windows must prove private file access,
+ # streaming without buffered fallback, and cleanup after process exit.
+ run: go test ./internal/integrations/wecom -v -run '^(TestStreamingDecrypt|TestMediaTempFile|TestPeekFile|TestIngest|TestTheStreamingPath)' -count=1 -timeout=5m
+
- name: Test Windows execution-environment isolation
working-directory: server
# Keep this job scoped to the runtime regression it exists to prove.
diff --git a/server/internal/integrations/wecom/media_ingest.go b/server/internal/integrations/wecom/media_ingest.go
index 63cef5daef..e0c814ca2d 100644
--- a/server/internal/integrations/wecom/media_ingest.go
+++ b/server/internal/integrations/wecom/media_ingest.go
@@ -184,7 +184,7 @@ func (r *wecomMediaResolver) ingestOne(ctx context.Context, inst engine.Resolved
streamer, canStream := r.storage.(mediaStreamStorage)
if canStream {
// The memory-flat path: ciphertext streams from the socket into the
- // decrypt, the plaintext lands in an unlinked temp file, and the
+ // decrypt, the plaintext lands in a private temp file, and the
// upload reads from there. Nothing holds a whole attachment.
ref, err := r.ingestStreaming(ctx, streamer, wm, index, m, key, link)
if err == nil || !errors.Is(err, errStreamingUnavailable) {
@@ -422,14 +422,14 @@ func (r *wecomMediaResolver) tellTheSender(inst engine.ResolvedInstallation, wm
}
// errStreamingUnavailable says the memory-flat path could not be taken for a
-// reason that is not the attachment's fault — no temp space, a backend that
-// advertises UploadStream and rejects it. The caller falls back to the
-// buffered path rather than failing an attachment over an optimisation.
+// reason that is not the attachment's fault, such as no temp space.
+// The caller falls back to the buffered path rather than failing an
+// attachment over an optimisation.
var errStreamingUnavailable = errors.New("wecom: streaming media ingest unavailable")
// ingestStreaming carries one attachment without ever holding it whole:
// ciphertext streams from the response body into the decrypt, the plaintext
-// lands in an unlinked temp file, and the upload reads from that file with
+// lands in a private temp file, and the upload reads from that file with
// the exact length it now knows.
func (r *wecomMediaResolver) ingestStreaming(
ctx context.Context,
@@ -450,9 +450,9 @@ func (r *wecomMediaResolver) ingestStreaming(
if err != nil {
// A decrypt failure is the attachment's problem and must be reported
// as one; only a failure to make the temp file is grounds to fall
- // back, and decryptToFile says so in its message.
- if strings.Contains(err.Error(), "media temp file") {
- return channel.MediaRef{}, fmt.Errorf("%w: %v", errStreamingUnavailable, err)
+ // back.
+ if errors.Is(err, errMediaTempFile) {
+ return channel.MediaRef{}, fmt.Errorf("%w: %w", errStreamingUnavailable, err)
}
return channel.MediaRef{}, err
}
diff --git a/server/internal/integrations/wecom/media_stream.go b/server/internal/integrations/wecom/media_stream.go
index 14b3f91114..e3417596ee 100644
--- a/server/internal/integrations/wecom/media_stream.go
+++ b/server/internal/integrations/wecom/media_stream.go
@@ -24,9 +24,9 @@ package wecom
// final block is read — unknowable at the moment the upload must start. A
// file on disk has already answered the question: its size IS the length.
//
-// Files are created 0600 and removed on every path. They hold decrypted
-// attachment content, so their permissions are part of the feature rather
-// than housekeeping.
+// Files are private to the process user and removed on every path. They hold
+// decrypted attachment content, so their permissions are part of the feature
+// rather than housekeeping.
import (
"crypto/aes"
@@ -43,9 +43,11 @@ import (
// is holding.
const mediaStreamChunk = 256 << 10
+var errMediaTempFile = errors.New("wecom: media temp file")
+
// decryptToFile reads ciphertext from src, decrypts it into a new temp file,
// and returns the file positioned at its start along with the plaintext
-// length. The caller closes and removes it.
+// length. The caller closes it; the OS also reclaims it on process exit.
//
// CBC needs the tail before the head can be trusted — the pad is on the last
// block — so the final block is held back until the source is exhausted and
@@ -62,21 +64,9 @@ func decryptToFile(aesKey string, src io.Reader, dir string) (f *os.File, size i
// The IV is the first 16 bytes of the key, as WeCom's own libraries do.
mode := cipher.NewCBCDecrypter(block, key[:aes.BlockSize])
- out, err := os.CreateTemp(dir, "wecom-media-*.bin")
+ out, err := createMediaTempFile(dir)
if err != nil {
- return nil, 0, fmt.Errorf("wecom: media temp file: %w", err)
- }
- // Unlink now: the file stays readable through the handle and disappears
- // the moment the process lets go of it, including on a crash. Nothing
- // with decrypted attachment content is left behind for anyone to find.
- if err := os.Remove(out.Name()); err != nil {
- out.Close()
- return nil, 0, fmt.Errorf("wecom: media temp file: %w", err)
- }
- if err := out.Chmod(0o600); err != nil && !errors.Is(err, os.ErrNotExist) {
- // Best effort: the file is already unlinked, so this is belt as well
- // as braces.
- _ = err
+ return nil, 0, fmt.Errorf("%w: %w", errMediaTempFile, err)
}
defer func() {
if err != nil {
diff --git a/server/internal/integrations/wecom/media_stream_test.go b/server/internal/integrations/wecom/media_stream_test.go
index e7c2c8d4ba..047fb54977 100644
--- a/server/internal/integrations/wecom/media_stream_test.go
+++ b/server/internal/integrations/wecom/media_stream_test.go
@@ -26,6 +26,7 @@ import (
"net/http/httptest"
"os"
"strings"
+ "sync/atomic"
"testing"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
@@ -166,62 +167,37 @@ func TestStreamingDecryptRefusesAWrongKey(t *testing.T) {
otherB64 := base64.StdEncoding.EncodeToString(other)
ct := sealMedia(t, key, []byte("the real contents"))
- if _, _, err := decryptToFile(otherB64, strings.NewReader(ct), t.TempDir()); err == nil {
+ dir := t.TempDir()
+ if _, _, err := decryptToFile(otherB64, strings.NewReader(ct), dir); err == nil {
t.Fatal("a wrong key produced a file")
}
+ assertMediaTempDirEmpty(t, dir)
}
// A truncated body is the same class of failure and must not half-succeed.
func TestStreamingDecryptRefusesATruncatedBody(t *testing.T) {
key, keyB64 := mediaTestKey(t)
ct := sealMedia(t, key, []byte(strings.Repeat("x", 200)))
+ dir := t.TempDir()
// Cut mid-block: not a multiple of the cipher block at all.
- if _, _, err := decryptToFile(keyB64, strings.NewReader(ct[:len(ct)-5]), t.TempDir()); err == nil {
+ if _, _, err := decryptToFile(keyB64, strings.NewReader(ct[:len(ct)-5]), dir); err == nil {
t.Fatal("a body cut mid-block produced a file")
}
// And cut on a block boundary, which only the pad check can catch.
- if _, _, err := decryptToFile(keyB64, strings.NewReader(ct[:len(ct)-aes.BlockSize]), t.TempDir()); err == nil {
+ if _, _, err := decryptToFile(keyB64, strings.NewReader(ct[:len(ct)-aes.BlockSize]), dir); err == nil {
t.Fatal("a body cut on a block boundary produced a file")
}
+ assertMediaTempDirEmpty(t, dir)
}
func TestStreamingDecryptRefusesAnEmptyBody(t *testing.T) {
_, keyB64 := mediaTestKey(t)
- if _, _, err := decryptToFile(keyB64, strings.NewReader(""), t.TempDir()); err == nil {
- t.Fatal("an empty body produced a file")
- }
-}
-
-// The plaintext is an attachment. Its temp file must not be readable by
-// anyone else, and must not outlive the handle — including if the process
-// dies holding it.
-func TestTheTempFileIsPrivateAndUnlinked(t *testing.T) {
- key, keyB64 := mediaTestKey(t)
dir := t.TempDir()
- ct := sealMedia(t, key, []byte("secret contents"))
-
- f, _, err := decryptToFile(keyB64, strings.NewReader(ct), dir)
- if err != nil {
- t.Fatalf("decryptToFile: %v", err)
- }
- defer f.Close()
-
- entries, err := os.ReadDir(dir)
- if err != nil {
- t.Fatalf("read dir: %v", err)
- }
- if len(entries) != 0 {
- t.Fatalf("the temp directory still holds %d entries; the plaintext file was not unlinked", len(entries))
- }
-
- info, err := f.Stat()
- if err != nil {
- t.Fatalf("stat: %v", err)
- }
- if perm := info.Mode().Perm(); perm&0o077 != 0 {
- t.Errorf("the plaintext file is mode %v, want no group or other access", perm)
+ if _, _, err := decryptToFile(keyB64, strings.NewReader(""), dir); err == nil {
+ t.Fatal("an empty body produced a file")
}
+ assertMediaTempDirEmpty(t, dir)
}
// peekFile has to leave the file where it found it, or the upload sends a
@@ -279,9 +255,18 @@ type streamingStorage struct {
gotBytes []byte
gotType string
streamErr error
+ gotFile *os.File
+ onStream func()
}
-func (s *streamingStorage) UploadStream(_ context.Context, key string, data io.Reader, size int64, contentType, filename string) (string, error) {
+func (s *streamingStorage) UploadStream(ctx context.Context, key string, data io.Reader, size int64, contentType, filename string) (string, error) {
+ s.gotFile, _ = data.(*os.File)
+ if s.onStream != nil {
+ s.onStream()
+ }
+ if err := ctx.Err(); err != nil {
+ return "", err
+ }
if s.streamErr != nil {
return "", s.streamErr
}
@@ -301,11 +286,15 @@ func (s *streamingStorage) UploadStream(_ context.Context, key string, data io.R
// with its exact length, and the object must be byte-identical to what the
// buffered path would have produced.
func TestIngestPrefersTheStreamingPathAndUploadsTheRightBytes(t *testing.T) {
+ dir := t.TempDir()
+ setMediaTempDir(t, dir)
key, keyB64 := mediaTestKey(t)
plain := []byte(strings.Repeat("报告正文。", 4000))
ct := sealMedia(t, key, plain)
+ var requests atomic.Int64
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ requests.Add(1)
w.Header().Set("Content-Disposition", `attachment; filename="report.txt"`)
w.Write([]byte(ct))
}))
@@ -330,6 +319,11 @@ func TestIngestPrefersTheStreamingPathAndUploadsTheRightBytes(t *testing.T) {
if storage.gotSize != int64(len(plain)) {
t.Fatalf("ContentLength = %d, want %d — a wrong length is a corrupt object", storage.gotSize, len(plain))
}
+ if requests.Load() != 1 || len(storage.stored()) != 0 {
+ t.Fatalf("streaming retried or used buffered upload: requests=%d buffered=%d", requests.Load(), len(storage.stored()))
+ }
+ assertMediaTempFileClosed(t, storage.gotFile)
+ assertMediaTempDirEmpty(t, dir)
if !bytes.Equal(storage.gotBytes, plain) {
t.Fatalf("the uploaded object is %d bytes, want the %d-byte plaintext", len(storage.gotBytes), len(plain))
}
diff --git a/server/internal/integrations/wecom/media_temp_other.go b/server/internal/integrations/wecom/media_temp_other.go
new file mode 100644
index 0000000000..83de57d889
--- /dev/null
+++ b/server/internal/integrations/wecom/media_temp_other.go
@@ -0,0 +1,21 @@
+//go:build !windows
+
+package wecom
+
+import (
+ "errors"
+ "os"
+)
+
+func createMediaTempFile(dir string) (*os.File, error) {
+ out, err := os.CreateTemp(dir, "wecom-media-*.bin") // Created with mode 0600.
+ if err != nil {
+ return nil, err
+ }
+ // Unlink before writing plaintext, so even an abnormal process exit
+ // cannot leave attachment content behind.
+ if err := os.Remove(out.Name()); err != nil {
+ return nil, errors.Join(err, out.Close(), os.Remove(out.Name()))
+ }
+ return out, nil
+}
diff --git a/server/internal/integrations/wecom/media_temp_other_test.go b/server/internal/integrations/wecom/media_temp_other_test.go
new file mode 100644
index 0000000000..1e5a617bdc
--- /dev/null
+++ b/server/internal/integrations/wecom/media_temp_other_test.go
@@ -0,0 +1,22 @@
+//go:build !windows
+
+package wecom
+
+import "testing"
+
+func TestMediaTempFileIsPrivateAndUnlinked(t *testing.T) {
+ dir := t.TempDir()
+ f, err := createMediaTempFile(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ assertMediaTempDirEmpty(t, dir)
+ info, err := f.Stat()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if perm := info.Mode().Perm(); perm&0o077 != 0 {
+ t.Errorf("the plaintext file is mode %v, want no group or other access", perm)
+ }
+}
diff --git a/server/internal/integrations/wecom/media_temp_test.go b/server/internal/integrations/wecom/media_temp_test.go
new file mode 100644
index 0000000000..717cc54e61
--- /dev/null
+++ b/server/internal/integrations/wecom/media_temp_test.go
@@ -0,0 +1,228 @@
+package wecom
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+func assertMediaTempDirEmpty(t *testing.T, dir string) {
+ t.Helper()
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 0 {
+ t.Fatalf("media processing left %d temporary files", len(entries))
+ }
+}
+
+func assertMediaTempFileClosed(t *testing.T, f *os.File) {
+ t.Helper()
+ if f == nil {
+ t.Fatal("streaming upload did not receive a plaintext file")
+ }
+ // Stat can return ERROR_INVALID_HANDLE after Close on Windows.
+ // Read checks Go's closed-file state consistently across platforms.
+ var buf [1]byte
+ if _, err := f.Read(buf[:]); !errors.Is(err, os.ErrClosed) {
+ t.Fatalf("plaintext file is still open: %v", err)
+ }
+}
+
+func setMediaTempDir(t *testing.T, dir string) {
+ t.Helper()
+ for _, name := range []string{"TMPDIR", "TMP", "TEMP", "SystemTemp"} {
+ t.Setenv(name, dir)
+ }
+}
+
+func TestMediaTempFileRemovedAfterClose(t *testing.T) {
+ dir := t.TempDir()
+ key, keyB64 := mediaTestKey(t)
+ f, _, err := decryptToFile(keyB64, strings.NewReader(sealMedia(t, key, []byte("private attachment"))), dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ if err := f.Close(); err != nil {
+ t.Fatal(err)
+ }
+ assertMediaTempDirEmpty(t, dir)
+}
+
+func TestMediaTempFileRemovedAfterProcessExit(t *testing.T) {
+ if os.Getenv("MULTICA_TEST_MEDIA_TEMP_CHILD") == "1" {
+ key, keyB64 := mediaTestKey(t)
+ f, _, err := decryptToFile(keyB64, strings.NewReader(sealMedia(t, key, []byte("private attachment"))), os.Getenv("MULTICA_TEST_MEDIA_TEMP_DIR"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ os.Exit(43) // Bypass deferred closes, as an abnormal process exit does.
+ }
+ dir := t.TempDir()
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cmd := exec.CommandContext(ctx, exe, "-test.run=^TestMediaTempFileRemovedAfterProcessExit$")
+ cmd.Env = append(os.Environ(), "MULTICA_TEST_MEDIA_TEMP_CHILD=1", "MULTICA_TEST_MEDIA_TEMP_DIR="+dir)
+ output, err := cmd.CombinedOutput()
+ var exitErr *exec.ExitError
+ if !errors.As(err, &exitErr) || exitErr.ExitCode() != 43 {
+ t.Fatalf("child did not reach the abrupt exit: %v\n%s", err, output)
+ }
+ assertMediaTempDirEmpty(t, dir)
+}
+
+func TestMediaTempFileCreationFailureClassified(t *testing.T) {
+ dir := t.TempDir()
+ _, keyB64 := mediaTestKey(t)
+ f, _, err := decryptToFile(keyB64, strings.NewReader(""), filepath.Join(dir, "missing"))
+ if f != nil || !errors.Is(err, errMediaTempFile) || !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("temp creation failure lost its classification or cause: file=%v err=%v", f, err)
+ }
+ assertMediaTempDirEmpty(t, dir)
+}
+
+type mediaErrorReader struct{ err error }
+
+func (r mediaErrorReader) Read([]byte) (int, error) { return 0, r.err }
+
+func TestStreamingDecryptReadErrorCleansTempFile(t *testing.T) {
+ key, keyB64 := mediaTestKey(t)
+ ct := sealMedia(t, key, []byte(strings.Repeat("x", mediaStreamChunk*2)))
+ for _, readErr := range []error{io.ErrUnexpectedEOF, context.Canceled} {
+ t.Run(readErr.Error(), func(t *testing.T) {
+ dir := t.TempDir()
+ src := io.MultiReader(strings.NewReader(ct[:mediaStreamChunk]), mediaErrorReader{readErr})
+ f, _, err := decryptToFile(keyB64, src, dir)
+ if f != nil || !errors.Is(err, readErr) || errors.Is(err, errMediaTempFile) {
+ t.Fatalf("read failure was misclassified: file=%v err=%v", f, err)
+ }
+ assertMediaTempDirEmpty(t, dir)
+ })
+ }
+}
+
+func TestIngestStreamingFailureClosesTempFile(t *testing.T) {
+ for _, failure := range []string{"upload", "cancel"} {
+ t.Run(failure, func(t *testing.T) {
+ dir := t.TempDir()
+ setMediaTempDir(t, dir)
+ key, keyB64 := mediaTestKey(t)
+ ct := sealMedia(t, key, []byte("private attachment"))
+ var requests atomic.Int64
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ requests.Add(1)
+ w.Write([]byte(ct))
+ }))
+ defer srv.Close()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ wantErr := errors.New("upload failed")
+ storage := &streamingStorage{streamErr: wantErr}
+ if failure == "cancel" {
+ wantErr = context.Canceled
+ storage.onStream = cancel
+ }
+ r := newTestResolver(storage, newFakeMediaLedger(nil), nil)
+ msg := mediaMessage(t, "file", map[string]any{"file": map[string]any{"url": srv.URL, "aeskey": keyB64}})
+ wm, err := wecomMsgFromRaw(msg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = r.ingestOne(ctx, mediaInstallation(), uuidOf(5), wm, 0, wm.Media[0])
+ if !errors.Is(err, wantErr) {
+ t.Fatalf("ingest error=%v, want %v", err, wantErr)
+ }
+ if requests.Load() != 1 || len(storage.stored()) != 0 {
+ t.Fatalf("failed upload was retried: requests=%d buffered=%d", requests.Load(), len(storage.stored()))
+ }
+ assertMediaTempFileClosed(t, storage.gotFile)
+ assertMediaTempDirEmpty(t, dir)
+ })
+ }
+}
+
+func TestIngestFallsBackWhenTempFileUnavailable(t *testing.T) {
+ dir := t.TempDir()
+ setMediaTempDir(t, filepath.Join(dir, "missing"))
+ key, keyB64 := mediaTestKey(t)
+ ct := sealMedia(t, key, []byte("private attachment"))
+ var requests atomic.Int64
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ requests.Add(1)
+ w.Write([]byte(ct))
+ }))
+ defer srv.Close()
+ storage := &streamingStorage{}
+ r := newTestResolver(storage, newFakeMediaLedger(nil), nil)
+ msg := mediaMessage(t, "file", map[string]any{"file": map[string]any{"url": srv.URL, "aeskey": keyB64}})
+ out := r.ResolveMedia(context.Background(), mediaInstallation(), engine.ResolvedIdentity{}, uuidOf(6), uuidOf(5), msg)
+ if len(out.MediaRefs) != 1 || requests.Load() != 2 || len(storage.stored()) != 1 || storage.gotFile != nil {
+ t.Fatalf("temp-file failure did not use buffered fallback: refs=%d requests=%d buffered=%d file=%v", len(out.MediaRefs), requests.Load(), len(storage.stored()), storage.gotFile)
+ }
+ assertMediaTempDirEmpty(t, dir)
+}
+
+type mediaReadErrorTransport struct {
+ http.RoundTripper
+ ciphertext string
+ err error
+}
+
+func (tr mediaReadErrorTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ resp, err := tr.RoundTripper.RoundTrip(req)
+ if err != nil {
+ return nil, err
+ }
+ resp.Body.Close()
+ resp.Body = io.NopCloser(io.MultiReader(strings.NewReader(tr.ciphertext), mediaErrorReader{tr.err}))
+ resp.ContentLength = -1
+ return resp, nil
+}
+
+func TestIngestReadFailureDoesNotRetryAsTempFailure(t *testing.T) {
+ dir := t.TempDir()
+ setMediaTempDir(t, dir)
+ key, keyB64 := mediaTestKey(t)
+ ct := sealMedia(t, key, []byte("private attachment"))
+ var requests atomic.Int64
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ requests.Add(1)
+ w.Write([]byte(ct))
+ }))
+ defer srv.Close()
+ storage := &streamingStorage{}
+ r := newTestResolver(storage, newFakeMediaLedger(nil), nil)
+ readErr := errors.New("media temp file: error text from the source")
+ r.http.Transport = mediaReadErrorTransport{r.http.Transport, ct, readErr}
+ msg := mediaMessage(t, "file", map[string]any{"file": map[string]any{"url": srv.URL, "aeskey": keyB64}})
+ wm, err := wecomMsgFromRaw(msg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = r.ingestOne(context.Background(), mediaInstallation(), uuidOf(5), wm, 0, wm.Media[0])
+ if !errors.Is(err, readErr) || requests.Load() != 1 {
+ t.Fatalf("source failure was retried as a temp-file failure: err=%v requests=%d", err, requests.Load())
+ }
+ if storage.gotFile != nil || len(storage.stored()) != 0 {
+ t.Fatal("a failed download reached storage")
+ }
+ assertMediaTempDirEmpty(t, dir)
+}
diff --git a/server/internal/integrations/wecom/media_temp_windows.go b/server/internal/integrations/wecom/media_temp_windows.go
new file mode 100644
index 0000000000..591e521ca0
--- /dev/null
+++ b/server/internal/integrations/wecom/media_temp_windows.go
@@ -0,0 +1,66 @@
+package wecom
+
+import (
+ "crypto/rand"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+func createMediaTempFile(dir string) (*os.File, error) {
+ user, err := windows.GetCurrentProcessToken().GetTokenUser()
+ if err != nil {
+ return nil, err
+ }
+ // Protect the DACL from inherited directory permissions. Chmod(0600)
+ // on Windows only sets the read-only attribute, not access permissions.
+ sd, err := windows.SecurityDescriptorFromString("D:P(A;;FA;;;" + user.User.Sid.String() + ")")
+ if err != nil {
+ return nil, err
+ }
+ attrs := windows.SecurityAttributes{
+ Length: uint32(unsafe.Sizeof(windows.SecurityAttributes{})),
+ SecurityDescriptor: sd,
+ InheritHandle: 0,
+ }
+ if dir == "" {
+ dir = os.TempDir()
+ }
+ dir, err = filepath.Abs(dir)
+ if err != nil {
+ return nil, err
+ }
+ // Match os.CreateTemp's support for paths beyond MAX_PATH, including UNC.
+ if !strings.HasPrefix(dir, `\\?\`) {
+ if strings.HasPrefix(dir, `\\`) {
+ dir = `\\?\UNC\` + strings.TrimPrefix(dir, `\\`)
+ } else {
+ dir = `\\?\` + dir
+ }
+ }
+ for range 10 {
+ name := filepath.Join(dir, "wecom-media-"+rand.Text()+".bin")
+ path, err := windows.UTF16PtrFromString(name)
+ if err != nil {
+ return nil, err
+ }
+ // No sharing or inheritance: another handle cannot expose the
+ // plaintext or postpone deletion after this process exits.
+ h, err := windows.CreateFile(path,
+ windows.GENERIC_READ|windows.GENERIC_WRITE|windows.DELETE,
+ 0, &attrs, windows.CREATE_NEW,
+ windows.FILE_ATTRIBUTE_TEMPORARY|windows.FILE_FLAG_DELETE_ON_CLOSE, 0)
+ if errors.Is(err, windows.ERROR_FILE_EXISTS) || errors.Is(err, windows.ERROR_ALREADY_EXISTS) {
+ continue
+ }
+ if err != nil {
+ return nil, &os.PathError{Op: "createtemp", Path: name, Err: err}
+ }
+ return os.NewFile(uintptr(h), name), nil
+ }
+ return nil, &os.PathError{Op: "createtemp", Path: dir, Err: os.ErrExist}
+}
diff --git a/server/internal/integrations/wecom/media_temp_windows_test.go b/server/internal/integrations/wecom/media_temp_windows_test.go
new file mode 100644
index 0000000000..d4d9ff959e
--- /dev/null
+++ b/server/internal/integrations/wecom/media_temp_windows_test.go
@@ -0,0 +1,70 @@
+package wecom
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+func TestMediaTempFileWindowsPrivacy(t *testing.T) {
+ dir := t.TempDir()
+ f, err := createMediaTempFile(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ sd, err := windows.GetSecurityInfo(windows.Handle(f.Fd()), windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION)
+ if err != nil {
+ t.Fatal(err)
+ }
+ control, _, err := sd.Control()
+ if err != nil || control&windows.SE_DACL_PROTECTED == 0 {
+ t.Fatalf("plaintext DACL is not protected from inheritance: control=%v err=%v", control, err)
+ }
+ dacl, _, err := sd.DACL()
+ if err != nil || dacl == nil || dacl.AceCount != 1 {
+ t.Fatalf("want exactly one private access entry: dacl=%v err=%v", dacl, err)
+ }
+ var ace *windows.ACCESS_ALLOWED_ACE
+ if err := windows.GetAce(dacl, 0, &ace); err != nil {
+ t.Fatal(err)
+ }
+ user, err := windows.GetCurrentProcessToken().GetTokenUser()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE ||
+ !(*windows.SID)(unsafe.Pointer(&ace.SidStart)).Equals(user.User.Sid) {
+ t.Fatal("plaintext access is not restricted to the process user")
+ }
+ if other, err := os.Open(f.Name()); err == nil {
+ other.Close()
+ t.Fatal("another handle could open the plaintext file")
+ }
+ if err := f.Close(); err != nil {
+ t.Fatal(err)
+ }
+ assertMediaTempDirEmpty(t, dir)
+}
+
+func TestMediaTempFileWindowsLongPath(t *testing.T) {
+ dir := t.TempDir()
+ for len(dir) < 280 {
+ dir = filepath.Join(dir, strings.Repeat("long-temp-", 5))
+ }
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ f, err := createMediaTempFile(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := f.Close(); err != nil {
+ t.Fatal(err)
+ }
+ assertMediaTempDirEmpty(t, dir)
+}