Skip to content

Commit f1dda52

Browse files
authored
Implement transport that will forward X-Access-Key header (#47)
1 parent aabeeec commit f1dda52

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

access_key.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@ import (
44
"context"
55
"errors"
66
"fmt"
7+
"net/http"
78
"strings"
89

910
"crypto/rand"
1011
"encoding/binary"
1112

13+
"github.com/go-chi/transport"
1214
"github.com/goware/base64"
1315
"github.com/jxskiss/base62"
1416
)
@@ -57,6 +59,18 @@ func GetAccessKeyPrefix(accessKey string) string {
5759
return strings.Join(parts[:len(parts)-1], Separator)
5860
}
5961

62+
func ForwardAccessKeyTransport(next http.RoundTripper) http.RoundTripper {
63+
return transport.RoundTripFunc(func(req *http.Request) (resp *http.Response, err error) {
64+
r := transport.CloneRequest(req)
65+
66+
if accessKey, ok := GetAccessKey(req.Context()); ok {
67+
r.Header.Set(HeaderAccessKey, accessKey)
68+
}
69+
70+
return next.RoundTrip(r)
71+
})
72+
}
73+
6074
type Encoding interface {
6175
Version() byte
6276
Encode(ctx context.Context, projectID uint64) string

access_key_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package authcontrol_test
22

33
import (
44
"context"
5+
"net/http"
6+
"net/http/httptest"
57
"testing"
68

79
"github.com/0xsequence/authcontrol"
@@ -57,3 +59,34 @@ func TestDecode(t *testing.T) {
5759
accessKey := authcontrol.GenerateAccessKey(ctx, 237)
5860
t.Log("=> k", accessKey, "| prefix =>", authcontrol.GetAccessKeyPrefix(accessKey))
5961
}
62+
63+
func TestForwardAccessKeyTransport(t *testing.T) {
64+
// Create a test server that captures the request headers
65+
var capturedHeaders http.Header
66+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
67+
capturedHeaders = r.Header.Clone()
68+
w.WriteHeader(http.StatusOK)
69+
}))
70+
defer server.Close()
71+
72+
// Create context with access key
73+
accessKey := "test-access-key-123"
74+
ctx := authcontrol.WithAccessKey(context.Background(), accessKey)
75+
76+
// Create HTTP client with ForwardAccessKeyTransport
77+
client := &http.Client{
78+
Transport: authcontrol.ForwardAccessKeyTransport(http.DefaultTransport),
79+
}
80+
81+
// Create request with the context
82+
req, err := http.NewRequestWithContext(ctx, "GET", server.URL, nil)
83+
require.NoError(t, err)
84+
85+
// Make the request
86+
resp, err := client.Do(req)
87+
require.NoError(t, err)
88+
defer resp.Body.Close()
89+
90+
// Verify the access key header was set
91+
require.Equal(t, accessKey, capturedHeaders.Get(authcontrol.HeaderAccessKey))
92+
}

0 commit comments

Comments
 (0)