Skip to content

Commit 56e79db

Browse files
committed
enhanced auth
1 parent 3fa8b0a commit 56e79db

File tree

49 files changed

+579
-528
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+579
-528
lines changed

cmd/options/auth.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ type (
99
Auth struct {
1010
HMAC string `short:"A" long:"jwtHMAC" description:"HMACKeyPath|EncKey" `
1111
RSA string `short:"J" long:"jwtRSA" description:"PublicKeyPath|EncKey" `
12-
Firebase string `short:"F" long:"fsecret" description:"Firebase secrets" `
12+
Firebase string `short:"F" long:"firebase" description:"Firebase secrets" `
13+
Cognito string `short:"T" long:"cognito" description:"Cognito pollId|secrets" `
1314
Custom CustomAuth `short:"E" long:"customAuth" description:"Custom AuthSQL" `
1415
}
1516
)

cmd/options/ext.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ type (
2121
Module struct {
2222
GitRepository *string `short:"g" long:"gitrepo" description:"git module repo"`
2323
GitFolder *string
24-
GitPrivate *string `short:"T" long:"gitprivate" description:"git private"`
24+
GitPrivate *string `short:"I" long:"gitprivate" description:"git private"`
2525
Name string `short:"n" long:"name" description:"module name" `
2626
}
2727

e2e/local/regression/cases/003_oauth/vendor_auth.sql

+3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
/* {"URI":"auth/vendors/{vendorID}"} */
22

3+
34
#set($_ = $Jwt<string>(Header/Authorization).WithCodec(JwtClaim).WithStatusCode(401))
5+
46
#set($_ = $Authorization /* !!403
57
SELECT Authorized /* {"DataType":"bool"} */
68
FROM (SELECT IS_VENDOR_AUTHORIZED($Jwt.UserID, $vendorID) AS Authorized) t
79
WHERE Authorized
810
*/)
11+
912
SELECT vendor.*,
1013
products.* EXCEPT VENDOR_ID
1114
FROM (SELECT CAST($Jwt.FirstName AS CHAR) AS FIRST_NAME, t.* FROM VENDOR t WHERE t.ID = $vendorID ) vendor

gateway/authorizer.go

-7
This file was deleted.

