Skip to content
Open
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
56 changes: 56 additions & 0 deletions goplugin/mw_go_plugin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,62 @@ func TestGoPluginResponseHook(t *testing.T) {
})
}

func TestGoPlugin_IPBindingPerKey(t *testing.T) {
ts := gateway.StartTest(nil)
defer ts.Close()

ts.Gw.BuildAndLoadAPI(func(spec *gateway.APISpec) {
spec.APIID = "plugin_api_ip_binding"
spec.Proxy.ListenPath = "/goplugin-ip-binding"
spec.UseKeylessAccess = false
spec.UseStandardAuth = true
spec.CustomMiddleware = apidef.MiddlewareSection{
Driver: apidef.GoPluginDriver,
PostKeyAuth: []apidef.MiddlewareDefinition{
{
Name: "MyPluginIPBindingPostKeyAuth",
Path: goPluginFilename(),
},
},
}
})

// Create a key with allowed_ips in meta_data
key := gateway.CreateSession(ts.Gw, func(s *user.SessionState) {
if s.MetaData == nil {
s.MetaData = make(map[string]interface{})
}
s.MetaData["allowed_ips"] = "1.2.3.4"
})

t.Run("Allowed IP", func(t *testing.T) {
ts.Run(t, []test.TestCase{
{
Path: "/goplugin-ip-binding/hit",
Headers: map[string]string{
"Authorization": key,
"X-Forwarded-For": "1.2.3.4",
},
Code: http.StatusOK,
},
}...)
})

t.Run("Disallowed IP", func(t *testing.T) {
ts.Run(t, []test.TestCase{
{
Path: "/goplugin-ip-binding/hit",
Headers: map[string]string{
"Authorization": key,
"X-Forwarded-For": "5.6.7.8",
},
Code: http.StatusForbidden,
BodyMatch: "IP not allowed",
},
}...)
})
}

func TestGoPluginPerPathSingleFile(t *testing.T) {

ts := gateway.StartTest(nil)
Expand Down
23 changes: 23 additions & 0 deletions test/goplugins/test_goplugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,26 @@

ctx.SetSession(r, session, true)
}

func MyPluginIPBindingPostKeyAuth(rw http.ResponseWriter, r *http.Request) {
session := ctx.GetSession(r)
if session == nil {
rw.WriteHeader(http.StatusUnauthorized)
return
}

// Extract allowed_ips from session.MetaData
allowedIPs, ok := session.MetaData["allowed_ips"].(string)
if !ok {
// No IP binding configured, allow request
return
}

// Compare with client IP (e.g., from X-Forwarded-For or r.RemoteAddr)
clientIP := r.Header.Get("X-Forwarded-For")
if clientIP != allowedIPs {
rw.WriteHeader(http.StatusForbidden)
rw.Write([]byte("IP not allowed"))

Check failure on line 249 in test/goplugins/test_goplugin.go

View workflow job for this annotation

GitHub Actions / lint

Error return value of `rw.Write` is not checked (errcheck)
return
}
}
Loading