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
23 changes: 23 additions & 0 deletions bridge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -983,3 +983,26 @@ func TestNewHTTPServer_BoundsEveryPhase(t *testing.T) {
t.Errorf("short bound: header=%v read=%v, want 1s for both", short.ReadHeaderTimeout, short.ReadTimeout)
}
}

func TestBuildSyslogStripsControlChars(t *testing.T) {
ts := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
got := buildSyslog(13, ts, "h", "app", "a\x1b[2Jb\x00c\td\x7fe")
want := "<13>1 2026-01-02T03:04:05.000Z h app - - - a [2Jb c d e"
if got != want {
t.Errorf("buildSyslog =\n %q\nwant\n %q", got, want)
}
}

// A request that is waiting for the forwarder must return once its context
// ends, rather than queue behind a busy connection forever.
func TestForwarderSendHonoursContextWhileBusy(t *testing.T) {
f := newForwarder("tcp", "127.0.0.1:1", false, time.Second)
f.gate <- struct{}{}

ctx, cancel := context.WithCancel(context.Background())
cancel()
err := f.send(ctx, []byte("x"))
if !errors.Is(err, context.Canceled) {
t.Fatalf("send error = %v, want one wrapping context.Canceled", err)
}
}
35 changes: 31 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ package main

import (
"context"
"crypto/sha256"
"crypto/subtle"
"crypto/tls"
"errors"
Expand Down Expand Up @@ -212,7 +213,7 @@ func (s *server) handle(w http.ResponseWriter, r *http.Request) {
return
}
if s.authHeader != "" &&
subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte(s.authHeader)) != 1 {
!authMatches(r.Header.Get("Authorization"), s.authHeader) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
Expand All @@ -238,20 +239,36 @@ func (s *server) handle(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}

// authMatches compares the presented Authorization header with the configured
// value by SHA-256 digest, so the comparison time does not reveal the expected
// token's length.
func authMatches(got, want string) bool {
g := sha256.Sum256([]byte(got))
w := sha256.Sum256([]byte(want))
return subtle.ConstantTimeCompare(g[:], w[:]) == 1
}

// buildSyslog renders one RFC 5424 message:
//
// <PRI>1 TIMESTAMP HOSTNAME APP-NAME PROCID MSGID STRUCTURED-DATA MSG
//
// PROCID, MSGID and STRUCTURED-DATA are nil ("-"); MSG carries the JSON body
// collapsed to a single line so it stays one syslog record.
// collapsed to a single line so it stays one syslog record. Every control
// character (C0, DEL and C1) in the body is replaced by a space, so a body
// cannot inject terminal escapes or extra records.
func buildSyslog(pri int, ts time.Time, host, app, msg string) string {
if host == "" {
host = "-"
}
if app == "" {
app = "-"
}
msg = strings.NewReplacer("\n", " ", "\r", " ").Replace(msg)
msg = strings.Map(func(r rune) rune {
if r < 0x20 || r == 0x7f || (r >= 0x80 && r <= 0x9f) {
return ' '
}
return r
}, msg)
return fmt.Sprintf("<%d>1 %s %s %s - - - %s",
pri, ts.UTC().Format("2006-01-02T15:04:05.000Z07:00"), host, app, msg)
}
Expand Down Expand Up @@ -280,12 +297,16 @@ type forwarder struct {
// certificate instead of the system root pool.
tlsConfig *tls.Config

// gate is a one-slot semaphore taken before mu so a waiting request gives up
// when its context ends instead of queuing forever behind a hung collector.
gate chan struct{}

mu sync.Mutex
conn net.Conn
}

func newForwarder(network, addr string, useTLS bool, dialTimeout time.Duration) *forwarder {
return &forwarder{network: network, addr: addr, useTLS: useTLS, dialTimeout: dialTimeout}
return &forwarder{network: network, addr: addr, useTLS: useTLS, dialTimeout: dialTimeout, gate: make(chan struct{}, 1)}
}

func (f *forwarder) dial(ctx context.Context) error {
Expand All @@ -312,6 +333,12 @@ func (f *forwarder) dial(ctx context.Context) error {
}

func (f *forwarder) send(ctx context.Context, frame []byte) error {
select {
case f.gate <- struct{}{}:
case <-ctx.Done():
return fmt.Errorf("wait for syslog connection: %w", ctx.Err())
}
defer func() { <-f.gate }()
f.mu.Lock()
defer f.mu.Unlock()
if f.conn != nil && !f.alive() {
Expand Down
4 changes: 2 additions & 2 deletions specs.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ Single flat package (`main`): `main.go` (relay + config + server logic), `bridge
- Forwards the received JSON body verbatim (schema-agnostic; does not parse, validate, or understand audit events)
- Prefers TCP over UDP for audit/compliance trails (UDP has no delivery confirmation; TCP surfaces a dead collector as a 502)
- Connection reuse: lazily dials once, then reuses; before each TCP write a short read probe (5 ms) checks whether the collector has closed the connection, and the bridge redials if it has; on write error, closes and reconnects once before surfacing the error. The probe is best-effort, not a delivery guarantee: a collector close whose FIN/RST lands after the probe goes unnoticed, and one record may then be written into the dead connection (reported as `204`: written to connection, best effort); the next write detects the close and reconnects, returning `204` on successful retry or `502` if the retry fails. Syslog framing has no acknowledgement, so this cannot be closed without a different transport
- Write deadline per frame (5s default) prevents a collector that accepts but does not drain from blocking indefinitely and wedging the handler behind the connection mutex
- RFC 5424 compliance: formats message as `<PRI>1 TIMESTAMP HOSTNAME APP-NAME PROCID MSGID STRUCTURED-DATA MSG`; collapses embedded newlines/CRs to spaces so each syslog record is one line; PROCID, MSGID, STRUCTURED-DATA are "-"
- Write deadline per frame (5s default) prevents a collector that accepts but does not drain from blocking indefinitely and wedging the handler behind the connection mutex; a request waiting for that mutex gives up when its request context ends (the wait is cancelled with the request)
- RFC 5424 compliance: formats message as `<PRI>1 TIMESTAMP HOSTNAME APP-NAME PROCID MSGID STRUCTURED-DATA MSG`; replaces every control character (C0, DEL and C1) in the body with a space, so each syslog record is one line and a body cannot inject terminal escapes or extra records; PROCID, MSGID, STRUCTURED-DATA are "-"
- `APP_NAME` and `SYSLOG_HOSTNAME` are validated at startup the same way `FACILITY`/`SEVERITY` are: each must be 1*max PRINTUSASCII (RFC 5424 %d33-126, no spaces or control bytes), APP-NAME capped at 48 bytes and HOSTNAME at 255 bytes, or `newServer` rejects the config before the process starts serving. An empty value is accepted and rendered as the RFC 5424 nil value `-`; when `SYSLOG_HOSTNAME` is empty the OS hostname is used instead, and an OS hostname that fails the same check (or can't be read) falls back to `-`

## Dependencies
Expand Down