gateway/config.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"github.com/viant/afs"
88
"github.com/viant/datly/gateway/runtime/meta"
99
"github.com/viant/datly/repository/path"
10-
"github.com/viant/datly/service/auth"
10+
"github.com/viant/datly/service/auth/config"
1111
"github.com/viant/datly/service/auth/secret"
1212
"github.com/viant/toolbox"
1313
"gopkg.in/yaml.v3"
@@ -36,7 +36,7 @@ type (
3636
MaxJobs int
3737
UseCacheFS bool
3838
SyncFrequencyMs int
39-
auth.Config
39+
config.Config
4040
Meta meta.Config
4141
AutoDiscovery *bool
4242
ChangeDetection *ChangeDetection

gateway/option.go

+3-18
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,13 @@ import (
1111

1212
type options struct {
1313
config *Config
14-
authorizer Authorizer
14+
initializers []func(config *Config, fs *embed.FS) error
1515
extensions *extension.Registry
1616
metrics *gmetric.Service
1717
repository *repository.Service
1818
statusHandler http.Handler
1919
embedFs *embed.FS
2020
configURL string
21-
authProvider func(config *Config, fs *embed.FS) (Authorizer, error)
2221
}
2322

2423
func newOptions(ctx context.Context, opts ...Option) (*options, error) {
@@ -46,13 +45,6 @@ func newOptions(ctx context.Context, opts ...Option) (*options, error) {
4645
result.config = &Config{}
4746
}
4847

49-
if result.authorizer == nil && result.authProvider != nil {
50-
var err error
51-
if result.authorizer, err = result.authProvider(result.config, result.embedFs); err != nil {
52-
return nil, err
53-
}
54-
}
55-
5648
return result, nil
5749
}
5850

@@ -66,13 +58,6 @@ func WithConfig(config *Config) Option {
6658
}
6759
}
6860

69-
// WithAuthorizer sets an authorizer
70-
func WithAuthorizer(authorizer Authorizer) Option {
71-
return func(o *options) {
72-
o.authorizer = authorizer
73-
}
74-
}
75-
7661
// WithExtensions sets an extension registry
7762
func WithExtensions(registry *extension.Registry) Option {
7863
return func(o *options) {
@@ -107,9 +92,9 @@ func WithStatusHandler(handler http.Handler) Option {
10792
}
10893
}
10994

110-
func WithAuthProvider(authProvider func(config *Config, fs *embed.FS) (Authorizer, error)) Option {
95+
func WithInitializer(initializer func(config *Config, fs *embed.FS) error) Option {
11196
return func(o *options) {
112-
o.authProvider = authProvider
97+
o.initializers = append(o.initializers, initializer)
11398
}
11499
}
115100

gateway/router.go

+6-15
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ type (
3838
OpenAPIInfo openapi3.Info
3939
metrics *gmetric.Service
4040
statusHandler http.Handler
41-
authorizer Authorizer
4241
paths []*contract.Path
4342
}
4443

@@ -66,12 +65,11 @@ func (a *AvailableRoutesError) Error() string {
6665
}
6766

6867
// NewRouter creates new router
69-
func NewRouter(ctx context.Context, components *repository.Service, config *Config, metrics *gmetric.Service, statusHandler http.Handler, authorizer Authorizer) (*Router, error) {
68+
func NewRouter(ctx context.Context, components *repository.Service, config *Config, metrics *gmetric.Service, statusHandler http.Handler) (*Router, error) {
7069
r := &Router{
7170
config: config,
7271
metrics: metrics,
7372
statusHandler: statusHandler,
74-
authorizer: authorizer,
7573
repository: components,
7674
operator: operator.New(),
7775
apiKeyMatcher: newApiKeyMatcher(config.APIKeys),
@@ -101,9 +99,6 @@ func (r *Router) handle(writer http.ResponseWriter, request *http.Request) {
10199
r.handleErrorCode(writer, http.StatusInternalServerError, err)
102100
return
103101
}
104-
if !r.authorizeRequestIfNeeded(writer, request) {
105-
return
106-
}
107102
errStatusCode, err := r.handleRoute(writer, request)
108103
r.handleErrorCode(writer, errStatusCode, err)
109104
}
@@ -154,7 +149,10 @@ func (r *Router) HandleJob(ctx context.Context, aJob *async.Job) error {
154149
request := &http.Request{Method: aJob.Method, URL: URL, RequestURI: aPath.URI}
155150
unmarshal := aComponent.UnmarshalFunc(request)
156151
locatorOptions := append(aComponent.LocatorOptions(request, hstate.NewForm(), unmarshal))
157-
aSession := session.New(aComponent.View, session.WithLocatorOptions(locatorOptions...), session.WithOperate(r.operator.Operate))
152+
aSession := session.New(aComponent.View,
153+
session.WithAuth(r.repository.Auth()),
154+
session.WithLocatorOptions(locatorOptions...),
155+
session.WithOperate(r.operator.Operate))
158156
if err != nil {
159157
return err
160158
}
@@ -267,13 +265,6 @@ func (r *Router) ensureRequestURL(request *http.Request) error {
267265
return err
268266
}
269267

270-
func (r *Router) authorizeRequestIfNeeded(writer http.ResponseWriter, request *http.Request) bool {
271-
if r.authorizer == nil {
272-
return true
273-
}
274-
return r.authorizer.Authorize(writer, request)
275-
}
276-
277268
func (r *Router) PreCacheables(ctx context.Context, method string, uri string) ([]*view.View, error) {
278269
route, err := r.Match(method, uri, nil)
279270
if err != nil {
@@ -342,7 +333,7 @@ func (r *Router) newMatcher(ctx context.Context) (*matcher.Matcher, []*contract.
342333
if err != nil {
343334
return nil, nil, fmt.Errorf("failed to locate component provider: %w", err)
344335
}
345-
routes = append(routes, r.NewRouteHandler(router.New(aPath, provider, r.repository.Registry())))
336+
routes = append(routes, r.NewRouteHandler(router.New(aPath, provider, r.repository.Registry(), r.repository.Auth())))
346337
if aPath.Cors != nil {
347338
optionsPaths[aPath.URI] = append(optionsPaths[aPath.URI], aPath)
348339
}

gateway/router/handler.go

+9-2
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"github.com/viant/datly/repository/contract"
1919
"github.com/viant/datly/repository/path"
2020
"github.com/viant/datly/service"
21+
"github.com/viant/datly/service/auth"
2122
"github.com/viant/datly/service/executor/expand"
2223
"github.com/viant/datly/service/operator"
2324
"github.com/viant/datly/service/session"
@@ -47,6 +48,7 @@ type (
4748
Provider *repository.Provider
4849
dispatcher *operator.Service
4950
registry *repository.Registry
51+
auth *auth.Service
5052
}
5153
)
5254

@@ -80,12 +82,13 @@ func (r *Handler) AuthorizeRequest(request *http.Request, aPath *path.Path) erro
8082
return nil
8183
}
8284

83-
func New(aPath *path.Path, provider *repository.Provider, registry *repository.Registry) *Handler {
85+
func New(aPath *path.Path, provider *repository.Provider, registry *repository.Registry, authService *auth.Service) *Handler {
8486
ret := &Handler{
8587
Path: aPath,
8688
Provider: provider,
8789
dispatcher: operator.New(),
8890
registry: registry,
91+
auth: authService,
8992
}
9093
return ret
9194
}
@@ -358,7 +361,11 @@ func (r *Handler) handleComponent(ctx context.Context, request *http.Request, aC
358361
anOperator := operator.New()
359362
unmarshal := aComponent.UnmarshalFunc(request)
360363
locatorOptions := append(aComponent.LocatorOptions(request, hstate.NewForm(), unmarshal))
361-
aSession := session.New(aComponent.View, session.WithLocatorOptions(locatorOptions...), session.WithRegistry(r.registry), session.WithOperate(anOperator.Operate))
364+
aSession := session.New(aComponent.View,
365+
session.WithAuth(r.auth),
366+
session.WithLocatorOptions(locatorOptions...),
367+
session.WithRegistry(r.registry),
368+
session.WithOperate(anOperator.Operate))
362369
err := aSession.InitKinds(state.KindComponent, state.KindHeader, state.KindRequestBody, state.KindForm, state.KindQuery)
363370
if err != nil {
364371
return nil, err

gateway/runtime/apigw/handler.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ func HandleHttpRequest(writer http.ResponseWriter, apiRequest *adapter.Request)
2727
if err != nil {
2828
return err
2929
}
30-
httpRequest := apiRequest.Request(service.JWTSigner)
30+
httpRequest := apiRequest.Request(service.JWTSigner())
3131
service.LogInitTimeIfNeeded(now, writer)
3232
service.ServeHTTP(writer, httpRequest)
3333
service.LogInitTimeIfNeeded(now, writer)

gateway/runtime/serverless/service.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ func GetService() (*gateway.Service, error) {
2323
return nil, fmt.Errorf("config was emty")
2424
}
2525
service, err := gateway.Singleton(context.Background(),
26-
gateway.WithAuthProvider(func(config *gateway.Config, fs *embed.FS) (gateway.Authorizer, error) {
26+
gateway.WithInitializer(func(config *gateway.Config, fs *embed.FS) error {
2727
return jwt.Init(gatewayConfig, fs)
2828
}),
2929
gateway.WithConfigURL(configURL),

gateway/runtime/standalone/auth.go

-13
This file was deleted.

gateway/runtime/standalone/option.go

+1-5
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@ package standalone
22

33
import (
44
"context"
5-
"embed"
65
"github.com/viant/datly/gateway"
7-
"github.com/viant/datly/service/auth/jwt"
86
)
97

108
// Options represents standalone options
@@ -28,9 +26,7 @@ func NewOptions(ctx context.Context, opts ...Option) (*Options, error) {
2826
for _, opt := range opts {
2927
opt(options)
3028
}
31-
options.options = append(options.options, gateway.WithAuthProvider(func(config *gateway.Config, fs *embed.FS) (gateway.Authorizer, error) {
32-
return jwt.Init(config, fs)
33-
}))
29+
3430
if options.config != nil {
3531
options.options = append(options.options, gateway.WithConfig(options.config.Config))
3632
} else if options.ConfigURL != "" {

gateway/runtime/standalone/server.go

-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import (
1717
type Server struct {
1818
http.Server
1919
Service *gateway.Service
20-
auth gateway.Authorizer
2120
useSingleton *bool //true by default
2221
}
2322

gateway/service.go

+15-13
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,15 @@ type (
2929
metrics *gmetric.Service
3030
mainRouter *Router
3131
cancelFn context.CancelFunc
32-
JWTSigner *signer.Service
3332
mux sync.RWMutex
3433
statusHandler http.Handler
35-
authorizer Authorizer
3634
}
3735
)
3836

37+
func (r *Service) JWTSigner() *signer.Service {
38+
return r.repository.JWTSigner()
39+
}
40+
3941
func (r *Service) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
4042
aRouter, writer, ok := r.router(writer)
4143
if !ok {
@@ -56,7 +58,7 @@ func (r *Service) router(writer http.ResponseWriter) (*Router, http.ResponseWrit
5658
}
5759

5860
func (r *Service) Router() (*Router, bool) {
59-
if err := r.syncChanges(context.Background(), r.metrics, r.statusHandler, r.authorizer, false); err != nil {
61+
if err := r.syncChanges(context.Background(), r.metrics, r.statusHandler, false); err != nil {
6062
fmt.Printf("[ERROR] failed to sync changes: %v\n", err)
6163
}
6264
mainRouter := r.mainRouter
@@ -89,20 +91,27 @@ func New(ctx context.Context, opts ...Option) (*Service, error) {
8991
}
9092
componentRepository := options.repository
9193
if componentRepository == nil {
94+
9295
componentRepository, err = repository.New(ctx, repository.WithComponentURL(aConfig.RouteURL),
9396
repository.WithResourceURL(aConfig.DependencyURL),
9497
repository.WithPluginURL(aConfig.PluginsURL),
9598
repository.WithApiPrefix(aConfig.APIPrefix),
9699
repository.WithExtensions(options.extensions),
97100
repository.WithMetrics(options.metrics),
101+
repository.WithJWTSigner(aConfig.JwtSigner),
102+
repository.WithJWTVerifier(aConfig.JWTValidator),
103+
repository.WithCognitoAuth(aConfig.Cognito),
104+
repository.WithFirebaseAuth(aConfig.Firebase),
105+
repository.WithCustomAuth(aConfig.Custom),
106+
repository.WithDependencyURL(aConfig.DependencyURL),
98107
repository.WithRefreshFrequency(aConfig.SyncFrequency()),
99108
repository.WithDispatcher(dispatcher.New),
100109
)
101110
if err != nil {
102111
return nil, fmt.Errorf("failed to initialise component service: %w", err)
103112
}
104113
}
105-
mainRouter, err := NewRouter(ctx, componentRepository, aConfig, options.metrics, options.statusHandler, options.authorizer)
114+
mainRouter, err := NewRouter(ctx, componentRepository, aConfig, options.metrics, options.statusHandler)
106115
if err != nil {
107116
return nil, err
108117
}
@@ -113,15 +122,8 @@ func New(ctx context.Context, opts ...Option) (*Service, error) {
113122
mux: sync.RWMutex{},
114123
fs: fs,
115124
statusHandler: options.statusHandler,
116-
authorizer: options.authorizer,
117125
mainRouter: mainRouter,
118126
}
119-
if aConfig.JwtSigner != nil {
120-
srv.JWTSigner = signer.New(aConfig.JwtSigner)
121-
if err = srv.JWTSigner.Init(context.Background()); err != nil {
122-
return nil, err
123-
}
124-
}
125127
go srv.watchAsyncJob(context.Background())
126128
fmt.Printf("[INFO]: started gatweay after: %s\n", time.Since(start))
127129
return srv, err
@@ -189,7 +191,7 @@ func CommonURL(URLs ...string) (string, error) {
189191
return base, nil
190192
}
191193

192-
func (r *Service) syncChanges(ctx context.Context, metrics *gmetric.Service, statusHandler http.Handler, authorizer Authorizer, isFirst bool) error {
194+
func (r *Service) syncChanges(ctx context.Context, metrics *gmetric.Service, statusHandler http.Handler, isFirst bool) error {
193195
changed, err := r.repository.SyncChanges(ctx)
194196
if err != nil {
195197
return err
@@ -199,7 +201,7 @@ func (r *Service) syncChanges(ctx context.Context, metrics *gmetric.Service, sta
199201
}
200202
start := time.Now()
201203
fmt.Printf("[INFO] detected resources changes, rebuilding routers\n")
202-
mainRouter, err := NewRouter(ctx, r.repository, r.Config, metrics, statusHandler, authorizer)
204+
mainRouter, err := NewRouter(ctx, r.repository, r.Config, metrics, statusHandler)
203205
if err != nil {
204206
return err
205207
}

0 commit comments

Comments
 (0)