Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

- Show setup guidance instead of a raw missing-file error when configuration-dependent commands cannot find `config.toml`. Thanks @0xdevalias.
- Report module build metadata for source-installed binaries instead of a stale hard-coded release version.
- Reject attachment redirects whose final URL leaves Discord's allowlisted CDN hosts. Thanks @GrantTheAssistant.

## 0.11.5 - 2026-07-09

Expand Down
32 changes: 29 additions & 3 deletions internal/media/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@ func Fetch(ctx context.Context, s *store.Store, opts FetchOptions) (FetchStats,
if opts.MaxBytes <= 0 {
opts.MaxBytes = DefaultMaxBytes
}
if opts.HTTPClient == nil {
opts.HTTPClient = &http.Client{Timeout: 30 * time.Second}
}
opts.HTTPClient = attachmentHTTPClient(opts.HTTPClient)
if opts.Now == nil {
opts.Now = time.Now
}
Expand Down Expand Up @@ -133,6 +131,29 @@ func Fetch(ctx context.Context, s *store.Store, opts FetchOptions) (FetchStats,
return stats, nil
}

func attachmentHTTPClient(client *http.Client) *http.Client {
if client == nil {
client = &http.Client{Timeout: 30 * time.Second}
}
clone := *client
previous := clone.CheckRedirect
clone.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) >= 3 || !isAllowedAttachmentURL(req.URL.String()) {
return errors.New("attachment redirect denied")
Comment on lines +141 to +142

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Allow the third redirect before denying

If an attachment legitimately needs three allowed Discord CDN redirects, this guard fails it before issuing the third redirected request: net/http calls CheckRedirect with req as the upcoming request and via as the requests already made, so len(via) == 3 is the third redirect target (initial request plus two followed redirects), not a request after three redirect hops. This caps successful fetches at two redirects and records those otherwise-allowed attachments as failures.

Useful? React with 👍 / 👎.

}
if previous != nil {
if err := previous(req, via); err != nil {
return err
}
if !isAllowedAttachmentURL(req.URL.String()) {
return errors.New("attachment redirect denied")
}
}
return nil
}
return &clone
}

func attachmentFailureRef(attachment store.AttachmentRow) store.FailureRef {
return store.FailureRef{
Operation: "fetch_attachment",
Expand Down Expand Up @@ -234,6 +255,11 @@ func fetchURL(ctx context.Context, opts FetchOptions, attachment store.Attachmen
}
}
defer func() { _ = resp.Body.Close() }()
// Injected clients can supply their own redirect policy, so validate the
// final response URL at the fetch boundary as well.
if resp.Request == nil || resp.Request.URL == nil || !isAllowedAttachmentURL(resp.Request.URL.String()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve injected RoundTrippers that omit Response.Request

When FetchOptions.HTTPClient is backed by a custom RoundTripper, net/http does not populate Response.Request for the transport; fakes and test transports often omit it. This guard now turns an otherwise successful response for the already-validated attachment URL into attachment response URL denied before status/body handling whenever the transport leaves Request nil, so injected clients that worked before fail even with no redirect involved.

Useful? React with 👍 / 👎.

return fetchResult{}, errors.New("attachment response URL denied")
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fetchResult{}, fmt.Errorf("attachment fetch returned HTTP %d", resp.StatusCode)
}
Expand Down
56 changes: 56 additions & 0 deletions internal/media/cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import (
"errors"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -470,6 +472,60 @@ func TestMediaPathHelpers(t *testing.T) {
require.False(t, isAllowedAttachmentURL("https://user@cdn.discordapp.com/attachments/c/file.png"))
}

func TestFetchURLRejectsAllowedCDNRedirectToMetadataHost(t *testing.T) {
t.Parallel()
var calls atomic.Int32
client := attachmentHTTPClient(&http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
calls.Add(1)
headers := make(http.Header)
headers.Set("Location", "http://169.254.169.254/computeMetadata/v1/")
return &http.Response{
StatusCode: http.StatusFound,
Header: headers,
Body: io.NopCloser(strings.NewReader("redirect")),
Request: req,
}, nil
})})
request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://cdn.discordapp.com/attachments/c/x.txt", nil)
require.NoError(t, err)
response, err := client.Do(request)
if response != nil {
_ = response.Body.Close()
}
require.ErrorContains(t, err, "attachment redirect denied")
require.EqualValues(t, 1, calls.Load())
}

func TestAttachmentHTTPClientRejectsRedirectCallbackURLMutation(t *testing.T) {
t.Parallel()
var calls atomic.Int32
client := attachmentHTTPClient(&http.Client{
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
calls.Add(1)
headers := make(http.Header)
headers.Set("Location", "https://media.discordapp.net/attachments/c/next.txt")
return &http.Response{
StatusCode: http.StatusFound,
Header: headers,
Body: io.NopCloser(strings.NewReader("redirect")),
Request: req,
}, nil
}),
CheckRedirect: func(req *http.Request, _ []*http.Request) error {
req.URL = &url.URL{Scheme: "http", Host: "169.254.169.254", Path: "/computeMetadata/v1/"}
return nil
},
})
request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://cdn.discordapp.com/attachments/c/x.txt", nil)
require.NoError(t, err)
response, err := client.Do(request)
if response != nil {
_ = response.Body.Close()
}
require.ErrorContains(t, err, "attachment redirect denied")
require.EqualValues(t, 1, calls.Load())
}

func TestMediaTargetNeedsWrite(t *testing.T) {
t.Parallel()

Expand Down