Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 8 additions & 0 deletions .jules/sentinel.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,11 @@
**Learning:** `ip.IsPrivate()` and `ip.IsLoopback()` are not sufficient to block all local traffic. The concept of "Unspecified" addresses (all zeros) must also be explicitly handled when validating IPs for SSRF protection in Go.

**Prevention:** When implementing a safe dialer to prevent SSRF, always include `ip.IsUnspecified()` in the list of blocked IP characteristics, in addition to private, loopback, and link-local addresses.

## 2026-01-27 - Fix Stored XSS in HTML Output

**Vulnerability:** The application was vulnerable to Stored Cross-Site Scripting (XSS) because it rendered HTML content from the `go-readability` library without adequate sanitization. Although `go-readability` performs some cleaning, it does not guarantee safety against all XSS vectors (e.g., `onerror` handlers).

**Learning:** Relying solely on a parsing library for security is insufficient. Libraries designed for content extraction (like `readability`) often prioritize preserving content structure over strict security sanitization. A dedicated sanitizer is required before rendering user-controlled HTML.

**Prevention:** We integrated `bluemonday` with `UGCPolicy` to explicitly sanitize the HTML content before it is injected into the HTML template or JSON response. This ensures that any malicious tags or attributes missed by the parser are stripped.
7 changes: 5 additions & 2 deletions api/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (

"codeberg.org/readeck/go-readability/v2"
"github.com/mattn/godown"
"github.com/microcosm-cc/bluemonday"
"golang.org/x/net/html"
)

Expand Down Expand Up @@ -57,6 +58,8 @@ const Template = `
var (
DefaultTemplate = template.Must(template.New("article").Parse(Template))
ReadabilityParser = readability.NewParser()
// sanitizer is used to clean up HTML content to prevent XSS
sanitizer = bluemonday.UGCPolicy()
// httpClient used for fetching remote articles with timeouts and redirect policy
httpClient = &http.Client{
Transport: &http.Transport{
Expand Down Expand Up @@ -270,7 +273,7 @@ func formatHTML(w http.ResponseWriter, article readability.Article, contentBuf *
Content template.HTML
}{
Title: article.Title(),
Content: template.HTML(contentBuf.String()),
Content: template.HTML(sanitizer.Sanitize(contentBuf.String())),
}
if err := DefaultTemplate.Execute(w, data); err != nil {
// at this point, we can't write a JSON error, so we log it
Expand All @@ -297,7 +300,7 @@ func formatJSON(w http.ResponseWriter, article readability.Article, buf *bytes.B
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(map[string]string{
"title": article.Title(),
"content": buf.String(),
"content": sanitizer.Sanitize(buf.String()),
}); err != nil {
log.Printf("error encoding json: %v", err)
}
Expand Down
12 changes: 6 additions & 6 deletions api/reconstruct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ func TestReconstructTargetURL(t *testing.T) {
gotU, _ := url.Parse(got)
expU, _ := url.Parse(tt.expected)

if gotU == nil || expU == nil {
if got != tt.expected {
t.Errorf("reconstructTargetURL() = %v, want %v", got, tt.expected)
}
return
}
if gotU == nil || expU == nil {
if got != tt.expected {
t.Errorf("reconstructTargetURL() = %v, want %v", got, tt.expected)
}
return
}

if gotU.Scheme != expU.Scheme || gotU.Host != expU.Host || gotU.Path != expU.Path {
t.Errorf("reconstructTargetURL() base mismatch = %v, want %v", got, tt.expected)
Expand Down
80 changes: 80 additions & 0 deletions api/xss_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package handler

import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)

func TestXSSVulnerability(t *testing.T) {
// Malicious HTML payload
htmlBody := `
<!DOCTYPE html>
<html>
<head><title>XSS Test</title></head>
<body>
<h1>XSS Test</h1>
<p>Safe content</p>
<script>alert('XSS')</script>
<img src="x" onerror="alert('img XSS')">
<a href="javascript:alert('link XSS')">Click me</a>
</body>
</html>`

srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write([]byte(htmlBody)); err != nil {
t.Errorf("failed to write response: %v", err)
}
}))
defer srv.Close()

// Override httpClient
oldClient := httpClient
httpClient = srv.Client()
defer func() { httpClient = oldClient }()

u, err := url.Parse(srv.URL)
if err != nil {
t.Fatalf("failed to parse server URL: %v", err)
}

ctx := context.Background()
req := httptest.NewRequest("GET", "/", nil)

// Fetch and parse
art, err := fetchAndParse(ctx, u, req)
if err != nil {
t.Fatalf("fetchAndParse failed: %v", err)
}

contentBuf := &bytes.Buffer{}
if err := art.RenderHTML(contentBuf); err != nil {
t.Fatalf("failed to render HTML: %v", err)
}

// We must test the output of formatHTML, which applies the sanitization
rec := httptest.NewRecorder()
formatHTML(rec, art, contentBuf)

resp := rec.Result()
bodyBuf := new(bytes.Buffer)
bodyBuf.ReadFrom(resp.Body)
content := bodyBuf.String()

// Check for XSS vectors
t.Logf("Rendered content: %s", content)

if strings.Contains(content, "<script>") {
t.Error("VULNERABILITY: <script> tag not stripped")
}
if strings.Contains(content, "onerror") {
t.Error("VULNERABILITY: onerror handler not stripped")
}
if strings.Contains(content, "javascript:") {
t.Error("VULNERABILITY: javascript: URI not stripped")
}
}
Comment on lines +3 to +80

Choose a reason for hiding this comment

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

security-medium medium

The security fix for XSS was applied to both formatHTML and formatJSON. This test currently only validates the formatHTML output. To ensure complete test coverage for the fix, you should also verify the output of formatJSON.

A good way to achieve this is by refactoring the test to be table-driven, which would allow you to easily test multiple formatters with the same setup logic. This also makes it easier to add tests for other formatters in the future.

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
)

func TestXSSVulnerability(t *testing.T) {
	// Malicious HTML payload
	htmlBody := `
