Files
zeekayandHanzo Dev 53350699b6 deps(vendor): fold the krakend/lura module set into internal/
Every import in this module now resolves to github.com/hanzoai/gateway/v2.
The 34 github.com/krakend/* + github.com/luraproject/lura modules that
supplied the engine and its components are vendored under internal/ and
their 91 packages rewritten onto our own path.

Why fold rather than mirror into 34 hanzoai/* repos:

  - It removes the exposure outright. 34 rows leave 34 rows of go.sum to
    reason about; zero modules leave nothing. `go list -m all` and go.sum
    now contain no krakend/lura entry at all.
  - Cross-references cannot go wrong. 28 of the 34 import lura (97 files
    inside lura self-reference it). Mirroring means rewriting every one of
    those to our lura, and a single miss silently links a SECOND copy of
    lura into the binary. With one module that is structurally impossible.
  - It creates no duplicates. These are lura-coupled gateway glue with no
    consumer outside this binary; publishing 34 repos would be 34 new
    things to maintain for zero second caller. internal/ makes that
    guarantee mechanical — Go forbids importing it from outside this
    module, so none of it can become a competing public package. Verified
    no repo outside gateway imports any hanzoai/gateway/v2 subpackage.

Layout mirrors provenance so an upstream re-sync stays a diff:

  luraproject/lura/v2  -> internal/lura         (the engine, 20 pkgs)
  krakend/krakend-<x>  -> internal/plugin/<x>   (28 components)
  krakend/<x>          -> internal/pkg/<x>      (6 standalone libs)

This commit is PURELY MECHANICAL: 196 of the 197 vendored files are
byte-identical to their upstream original once the import rewrite is
applied. The single exception is bloomfilter's subpackage, which upstream
names `krakend` — the one package name that could not survive as-is; it
becomes internal/pkg/bloomfilter/register. Hand edits land separately in
the next commit so they are readable on their own.

Per `go mod vendor` semantics, dependencies' _test.go files are not
vendored. They test upstream code at a pinned version that we do not
modify, several cannot run at all from a module distribution (they need
TLS certs and compiled .so plugins upstream generates but never ships),
and one is a 100k-request stress test that exhausts the ephemeral port
range and fails every package running beside it. Fold integrity is proven
by the byte-diff above instead, which is the stronger check.

Preserved deliberately — each of these is behaviour, not branding:
  - the `github.com/devopsfaith/krakend*` extra_config namespace strings
    (35 of them). These are config-surface keys, not import paths;
    renaming one silently stops that component finding its config. The
    jose validator namespace backs `auth/validator` on 212 endpoints.
  - core.KrakendVersion / KrakendUserAgent / the X-KRAKEND consts, whose
    VALUES rebrand.go overwrites — that seam is unchanged.
  - the KRAKEND_ koanf env prefix (a hardcoded upstream const).
  - every vendored module's LICENSE (34 files, Apache-2.0/MIT).

The Makefile/CI -X paths move with the engine. An -X naming a symbol that
does not exist is silently ignored by the linker, so a stale path here
would have shipped an "undefined" version in the backend User-Agent and
X-Api-Version with a perfectly green build. Verified live:
`gateway version` reports 2.13.0, not undefined.

Verification (GOWORK=off CGO_ENABLED=0, both tag modes):
  go build ./...              OK      go build -tags legacy ./...   OK
  go vet ./...                clean   go vet -tags legacy ./...     clean
  go test ./...               6/6 ok  go test -tags legacy          5/5 ok
  tests/ integration harness  47 fixtures pass
  gateway check -c configs/{hanzo,lux}/gateway.json  -> Syntax OK!
  go list -m all | grep -iE 'krakend|lura'  -> empty
  go mod verify -> all modules verified

Co-authored-by: Hanzo Dev <[email protected]>
2026-07-25 14:57:19 -07:00

248 lines
8.0 KiB
Go

// SPDX-License-Identifier: Apache-2.0
package gin
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/textproto"
"net/url"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/hanzoai/gateway/v2/internal/lura/config"
"github.com/hanzoai/gateway/v2/internal/lura/core"
"github.com/hanzoai/gateway/v2/internal/lura/logging"
"github.com/hanzoai/gateway/v2/internal/lura/transport/http/server"
)
const Namespace = "github_com/luraproject/lura/router/gin"
type EngineOptions struct {
Logger logging.Logger
Writer io.Writer
Formatter gin.LogFormatter
Health <-chan string
}
// NewEngine returns an initialized gin engine
func NewEngine(cfg config.ServiceConfig, opt EngineOptions) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
if cfg.Debug {
opt.Logger.Debug(logPrefix, "Debug enabled")
}
engine := gin.New()
engine.RedirectTrailingSlash = true
engine.RedirectFixedPath = true
engine.HandleMethodNotAllowed = true
engine.ContextWithFallback = true
var paths []string
ginOptions := engineConfiguration{}
if v, ok := cfg.ExtraConfig[Namespace]; ok {
if b, err := json.Marshal(v); err == nil {
if err := json.Unmarshal(b, &ginOptions); err == nil {
if ginOptions.DisableRedirectTrailingSlash != nil {
engine.RedirectTrailingSlash = !*ginOptions.DisableRedirectTrailingSlash
}
if ginOptions.DisableRedirectFixedPath != nil {
engine.RedirectFixedPath = !*ginOptions.DisableRedirectFixedPath
}
if ginOptions.DisableHandleMethodNotAllowed != nil {
engine.HandleMethodNotAllowed = !*ginOptions.DisableHandleMethodNotAllowed
}
if ginOptions.ForwardedByClientIP != nil {
engine.ForwardedByClientIP = *ginOptions.ForwardedByClientIP
}
if len(ginOptions.RemoteIPHeaders) > 0 {
engine.RemoteIPHeaders = ginOptions.RemoteIPHeaders
for k, h := range engine.RemoteIPHeaders {
engine.RemoteIPHeaders[k] = textproto.CanonicalMIMEHeaderKey(h)
}
}
if len(ginOptions.TrustedProxies) > 0 {
engine.SetTrustedProxies(ginOptions.TrustedProxies)
}
engine.AppEngine = ginOptions.AppEngine
engine.MaxMultipartMemory = ginOptions.MaxMultipartMemory
engine.RemoveExtraSlash = ginOptions.RemoveExtraSlash
engine.UseH2C = ginOptions.UseH2C
paths = ginOptions.LoggerSkipPaths
returnErrorMsg = ginOptions.ReturnErrorMsg
if ginOptions.ObfuscateVersionHeader {
core.KrakendHeaderValue = "Version undefined"
}
}
}
}
engine.NoRoute(func(c *gin.Context) {
c.Header(server.CompleteResponseHeaderName, server.HeaderIncompleteResponseValue)
})
if !ginOptions.DisableAccessLog {
engine.Use(
gin.LoggerWithConfig(gin.LoggerConfig{
Output: opt.Writer,
SkipPaths: paths,
Formatter: opt.Formatter,
}),
)
}
engine.Use(gin.Recovery())
if !ginOptions.DisablePathDecoding {
engine.Use(paramChecker())
}
if !ginOptions.DisableHealthEndpoint {
path := "/__health"
if ginOptions.HealthPath != "" {
path = ginOptions.HealthPath
}
engine.GET(path, healthEndpoint(opt.Health))
}
return engine
}
func healthEndpoint(health <-chan string) func(*gin.Context) {
mu := new(sync.RWMutex)
reports := map[string]string{}
go func() {
for name := range health {
mu.Lock()
reports[name] = time.Now().String()
mu.Unlock()
}
}()
return func(c *gin.Context) {
mu.RLock()
defer mu.RUnlock()
c.JSON(200, gin.H{"status": "ok", "agents": reports, "now": time.Now().String()})
}
}
func paramChecker() gin.HandlerFunc {
return func(c *gin.Context) {
for _, param := range c.Params {
s, err := url.PathUnescape(param.Value)
if err != nil {
c.Status(http.StatusBadRequest)
ErrorResponseWriter(c, fmt.Errorf("error: %s", err))
c.Abort()
return
}
if s != param.Value || strings.Contains(s, "?") || strings.Contains(s, "#") {
c.Status(http.StatusBadRequest)
ErrorResponseWriter(c, errors.New("error: encoded url params"))
c.Abort()
return
}
}
}
}
type engineConfiguration struct {
// Disables automatic redirection if the current route can't be matched but a
// handler for the path with (without) the trailing slash exists.
// For example if /foo/ is requested but a route only exists for /foo, the
// client is redirected to /foo with http status code 301 for GET requests
// and 307 for all other request methods.
DisableRedirectTrailingSlash *bool `json:"disable_redirect_trailing_slash"`
// If enabled, the router tries to fix the current request path, if no
// handle is registered for it.
// First superfluous path elements like ../ or // are removed.
// Afterwards the router does a case-insensitive lookup of the cleaned path.
// If a handle can be found for this route, the router makes a redirection
// to the corrected path with status code 301 for GET requests and 307 for
// all other request methods.
// For example /FOO and /..//Foo could be redirected to /foo.
// RedirectTrailingSlash is independent of this option.
DisableRedirectFixedPath *bool `json:"disable_redirect_fixed_path"`
// If enabled, the router checks if another method is allowed for the
// current route, if the current request can not be routed.
// If this is the case, the request is answered with 'Method Not Allowed'
// and HTTP status code 405.
// If no other Method is allowed, the request is delegated to the NotFound
// handler.
DisableHandleMethodNotAllowed *bool `json:"disable_handle_method_not_allowed"`
// If enabled, client IP will be parsed from the request's headers that
// match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was
// fetched, it falls back to the IP obtained from
// `(*gin.Context).Request.RemoteAddr`.
ForwardedByClientIP *bool `json:"forwarded_by_client_ip"`
// List of headers used to obtain the client IP when
// `(*gin.Engine).ForwardedByClientIP` is `true` and
// `(*gin.Context).Request.RemoteAddr` is matched by at least one of the
// network origins of `(*gin.Engine).TrustedProxies`.
RemoteIPHeaders []string `json:"remote_ip_headers"`
// List of network origins (IPv4 addresses, IPv4 CIDRs, IPv6 addresses or
// IPv6 CIDRs) from which to trust request's headers that contain
// alternative client IP when `(*gin.Engine).ForwardedByClientIP` is
// `true`.
TrustedProxies []string `json:"trusted_proxies"`
// #726 #755 If enabled, it will trust some headers starting with
// 'X-AppEngine...' for better integration with that PaaS.
AppEngine bool `json:"app_engine"`
// Value of 'maxMemory' param that is given to http.Request's ParseMultipartForm
// method call.
MaxMultipartMemory int64 `json:"max_multipart_memory"`
// RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes.
// See the PR #1817 and issue #1644
RemoveExtraSlash bool `json:"remove_extra_slash"`
// LoggerSkipPaths defines the set of path to avoid logging
LoggerSkipPaths []string `json:"logger_skip_paths"`
// AutoOptions enables the autogenerated OPTIONS endpoint for all the registered paths
AutoOptions bool `json:"auto_options"`
// ReturnErrorMsg flags if the error msg should be returned to the client as response body
ReturnErrorMsg bool `json:"return_error_msg"`
// DisableHealthEndpoint marks if the health check endpoint should be exposed
DisableHealthEndpoint bool `json:"disable_health"`
// HealthPath allows users to define a custom path for the health check endpoint
HealthPath string `json:"health_path"`
// DisableAccessLog blocks the injection of the router logger
DisableAccessLog bool `json:"disable_access_log"`
// DisablePathDecoding disables automatic validation of the url params looking for url encoded ones.
// For example if /foo/..%252Fbar is requested and this flag is set to false, the router will
// reject the request with http status code 400.
DisablePathDecoding bool `json:"disable_path_decoding"`
// ObfuscateVersionHeader flags if the version header returned by the router should replace the actual
// version with the value "undefined"
ObfuscateVersionHeader bool `json:"hide_version_header"`
// UseH2C enable h2c support.
UseH2C bool `json:"use_h2c"`
}
var returnErrorMsg bool