Subject: [PATCH links] Add X-Real-IP header for internal API relays so AuditLogs record the correct IP address.

From: Peter Sanchez <[email-masked]>
Date: Mon, 28 Apr 2025 14:53:23 -0600

Fixes: https://todo.code.netlandish.com/~netlandish/links/109
---
 client.go  | 14 +++++++++++++-
 helpers.go |  3 +--
 2 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/client.go b/client.go
index caeabcc..62f1733 100644
--- a/client.go
+++ b/client.go
@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 	"net/http"
+	"net/url"
 	"strings"
 	"time"
 
@@ -74,13 +75,24 @@ func Execute(ctx context.Context, op *gqlclient.Operation, result any) error {
 
 	token := grant.Encode(ctx)
 	trans.AddHeader("Authorization", fmt.Sprintf("Internal %s", token))
+
+	ourl, err := url.Parse(origin)
+	if err == nil {
+		if ourl.Host == "127.0.0.1" || ourl.Host == "localhost" {
+			ip := IPForContext(ctx)
+			if ip != "" {
+				trans.AddHeader("X-Real-IP", IPForContext(ctx))
+			}
+		}
+	}
+
 	httpClient = &http.Client{
 		Transport: trans,
 		Timeout:   30 * time.Second,
 	}
 
 	client = gqlclient.New(origin, httpClient)
-	err := client.Execute(ctx, op, &result)
+	err = client.Execute(ctx, op, &result)
 	if err != nil {
 		if graphErrors, ok := err.(interface{ Unwrap() []error }); ok {
 			errs := graphErrors.Unwrap()
diff --git a/helpers.go b/helpers.go
index 4e944c0..a2fbc3d 100644
--- a/helpers.go
+++ b/helpers.go
@@ -6,7 +6,6 @@ import (
 	"database/sql"
 	"encoding/json"
 	"encoding/xml"
-	"errors"
 	"fmt"
 	"html/template"
 	"io"
@@ -1193,7 +1192,7 @@ func IPContext(ctx context.Context, ip string) context.Context {
 func IPForContext(ctx context.Context) string {
 	ip, ok := ctx.Value(IPCtxKey).(string)
 	if !ok {
-		panic(errors.New("Invalid IP context"))
+		return ""
 	}
 	return ip
 }
-- 
2.47.2