Skip to content
Merged
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
2 changes: 1 addition & 1 deletion Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ lint: vet
# locally install build dependencies
[group('build')]
init:
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.11.4
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.14.0
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,50 @@ fmt.Println(ua.Anchor()) # e.g. example.org/path/to/page
fmt.Println(ua.From()) # e.g. 10.0.0.1
```

##### Origin headers

The `From()` method returns the originating client IP. The address is
parsed from HTTP headers at construction time (`Origins()`) using the
following precedence:

1. `Forwarded` (RFC 7239) — the leftmost usable `for=` parameter. Surrounding
double-quotes are stripped, and any port is stripped. Redacted tokens
(`unknown`, `_hidden`, and any value beginning with `_`) are treated as
missing and cause a fall-through.
2. `X-Forwarded-For` — the leftmost comma-separated entry with any port
stripped.
3. `X-Real-IP` — common nginx convention, with any port stripped.
4. `RemoteAddr` — the host portion of the TCP source address, via
`net.SplitHostPort`.

Regardless of which source produced the value:

- Ports are always stripped (IPv4 `:port`, bracketed IPv6 `[::1]:port`,
bare hostnames `:port`).
- The leftmost entry is always returned. Each proxy along the chain appends
to the right, so the leftmost value is the one nearest the originating
client.
- Redacted `Forwarded` tokens (`for=unknown`, `for=_hidden`) are silently
dropped so callers transparently fall back to the next source rather
than logging an opaque placeholder.

In all three header layouts below `From()` returns the same value for the
same originating client:

```go
// 1. RFC 7239 Forwarded header
r.Header.Set("Forwarded", "for=192.0.2.43;proto=https")
// From() -> 192.0.2.43

// 2. Legacy X-Forwarded-For (most common in practice)
r.Header.Set("X-Forwarded-For", "192.0.2.43, 10.0.0.5, proxy.example.com")
// From() -> 192.0.2.43 (leftmost = originating client)

// 3. nginx-style X-Real-IP, or nothing at all
r.Header.Set("X-Real-IP", "192.0.2.43")
// From() -> 192.0.2.43
```

#### package webtools/htmx

Provides utilities for building HTMX-compatible responses. The package includes an `Interface` for rendering HTMX responses, along with support for plain text, raw HTML, and templated content.
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module cattlecloud.net/go/webtools

go 1.26
go 1.27

require (
cattlecloud.net/go/forms v1.1.0
Expand Down
104 changes: 98 additions & 6 deletions useragent.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package webtools

import (
"net"
"net/http"
"net/url"
"strings"
Expand All @@ -16,13 +17,23 @@ type Origin struct {
UserAgent useragent.UserAgent

// about the requesting entity
Remote string
//
// Forward is the originating client as derived from the X-Forwarded-For,
// RFC 7239 Forwarded, or X-Real-IP headers (consulted in that order).
// It is the leftmost usable entry with any port stripped. The value
// is a bare host with no port.
//
// Remote is the host portion of the TCP source address (r.RemoteAddr)
// with any port stripped.
Forward string
Remote string
Reference string
}

// From returns the value of the X-Forwarded-For if set, otherwise defaulting
// to the Remote address.
// From returns the originating client IP. If available, this is the
// leftmost usable value from the Forwarded (RFC 7239), X-Forwarded-For,
// or X-Real-IP headers, in that order. Otherwise it falls back to the
// host portion of RemoteAddr. Ports are always stripped.
func (o *Origin) From() string {
if o.Forward != "" {
return o.Forward
Expand Down Expand Up @@ -65,14 +76,31 @@ func (o *Origin) String() string {
//
// - Method
// - Host
// - Forwarder
// - Referer
// - User-Agent
//
// The originating client IP (Forward/Remote) is resolved from headers in this
// order:
//
// 1. Forwarded (RFC 7239) — leftmost usable "for=" value, with quotes and
// port stripped; redacted values ("unknown", "_hidden", any value
// starting with "_") are treated as missing.
// 2. X-Forwarded-For — leftmost comma-separated entry, port stripped.
// 3. X-Real-IP — common nginx convention, port stripped.
// 4. RemoteAddr — host portion of the TCP source address, port stripped.
//
// Ports are always stripped regardless of source.
func Origins(r *http.Request) *Origin {
method := strings.ToUpper(r.Method)
host := r.Host
remote := r.RemoteAddr
forward := r.Header.Get("X-Forwarded-For")
remote := sanitize(r.RemoteAddr)
forward := forwarded(r.Header.Get("Forwarded"))
if forward == "" {
forward = sanitize(leftmost(r.Header.Get("X-Forwarded-For")))
}
if forward == "" {
forward = sanitize(r.Header.Get("X-Real-IP"))
}
reference := r.Header.Get("Referer")
agent := r.Header.Get("User-Agent")
ua := useragent.Parse(agent)
Expand All @@ -85,3 +113,67 @@ func Origins(r *http.Request) *Origin {
Reference: reference,
}
}

// leftmost returns the first comma-separated token of a header value with
// surrounding whitespace stripped, or "" when the input is empty.
func leftmost(header string) string {
if i := strings.Index(header, ","); i >= 0 {
header = header[:i]
}
return strings.TrimSpace(header)
}

// forwarded parses an RFC 7239 Forwarded header and returns the leftmost
// usable "for=" value with surrounding quotes and any port stripped. It
// returns "" when the header is absent, malformed, or contains only
// redacted values (the literal "unknown" or any value beginning with "_").
func forwarded(header string) string {
if header == "" {
return ""
}
for _, entry := range strings.Split(header, ",") {
entry = strings.TrimSpace(entry)
var value string
var found bool
for _, param := range strings.Split(entry, ";") {
param = strings.TrimSpace(param)
if !strings.HasPrefix(param, "for=") {
continue
}
value = strings.TrimPrefix(param, "for=")
found = true
break
}
if !found {
continue
}
// Strip surrounding double quotes, per RFC 7239.
if len(value) >= 2 && value[0] == '"' && value[len(value)-1] == '"' {
value = value[1 : len(value)-1]
}
// Treat redacted tokens as missing so callers transparently fall
// through to the next source (X-Forwarded-For, X-Real-IP, RemoteAddr).
if value == "unknown" || strings.HasPrefix(value, "_") {
continue
}
return sanitize(value)
}
return ""
}

// sanitize returns the host portion of an address, stripping any trailing
// port. It accepts "host:port", "[ipv6]:port", and bare bracketed IPv6
// addresses. If no port can be detected the input is returned unchanged.
func sanitize(address string) string {
if address == "" {
return ""
}
if host, _, err := net.SplitHostPort(address); err == nil {
return host
}
// Bare bracketed IPv6, e.g. "[2001:db8::1]" with no port.
if len(address) >= 2 && address[0] == '[' && address[len(address)-1] == ']' {
return address[1 : len(address)-1]
}
return address
}
Loading