- add trusted proxy settings, migration, API, and UI - derive client addresses from X-Forwarded-For behind trusted hops - enforce delivery policy for listener batches and record denials
82 lines
2.0 KiB
Go
82 lines
2.0 KiB
Go
package governance
|
|
|
|
import (
|
|
"context"
|
|
json "encoding/json/v2"
|
|
"fmt"
|
|
"net/netip"
|
|
"strings"
|
|
)
|
|
|
|
// maxTrustedProxies limits the size of the proxy list, which is read on every
|
|
// webhook delivery.
|
|
const maxTrustedProxies = 64
|
|
|
|
// normalizeProxies trims each entry and checks that it is an address or a CIDR
|
|
// range. A bare address means that one host.
|
|
func normalizeProxies(entries []string) ([]string, error) {
|
|
if len(entries) > maxTrustedProxies {
|
|
return nil, ErrInvalidIdentity
|
|
}
|
|
out := make([]string, 0, len(entries))
|
|
for _, entry := range entries {
|
|
entry = strings.TrimSpace(entry)
|
|
if entry == "" {
|
|
continue
|
|
}
|
|
prefix, err := parseProxy(entry)
|
|
if err != nil {
|
|
return nil, ErrInvalidIdentity
|
|
}
|
|
out = append(out, prefix.String())
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func parseProxy(entry string) (netip.Prefix, error) {
|
|
if strings.Contains(entry, "/") {
|
|
return netip.ParsePrefix(entry)
|
|
}
|
|
addr, err := netip.ParseAddr(entry)
|
|
if err != nil {
|
|
return netip.Prefix{}, err
|
|
}
|
|
return netip.PrefixFrom(addr, addr.BitLen()), nil
|
|
}
|
|
|
|
// TrustedProxies returns the reverse proxies whose X-Forwarded-For header
|
|
// webhook intake uses as the client address.
|
|
func (m *Module) TrustedProxies(ctx context.Context) ([]netip.Prefix, error) {
|
|
settings, err := m.AuthenticationSettings(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]netip.Prefix, 0, len(settings.TrustedProxies))
|
|
for _, entry := range settings.TrustedProxies {
|
|
prefix, err := parseProxy(entry)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("stored trusted proxy %q: %w", entry, err)
|
|
}
|
|
out = append(out, prefix)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func encodeProxies(entries []string) ([]byte, error) {
|
|
if entries == nil {
|
|
entries = []string{}
|
|
}
|
|
return json.Marshal(entries)
|
|
}
|
|
|
|
func decodeProxies(raw []byte) ([]string, error) {
|
|
entries := []string{}
|
|
if len(raw) == 0 {
|
|
return entries, nil
|
|
}
|
|
if err := json.Unmarshal(raw, &entries); err != nil {
|
|
return nil, fmt.Errorf("read trusted proxies: %w", err)
|
|
}
|
|
return entries, nil
|
|
}
|