<!DOCTYPE html>
<html>
<head><title>XSS Test</title></head>
<body>
	<h1>XSS Test</h1>
	<p>Safe content</p>
	<script>alert('XSS')</script>
	<img src="x" onerror="alert('img XSS')">
	<a href="javascript:alert('link XSS')">Click me</a>
</body>
</html>`

	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if _, err := w.Write([]byte(htmlBody)); err != nil {
			t.Errorf("failed to write response: %v", err)
		}
	}))
	defer srv.Close()

	// Override httpClient
	oldClient := httpClient
	httpClient = srv.Client()
	defer func() { httpClient = oldClient }()

	u, err := url.Parse(srv.URL)
	if err != nil {
		t.Fatalf("failed to parse server URL: %v", err)
	}

	ctx := context.Background()
	req := httptest.NewRequest("GET", "/", nil)

	// Fetch and parse
	art, err := fetchAndParse(ctx, u, req)
	if err != nil {
		t.Fatalf("fetchAndParse failed: %v", err)
	}

	contentBuf := &bytes.Buffer{}
	if err := art.RenderHTML(contentBuf); err != nil {
		t.Fatalf("failed to render HTML: %v", err)
	}

	testCases := []struct {
		name       string
		formatFunc formatHandler
		getContent func(t *testing.T, resp *http.Response) string
	}{
		{
			name:       "HTML format",
			formatFunc: formatHTML,
			getContent: func(t *testing.T, resp *http.Response) string {
				body, err := io.ReadAll(resp.Body)
				if err != nil {
					t.Fatalf("failed to read response body: %v", err)
				}
				return string(body)
			},
		},
		{
			name:       "JSON format",
			formatFunc: formatJSON,
			getContent: func(t *testing.T, resp *http.Response) string {
				var data map[string]string
				if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
					t.Fatalf("failed to decode json response: %v", err)
				}
				return data["content"]
			},
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			rec := httptest.NewRecorder()
			tc.formatFunc(rec, art, contentBuf)
			content := tc.getContent(t, rec.Result())

			// Check for XSS vectors
			t.Logf("Rendered content in %s: %s", tc.name, content)

			if strings.Contains(content, "<script>") {
				t.Error("VULNERABILITY: <script> tag not stripped")
			}
			if strings.Contains(content, "onerror") {
				t.Error("VULNERABILITY: onerror handler not stripped")
			}
			if strings.Contains(content, "javascript:") {
				t.Error("VULNERABILITY: javascript: URI not stripped")
			}
		})
	}
}

3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ require (
require (
github.com/andybalholm/cascadia v1.3.3 // indirect
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
github.com/go-shiori/dom v0.0.0-20230515143342-73569d674e1c // indirect
github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
golang.org/x/text v0.32.0 // indirect
)
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kk
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de h1:FxWPpzIjnTlhPwqqXc4/vE0f7GvRjuAsbW+HOIe8KnA=
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de/go.mod h1:DCaWoUhZrYW9p1lxo/cm8EmUOOzAPSEZNGF2DK1dJgw=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4=
Expand All @@ -16,12 +18,16 @@ github.com/go-shiori/dom v0.0.0-20230515143342-73569d674e1c/go.mod h1:oVDCh3qjJM
github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f h1:3BSP1Tbs2djlpprl7wCLuiqMaUh5SJkkzI2gDs+FgLs=
github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f/go.mod h1:Pcatq5tYkCW2Q6yrR2VRHlbHpZ/R4/7qyL1TCF7vl14=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
github.com/mattn/go-runewidth v0.0.8/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mattn/godown v0.0.1 h1:39uk50ufLVQFs0eapIJVX5fCS74a1Fs2g5f1MVqIHdE=
github.com/mattn/godown v0.0.1/go.mod h1:/ivCKurgV/bx6yqtP/Jtc2Xmrv3beCYBvlfAUl4X5g4=
github.com/microcosm-cc/bluemonday v1.0.27 h1:MpEUotklkwCSLeH+Qdx1VJgNqLlpY2KXwXFM08ygZfk=
github.com/microcosm-cc/bluemonday v1.0.27/go.mod h1:jFi9vgW+H7c3V0lb6nR74Ib/DIB5OBs92Dimizgw2cA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
Expand Down