fix(groups): reject incomplete subscription exports

Finish generating the export in a private temporary file before sending a success response. Keep memory bounded, send the complete length, and discard staged data when the database read fails.
This commit is contained in:
Hamed Sanaei
2026-12-01 12:16:34 +03:30
parent 1ac11c7783
commit 7e6f64cd01
2 changed files with 82 additions and 13 deletions
+48 -12
View File
@@ -3,7 +3,9 @@ package controller
import (
"bufio"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
@@ -260,12 +262,45 @@ func (a *GroupController) exportSubLinks(c *gin.Context) {
return
}
c.Header("Content-Type", "text/plain; charset=utf-8")
c.Header("Content-Disposition", `attachment; filename="sub-links.txt"`)
c.Header("Cache-Control", "no-store")
out := bufio.NewWriter(c.Writer)
serveGroupSubscriptionExport(c, links, func(visit func(email, subID string) error) error {
return a.clientService.WalkGroupSubscriptionClients(c.Request.Context(), group, visit)
})
}
func serveGroupSubscriptionExport(c *gin.Context, links service.PanelSubscriptionLinks, walk func(func(email, subID string) error) error) {
file, err := os.CreateTemp("", "x-ui-group-links-*.txt")
if err != nil {
groupSubscriptionExportFailed(c, err)
return
}
defer func() {
_ = file.Close()
_ = os.Remove(file.Name())
}()
// Stage the output so a mid-query failure cannot publish a partial download.
if err := writeGroupSubscriptionExport(file, links, walk); err != nil {
groupSubscriptionExportFailed(c, err)
return
}
size, err := file.Seek(0, io.SeekCurrent)
if err == nil {
_, err = file.Seek(0, io.SeekStart)
}
if err != nil {
groupSubscriptionExportFailed(c, err)
return
}
c.DataFromReader(http.StatusOK, size, "text/plain; charset=utf-8", file, map[string]string{
"Content-Disposition": `attachment; filename="sub-links.txt"`,
"Cache-Control": "no-store",
})
}
func writeGroupSubscriptionExport(dst io.Writer, links service.PanelSubscriptionLinks, walk func(func(email, subID string) error) error) error {
out := bufio.NewWriter(dst)
first := true
err = a.clientService.WalkGroupSubscriptionClients(c.Request.Context(), group, func(email, subID string) error {
err := walk(func(email, subID string) error {
if !first {
if err := out.WriteByte('\n'); err != nil {
return err
@@ -281,14 +316,15 @@ func (a *GroupController) exportSubLinks(c *gin.Context) {
}
return nil
})
if err == nil {
err = out.Flush()
if err != nil {
return err
}
if err != nil && c.Request.Context().Err() == nil {
return out.Flush()
}
func groupSubscriptionExportFailed(c *gin.Context, err error) {
if c.Request.Context().Err() == nil {
logger.Warning("group subscription export failed:", err)
if !c.Writer.Written() {
c.Header("Content-Disposition", "")
c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong"))
}
c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong"))
}
}
@@ -2,6 +2,7 @@ package controller
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -230,6 +231,37 @@ func TestGroupAdjustCapsReportedSkipsWithoutChangingExplicitResponses(t *testing
}
}
func TestGroupSubscriptionExportRejectsFailedReadBeforeSendingFile(t *testing.T) {
dir := t.TempDir()
t.Setenv("TMPDIR", dir)
t.Setenv("TMP", dir)
t.Setenv("TEMP", dir)
router := gin.New()
router.GET("/export", func(c *gin.Context) {
links := service.PanelSubscriptionLinks{Enable: true, URI: "https://sub.example.test/plain/"}
serveGroupSubscriptionExport(c, links, func(visit func(string, string) error) error {
for i := range 300 {
if err := visit(fmt.Sprintf("client-%03d", i), "example-id"); err != nil {
return err
}
}
return errors.New("injected client query failure after reading several pages")
})
})
req := httptest.NewRequest(http.MethodGet, "/export", nil)
out := httptest.NewRecorder()
router.ServeHTTP(out, req)
if out.Code != http.StatusInternalServerError || out.Header().Get("Content-Disposition") != "" ||
strings.Contains(out.Body.String(), "https://sub.example.test") {
t.Fatalf("failed export sent HTTP %d, disposition %q, and %d bytes", out.Code, out.Header().Get("Content-Disposition"), out.Body.Len())
}
files, err := os.ReadDir(dir)
if err != nil || len(files) != 0 {
t.Fatalf("temporary export leaked after failure: %v (%v)", files, err)
}
}
func TestGroupSubscriptionExportAndPagingHTTP(t *testing.T) {
sizes := []int{1000}
if os.Getenv("XUI_SCALE_TEST") != "" {
@@ -276,7 +308,8 @@ func testGroupSubscriptionExportAndPaging(t *testing.T, size int) {
}
out := groupAPIRequest(router, http.MethodGet, "/groups/subLinks/export?group=staff", "")
lines := strings.Split(out.Body.String(), "\n")
if out.Code != http.StatusOK || out.Header().Get("Cache-Control") != "no-store" || len(lines) != total {
if out.Code != http.StatusOK || out.Header().Get("Cache-Control") != "no-store" || len(lines) != total ||
out.Header().Get("Content-Length") != fmt.Sprint(out.Body.Len()) {
t.Fatalf("export returned HTTP %d and %d rows, want %d rows", out.Code, len(lines), total)
}
for index, line := range lines {