Skip to content
Draft
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
12 changes: 12 additions & 0 deletions auth/authorizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ func NewAuthorizer(appCtx context.Context, logger *zerolog.Logger, projectId str
if err != nil {
return nil, err
}
case common.AuthTypeForwardedClientId:
if cfg.ForwardedClientId == nil {
return nil, common.NewErrInvalidConfig("forwardedClientId strategy config is nil")
}
strategy, err = NewForwardedClientIdStrategy(cfg.ForwardedClientId)
if err != nil {
return nil, err
}
if len(cfg.ForwardedClientId.AllowedProxies) == 0 {
logger.Warn().Str("projectId", projectId).Str("header", cfg.ForwardedClientId.Header).
Msg("forwardedClientId auth strategy accepts its header from any peer; set allowedProxies to the proxy that sets it")
}
default:
return nil, common.NewErrInvalidConfig(fmt.Sprintf("unknown auth strategy type: %s", cfg.Type))
}
Expand Down
62 changes: 60 additions & 2 deletions auth/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,21 @@ import (
"errors"
"net/http"
"net/url"
"path"
"strings"

"github.com/erpc/erpc/common"
)

func NewPayloadFromHttp(method string, remoteAddr string, headers http.Header, args url.Values) (*AuthPayload, error) {
// NewPayloadFromHttp extracts auth signals from an HTTP (or WebSocket
// upgrade) request. credentialPath is the request path when the server does
// not use it for routing (a domain alias preselects project, architecture and
// chain), and "" otherwise; see PathSegmentSecret.
func NewPayloadFromHttp(method string, remoteAddr string, headers http.Header, args url.Values, credentialPath string) (*AuthPayload, error) {
ap := &AuthPayload{
Method: method,
Method: method,
Headers: headers,
RemoteAddr: remoteAddr,
}

if token := args.Get("token"); token != "" { // deprecated
Expand Down Expand Up @@ -79,6 +86,23 @@ func NewPayloadFromHttp(method string, remoteAddr string, headers http.Header, a
}
}

// Secondary secret locations, for clients and gateways that use the
// common "API key" conventions. They fill ap.Secret only when no other
// secret was found and never change ap.Type, so they do not alter which
// strategies a request without one of the credentials above reaches:
// a request that only carries an X-Api-Key header still reaches a
// network strategy, and only secret/database strategies that list the
// location in additionalLocations pick the key up.
if ap.Secret == nil {
if apikey := args.Get("apikey"); apikey != "" {
ap.Secret = &SecretPayload{Value: apikey, Location: common.SecretLocationApikeyQuery}
} else if apikey := firstNonEmptyHeader(headers, "X-Api-Key", "Apikey"); apikey != "" {
ap.Secret = &SecretPayload{Value: apikey, Location: common.SecretLocationApikeyHeader}
} else if pathSecret := PathSegmentSecret(credentialPath); pathSecret != "" {
ap.Secret = &SecretPayload{Value: pathSecret, Location: common.SecretLocationPath}
}
}

// Default to network strategy when no other auth signals are present.
if ap.Type == "" {
ap.Type = common.AuthTypeNetwork
Expand All @@ -87,6 +111,40 @@ func NewPayloadFromHttp(method string, remoteAddr string, headers http.Header, a
return ap, nil
}

// reservedPathSegments are single-segment paths eRPC serves itself; they are
// never treated as a secret.
var reservedPathSegments = map[string]struct{}{
"admin": {},
"healthcheck": {},
"metrics": {},
}

// PathSegmentSecret returns the secret carried as the only path segment of
// requestPath ("/<secret>" or "/<secret>/"), or "" when the path is empty,
// "/", has several segments, or is a reserved endpoint.
func PathSegmentSecret(requestPath string) string {
if requestPath == "" {
return ""
}
seg := strings.TrimPrefix(path.Clean("/"+requestPath), "/")
if seg == "" || strings.Contains(seg, "/") {
return ""
}
if _, reserved := reservedPathSegments[seg]; reserved {
return ""
}
return seg
}

func firstNonEmptyHeader(headers http.Header, names ...string) string {
for _, name := range names {
if v := strings.TrimSpace(headers.Get(name)); v != "" {
return v
}
}
return ""
}

func normalizeSiweMessage(msg string) string {
decoded, err := base64.StdEncoding.DecodeString(msg)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions auth/http_payload_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ func TestNewPayloadFromHttp_SignalPrecedence(t *testing.T) {
if args == nil {
args = url.Values{}
}
ap, err := NewPayloadFromHttp("eth_call", "10.0.0.1:1234", headers, args)
ap, err := NewPayloadFromHttp("eth_call", "10.0.0.1:1234", headers, args, "")
require.NoError(t, err)
assert.Equal(t, "eth_call", ap.Method)
assert.Equal(t, tc.wantType, ap.Type)
Expand Down Expand Up @@ -169,7 +169,7 @@ func TestNewPayloadFromHttp_MalformedBasicAuth(t *testing.T) {
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ap, err := NewPayloadFromHttp("eth_call", "", http.Header{"Authorization": {tc.value}}, url.Values{})
ap, err := NewPayloadFromHttp("eth_call", "", http.Header{"Authorization": {tc.value}}, url.Values{}, "")
require.Error(t, err)
assert.Nil(t, ap)
})
Expand Down
200 changes: 200 additions & 0 deletions auth/http_secret_locations_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
package auth

import (
"context"
"net/http"
"net/url"
"testing"

"github.com/erpc/erpc/common"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestPathSegmentSecret(t *testing.T) {
cases := map[string]string{
"": "",
"/": "",
"/my-secret-key": "my-secret-key",
"/my-secret-key/": "my-secret-key",
"my-secret-key": "my-secret-key",
"/main/evm/1": "",
"/main/evm": "",
"/a/../b": "b",
"/a/..": "",
"/admin": "",
"/healthcheck": "",
"/metrics": "",
"/admin/": "",
}
for in, want := range cases {
assert.Equal(t, want, PathSegmentSecret(in), "path %q", in)
}
}

func TestNewPayloadFromHttp_SecondarySecretLocations(t *testing.T) {
t.Run("apikey query", func(t *testing.T) {
ap, err := NewPayloadFromHttp("eth_blockNumber", "", http.Header{}, url.Values{"apikey": {"q-key"}}, "")
require.NoError(t, err)
require.NotNil(t, ap.Secret)
assert.Equal(t, "q-key", ap.Secret.Value)
assert.Equal(t, common.AuthTypeNetwork, ap.Type, "secondary locations must not change the payload type")
})

for _, name := range []string{"X-Api-Key", "x-api-key", "apikey"} {
t.Run("header "+name, func(t *testing.T) {
h := http.Header{}
h.Set(name, "h-key")
ap, err := NewPayloadFromHttp("eth_blockNumber", "", h, url.Values{}, "")
require.NoError(t, err)
require.NotNil(t, ap.Secret)
assert.Equal(t, "h-key", ap.Secret.Value)
assert.Equal(t, common.AuthTypeNetwork, ap.Type)
})
}

t.Run("path segment", func(t *testing.T) {
ap, err := NewPayloadFromHttp("eth_blockNumber", "", http.Header{}, url.Values{}, "/my-secret-key")
require.NoError(t, err)
require.NotNil(t, ap.Secret)
assert.Equal(t, "my-secret-key", ap.Secret.Value)
assert.Equal(t, common.AuthTypeNetwork, ap.Type)
})

t.Run("multi-segment and reserved paths are ignored", func(t *testing.T) {
for _, p := range []string{"/main/evm/1", "/admin", "/healthcheck", "/metrics", "/"} {
ap, err := NewPayloadFromHttp("eth_blockNumber", "", http.Header{}, url.Values{}, p)
require.NoError(t, err)
assert.Nil(t, ap.Secret, "path %s", p)
assert.Equal(t, common.AuthTypeNetwork, ap.Type, "path %s", p)
}
})

t.Run("precedence: primary locations win, then query, header, path", func(t *testing.T) {
h := http.Header{}
h.Set("X-Api-Key", "h-key")
h.Set("X-ERPC-Secret-Token", "primary")
ap, err := NewPayloadFromHttp("eth_blockNumber", "", h, url.Values{"apikey": {"q-key"}}, "/path-key")
require.NoError(t, err)
assert.Equal(t, "primary", ap.Secret.Value)
assert.Equal(t, common.AuthTypeSecret, ap.Type)

h.Del("X-ERPC-Secret-Token")
ap, err = NewPayloadFromHttp("eth_blockNumber", "", h, url.Values{"apikey": {"q-key"}}, "/path-key")
require.NoError(t, err)
assert.Equal(t, "q-key", ap.Secret.Value)

ap, err = NewPayloadFromHttp("eth_blockNumber", "", h, url.Values{}, "/path-key")
require.NoError(t, err)
assert.Equal(t, "h-key", ap.Secret.Value)
})

t.Run("a bearer token keeps the jwt type and the api key is still available", func(t *testing.T) {
h := http.Header{}
h.Set("Authorization", "Bearer a.b.c")
h.Set("X-Api-Key", "h-key")
ap, err := NewPayloadFromHttp("eth_blockNumber", "", h, url.Values{}, "")
require.NoError(t, err)
assert.Equal(t, common.AuthTypeJwt, ap.Type)
require.NotNil(t, ap.Jwt)
require.NotNil(t, ap.Secret)
assert.Equal(t, "h-key", ap.Secret.Value)
})
}

func TestAuthRegistry_SecondarySecretLocations(t *testing.T) {
secretOnly := newSecretAuthRegistry(t, &common.AuthConfig{Strategies: []*common.AuthStrategyConfig{{
Type: common.AuthTypeSecret,
Secret: &common.SecretStrategyConfig{Id: "backend", Value: "backend-token", AdditionalLocations: []common.SecretLocation{
common.SecretLocationApikeyQuery, common.SecretLocationApikeyHeader, common.SecretLocationPath,
}},
}}})

h := http.Header{}
h.Set("X-Api-Key", "backend-token")
for name, ap := range map[string]func() (*AuthPayload, error){
"query": func() (*AuthPayload, error) {
return NewPayloadFromHttp("m", "", http.Header{}, url.Values{"apikey": {"backend-token"}}, "")
},
"header": func() (*AuthPayload, error) { return NewPayloadFromHttp("m", "", h, url.Values{}, "") },
"path": func() (*AuthPayload, error) {
return NewPayloadFromHttp("m", "", http.Header{}, url.Values{}, "/backend-token")
},
} {
t.Run(name, func(t *testing.T) {
p, err := ap()
require.NoError(t, err)
user, err := secretOnly.Authenticate(context.Background(), nil, "m", p)
require.NoError(t, err)
assert.Equal(t, "backend", user.Id)
})
}

t.Run("locations are off unless listed", func(t *testing.T) {
standardOnly := newSecretAuthRegistry(t, &common.AuthConfig{Strategies: []*common.AuthStrategyConfig{{
Type: common.AuthTypeSecret,
Secret: &common.SecretStrategyConfig{Id: "backend", Value: "backend-token"},
}}})
headerOnly := newSecretAuthRegistry(t, &common.AuthConfig{Strategies: []*common.AuthStrategyConfig{{
Type: common.AuthTypeSecret,
Secret: &common.SecretStrategyConfig{Id: "backend", Value: "backend-token", AdditionalLocations: []common.SecretLocation{
common.SecretLocationApikeyHeader,
}},
}}})

p, err := NewPayloadFromHttp("m", "", h, url.Values{}, "")
require.NoError(t, err)
_, err = standardOnly.Authenticate(context.Background(), nil, "m", p)
require.Error(t, err)
user, err := headerOnly.Authenticate(context.Background(), nil, "m", p)
require.NoError(t, err)
assert.Equal(t, "backend", user.Id)

p, err = NewPayloadFromHttp("m", "", http.Header{}, url.Values{}, "/backend-token")
require.NoError(t, err)
_, err = headerOnly.Authenticate(context.Background(), nil, "m", p)
require.Error(t, err)

// The standard locations keep working without additionalLocations.
p, err = NewPayloadFromHttp("m", "", http.Header{}, url.Values{"secret": {"backend-token"}}, "")
require.NoError(t, err)
user, err = standardOnly.Authenticate(context.Background(), nil, "m", p)
require.NoError(t, err)
assert.Equal(t, "backend", user.Id)
})

t.Run("wrong path secret is rejected", func(t *testing.T) {
p, err := NewPayloadFromHttp("m", "", http.Header{}, url.Values{}, "/wrong")
require.NoError(t, err)
_, err = secretOnly.Authenticate(context.Background(), nil, "m", p)
require.Error(t, err)
})

t.Run("network strategy still serves requests that only carry a secondary secret", func(t *testing.T) {
networkOnly := newSecretAuthRegistry(t, &common.AuthConfig{Strategies: []*common.AuthStrategyConfig{{
Type: common.AuthTypeNetwork,
Network: &common.NetworkStrategyConfig{AllowLocalhost: true},
}}})
p, err := NewPayloadFromHttp("m", "", h, url.Values{}, "")
require.NoError(t, err)
req := common.NewNormalizedRequest(nil)
req.SetClientIP("127.0.0.1")
user, err := networkOnly.Authenticate(context.Background(), req, "m", p)
require.NoError(t, err)
assert.Equal(t, "127.0.0.1", user.Id)
})
}

func TestStrategySupports_AdditionalLocations(t *testing.T) {
headerKey := &AuthPayload{Type: common.AuthTypeNetwork, Secret: &SecretPayload{Value: "k", Location: common.SecretLocationApikeyHeader}}
standard := &AuthPayload{Type: common.AuthTypeSecret, Secret: &SecretPayload{Value: "k"}}
headerOnly := []common.SecretLocation{common.SecretLocationApikeyHeader}

assert.False(t, NewSecretStrategy(&common.SecretStrategyConfig{Value: "k"}).Supports(headerKey))
assert.True(t, NewSecretStrategy(&common.SecretStrategyConfig{Value: "k", AdditionalLocations: headerOnly}).Supports(headerKey))
assert.True(t, NewSecretStrategy(&common.SecretStrategyConfig{Value: "k"}).Supports(standard))

assert.False(t, (&DatabaseStrategy{cfg: &common.DatabaseStrategyConfig{}}).Supports(headerKey))
assert.True(t, (&DatabaseStrategy{cfg: &common.DatabaseStrategyConfig{AdditionalLocations: headerOnly}}).Supports(headerKey))
assert.True(t, (&DatabaseStrategy{cfg: &common.DatabaseStrategyConfig{}}).Supports(standard))
}
33 changes: 32 additions & 1 deletion auth/payload.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,49 @@
package auth

import "github.com/erpc/erpc/common"
import (
"net/http"

"github.com/erpc/erpc/common"
)

type AuthPayload struct {
Method string
Type common.AuthType
Secret *SecretPayload
Jwt *JwtPayload
Siwe *SiwePayload

// Headers and RemoteAddr carry the raw transport context for strategies
// that need it rather than a credential extracted up front (e.g.
// forwardedClientId reads its configured header and checks the direct
// peer). They are only populated for HTTP and WebSocket requests.
Headers http.Header
RemoteAddr string
}

// This payload is used by both "secret" and "database" strategies
type SecretPayload struct {
Value string
// Location is where an additional-location secret was found (see
// common.SecretLocation); "" for the standard locations.
Location common.SecretLocation
}

// secretAccepted reports whether ap carries a secret from a location a
// strategy accepts: a standard one, or one of its additional locations.
func secretAccepted(ap *AuthPayload, additional []common.SecretLocation) bool {
if ap.Secret == nil {
return false
}
if ap.Secret.Location == "" {
return true
}
for _, l := range additional {
if l == ap.Secret.Location {
return true
}
}
return false
}

type JwtPayload struct {
Expand Down
2 changes: 1 addition & 1 deletion auth/strategy_database.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ func NewDatabaseStrategy(appCtx context.Context, logger *zerolog.Logger, cfg *co
}

func (s *DatabaseStrategy) Supports(ap *AuthPayload) bool {
return ap.Type == common.AuthTypeSecret || ap.Type == common.AuthTypeDatabase
return ap.Type == common.AuthTypeSecret || ap.Type == common.AuthTypeDatabase || secretAccepted(ap, s.cfg.AdditionalLocations)
}

func (s *DatabaseStrategy) Authenticate(ctx context.Context, req *common.NormalizedRequest, ap *AuthPayload) (*common.User, error) {
Expand Down
Loading
Loading