Merge pull request #438 from beckn/feature/core
added updated code for core wiring
This commit is contained in:
@@ -7,13 +7,13 @@ import (
|
||||
decrypter "github.com/beckn/beckn-onix/pkg/plugin/implementation/decrypter"
|
||||
)
|
||||
|
||||
// DecrypterProvider implements the definition.DecrypterProvider interface.
|
||||
type DecrypterProvider struct{}
|
||||
// decrypterProvider implements the definition.decrypterProvider interface.
|
||||
type decrypterProvider struct{}
|
||||
|
||||
// New creates a new Decrypter instance using the provided configuration.
|
||||
func (dp DecrypterProvider) New(ctx context.Context, config map[string]string) (definition.Decrypter, func() error, error) {
|
||||
func (dp decrypterProvider) New(ctx context.Context, config map[string]string) (definition.Decrypter, func() error, error) {
|
||||
return decrypter.New(ctx)
|
||||
}
|
||||
|
||||
// Provider is the exported symbol that the plugin manager will look for.
|
||||
var Provider definition.DecrypterProvider = DecrypterProvider{}
|
||||
var Provider = decrypterProvider{}
|
||||
|
||||
@@ -25,7 +25,7 @@ func TestDecrypterProviderSuccess(t *testing.T) {
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
provider := DecrypterProvider{}
|
||||
provider := decrypterProvider{}
|
||||
decrypter, cleanup, err := provider.New(tt.ctx, tt.config)
|
||||
|
||||
// Check error.
|
||||
|
||||
@@ -7,12 +7,12 @@ import (
|
||||
"github.com/beckn/beckn-onix/pkg/plugin/implementation/encrypter"
|
||||
)
|
||||
|
||||
// EncrypterProvider implements the definition.EncrypterProvider interface.
|
||||
type EncrypterProvider struct{}
|
||||
// encrypterProvider implements the definition.encrypterProvider interface.
|
||||
type encrypterProvider struct{}
|
||||
|
||||
func (ep EncrypterProvider) New(ctx context.Context, config map[string]string) (definition.Encrypter, func() error, error) {
|
||||
func (ep encrypterProvider) New(ctx context.Context, config map[string]string) (definition.Encrypter, func() error, error) {
|
||||
return encrypter.New(ctx)
|
||||
}
|
||||
|
||||
// Provider is the exported symbol that the plugin manager will look for.
|
||||
var Provider definition.EncrypterProvider = EncrypterProvider{}
|
||||
var Provider = encrypterProvider{}
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestEncrypterProviderSuccess(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Create provider and encrypter.
|
||||
provider := EncrypterProvider{}
|
||||
provider := encrypterProvider{}
|
||||
encrypter, cleanup, err := provider.New(tt.ctx, tt.config)
|
||||
if err != nil {
|
||||
t.Fatalf("EncrypterProvider.New() error = %v", err)
|
||||
|
||||
@@ -5,17 +5,20 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
requestpreprocessor "github.com/beckn/beckn-onix/pkg/plugin/implementation/requestPreProcessor"
|
||||
"github.com/beckn/beckn-onix/pkg/plugin/implementation/reqpreprocessor"
|
||||
)
|
||||
|
||||
type provider struct{}
|
||||
|
||||
func (p provider) New(ctx context.Context, c map[string]string) (func(http.Handler) http.Handler, error) {
|
||||
config := &requestpreprocessor.Config{}
|
||||
if contextKeysStr, ok := c["ContextKeys"]; ok {
|
||||
config := &reqpreprocessor.Config{}
|
||||
if contextKeysStr, ok := c["contextKeys"]; ok {
|
||||
config.ContextKeys = strings.Split(contextKeysStr, ",")
|
||||
}
|
||||
return requestpreprocessor.NewUUIDSetter(config)
|
||||
if role, ok := c["role"]; ok {
|
||||
config.Role = role
|
||||
}
|
||||
return reqpreprocessor.NewPreProcessor(config)
|
||||
}
|
||||
|
||||
var Provider = provider{}
|
||||
@@ -34,7 +34,7 @@ func TestProviderNew(t *testing.T) {
|
||||
{
|
||||
name: "With Check Keys",
|
||||
config: map[string]string{
|
||||
"ContextKeys": "message_id,transaction_id",
|
||||
"contextKeys": "message_id,transaction_id",
|
||||
},
|
||||
expectedError: false,
|
||||
expectedStatus: http.StatusOK,
|
||||
@@ -1,4 +1,4 @@
|
||||
package requestpreprocessor
|
||||
package reqpreprocessor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -9,24 +9,26 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/beckn/beckn-onix/pkg/log"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Config holds the configuration settings for the application.
|
||||
type Config struct {
|
||||
ContextKeys []string
|
||||
Role string
|
||||
ContextKeys []string // ContextKeys is a list of context keys used for request processing.
|
||||
Role string // Role specifies the role of the entity (e.g., subscriber, gateway).
|
||||
}
|
||||
|
||||
type becknRequest struct {
|
||||
Context map[string]any `json:"context"`
|
||||
}
|
||||
|
||||
type contextKeyType string
|
||||
|
||||
const contextKey = "context"
|
||||
const subscriberIDKey contextKeyType = "subscriber_id"
|
||||
const subscriberIDKey = "subscriber_id"
|
||||
|
||||
func NewUUIDSetter(cfg *Config) (func(http.Handler) http.Handler, error) {
|
||||
// NewPreProcessor creates a middleware that processes incoming HTTP requests by extracting
|
||||
// and modifying the request context based on the provided configuration.
|
||||
func NewPreProcessor(cfg *Config) (func(http.Handler) http.Handler, error) {
|
||||
if err := validateConfig(cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -34,6 +36,7 @@ func NewUUIDSetter(cfg *Config) (func(http.Handler) http.Handler, error) {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var req becknRequest
|
||||
ctx := r.Context()
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
http.Error(w, "Failed to decode request body", http.StatusBadRequest)
|
||||
return
|
||||
@@ -49,11 +52,15 @@ func NewUUIDSetter(cfg *Config) (func(http.Handler) http.Handler, error) {
|
||||
case "bpp":
|
||||
subID = req.Context["bpp_id"]
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), subscriberIDKey, subID)
|
||||
if subID != nil {
|
||||
log.Debugf(ctx, "adding subscriberId to request:%s, %v", subscriberIDKey, subID)
|
||||
// TODO: Add a ContextKey type in model and use it here instead of raw context key.
|
||||
ctx = context.WithValue(ctx, subscriberIDKey, subID)
|
||||
}
|
||||
for _, key := range cfg.ContextKeys {
|
||||
value := uuid.NewString()
|
||||
updatedValue := update(req.Context, key, value)
|
||||
ctx = context.WithValue(ctx, contextKeyType(key), updatedValue)
|
||||
ctx = context.WithValue(ctx, key, updatedValue)
|
||||
}
|
||||
reqData := map[string]any{"context": req.Context}
|
||||
updatedBody, _ := json.Marshal(reqData)
|
||||
@@ -1,4 +1,4 @@
|
||||
package requestpreprocessor
|
||||
package reqpreprocessor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -52,7 +52,7 @@ func TestNewUUIDSetterSuccessCases(t *testing.T) {
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
middleware, err := NewUUIDSetter(tt.config)
|
||||
middleware, err := NewPreProcessor(tt.config)
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error while creating middleware: %v", err)
|
||||
}
|
||||
@@ -148,7 +148,7 @@ func TestNewUUIDSetterErrorCases(t *testing.T) {
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
middleware, err := NewUUIDSetter(tt.config)
|
||||
middleware, err := NewPreProcessor(tt.config)
|
||||
if tt.config == nil {
|
||||
if err == nil {
|
||||
t.Error("Expected an error for nil config, but got none")
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
definition "github.com/beckn/beckn-onix/pkg/plugin/definition"
|
||||
router "github.com/beckn/beckn-onix/pkg/plugin/implementation/router"
|
||||
"github.com/beckn/beckn-onix/pkg/plugin/definition"
|
||||
"github.com/beckn/beckn-onix/pkg/plugin/implementation/router"
|
||||
)
|
||||
|
||||
// RouterProvider provides instances of Router.
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
definition "github.com/beckn/beckn-onix/pkg/plugin/definition"
|
||||
"github.com/beckn/beckn-onix/pkg/model"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
@@ -26,7 +26,7 @@ type routingConfig struct {
|
||||
|
||||
// Router implements Router interface.
|
||||
type Router struct {
|
||||
rules map[string]map[string]map[string]*definition.Route // domain -> version -> endpoint -> route
|
||||
rules map[string]map[string]map[string]*model.Route // domain -> version -> endpoint -> route
|
||||
}
|
||||
|
||||
// RoutingRule represents a single routing rule.
|
||||
@@ -61,7 +61,7 @@ func New(ctx context.Context, config *Config) (*Router, func() error, error) {
|
||||
return nil, nil, fmt.Errorf("config cannot be nil")
|
||||
}
|
||||
router := &Router{
|
||||
rules: make(map[string]map[string]map[string]*definition.Route),
|
||||
rules: make(map[string]map[string]map[string]*model.Route),
|
||||
}
|
||||
|
||||
// Load rules at bootup
|
||||
@@ -71,30 +71,6 @@ func New(ctx context.Context, config *Config) (*Router, func() error, error) {
|
||||
return router, nil, nil
|
||||
}
|
||||
|
||||
// parseTargetURL parses a URL string into a url.URL object with strict validation
|
||||
func parseTargetURL(urlStr string) (*url.URL, error) {
|
||||
if urlStr == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
parsed, err := url.Parse(urlStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid URL '%s': %w", urlStr, err)
|
||||
}
|
||||
|
||||
// Enforce scheme requirement
|
||||
if parsed.Scheme == "" {
|
||||
return nil, fmt.Errorf("URL '%s' must include a scheme (http/https)", urlStr)
|
||||
}
|
||||
|
||||
// Optionally validate scheme is http or https
|
||||
if parsed.Scheme != "https" {
|
||||
return nil, fmt.Errorf("URL '%s' must use https scheme", urlStr)
|
||||
}
|
||||
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
// LoadRules reads and parses routing rules from the YAML configuration file.
|
||||
func (r *Router) loadRules(configPath string) error {
|
||||
if configPath == "" {
|
||||
@@ -117,41 +93,41 @@ func (r *Router) loadRules(configPath string) error {
|
||||
for _, rule := range config.RoutingRules {
|
||||
// Initialize domain map if not exists
|
||||
if _, ok := r.rules[rule.Domain]; !ok {
|
||||
r.rules[rule.Domain] = make(map[string]map[string]*definition.Route)
|
||||
r.rules[rule.Domain] = make(map[string]map[string]*model.Route)
|
||||
}
|
||||
|
||||
// Initialize version map if not exists
|
||||
if _, ok := r.rules[rule.Domain][rule.Version]; !ok {
|
||||
r.rules[rule.Domain][rule.Version] = make(map[string]*definition.Route)
|
||||
r.rules[rule.Domain][rule.Version] = make(map[string]*model.Route)
|
||||
}
|
||||
|
||||
// Add all endpoints for this rule
|
||||
for _, endpoint := range rule.Endpoints {
|
||||
var route *definition.Route
|
||||
var route *model.Route
|
||||
switch rule.TargetType {
|
||||
case targetTypePublisher:
|
||||
route = &definition.Route{
|
||||
route = &model.Route{
|
||||
TargetType: rule.TargetType,
|
||||
PublisherID: rule.Target.PublisherID,
|
||||
}
|
||||
case targetTypeURL:
|
||||
parsedURL, err := parseTargetURL(rule.Target.URL)
|
||||
parsedURL, err := url.Parse(rule.Target.URL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid URL in rule: %w", err)
|
||||
}
|
||||
route = &definition.Route{
|
||||
route = &model.Route{
|
||||
TargetType: rule.TargetType,
|
||||
URL: parsedURL,
|
||||
}
|
||||
case targetTypeBPP, targetTypeBAP:
|
||||
var parsedURL *url.URL
|
||||
if rule.Target.URL != "" {
|
||||
parsedURL, err = parseTargetURL(rule.Target.URL)
|
||||
parsedURL, err = url.Parse(rule.Target.URL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid URL in rule: %w", err)
|
||||
}
|
||||
}
|
||||
route = &definition.Route{
|
||||
route = &model.Route{
|
||||
TargetType: rule.TargetType,
|
||||
URL: parsedURL,
|
||||
}
|
||||
@@ -177,7 +153,7 @@ func validateRules(rules []routingRule) error {
|
||||
if rule.Target.URL == "" {
|
||||
return fmt.Errorf("invalid rule: url is required for targetType 'url'")
|
||||
}
|
||||
if _, err := parseTargetURL(rule.Target.URL); err != nil {
|
||||
if _, err := url.Parse(rule.Target.URL); err != nil {
|
||||
return fmt.Errorf("invalid URL - %s: %w", rule.Target.URL, err)
|
||||
}
|
||||
case targetTypePublisher:
|
||||
@@ -186,7 +162,7 @@ func validateRules(rules []routingRule) error {
|
||||
}
|
||||
case targetTypeBPP, targetTypeBAP:
|
||||
if rule.Target.URL != "" {
|
||||
if _, err := parseTargetURL(rule.Target.URL); err != nil {
|
||||
if _, err := url.Parse(rule.Target.URL); err != nil {
|
||||
return fmt.Errorf("invalid URL - %s defined in routing config for target type %s: %w", rule.Target.URL, rule.TargetType, err)
|
||||
}
|
||||
}
|
||||
@@ -199,8 +175,7 @@ func validateRules(rules []routingRule) error {
|
||||
}
|
||||
|
||||
// Route determines the routing destination based on the request context.
|
||||
func (r *Router) Route(ctx context.Context, url *url.URL, body []byte) (*definition.Route, error) {
|
||||
|
||||
func (r *Router) Route(ctx context.Context, url *url.URL, body []byte) (*model.Route, error) {
|
||||
// Parse the body to extract domain and version
|
||||
var requestBody struct {
|
||||
Context struct {
|
||||
@@ -244,32 +219,32 @@ func (r *Router) Route(ctx context.Context, url *url.URL, body []byte) (*definit
|
||||
}
|
||||
|
||||
// handleProtocolMapping handles both BPP and BAP routing with proper URL construction
|
||||
func handleProtocolMapping(route *definition.Route, requestURI, endpoint string) (*definition.Route, error) {
|
||||
uri := strings.TrimSpace(requestURI)
|
||||
var targetURL *url.URL
|
||||
if len(uri) != 0 {
|
||||
parsedURL, err := parseTargetURL(uri)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid %s URI - %s in request body for %s: %w", strings.ToUpper(route.TargetType), uri, endpoint, err)
|
||||
}
|
||||
targetURL = parsedURL
|
||||
}
|
||||
|
||||
// If no request URI, fall back to configured URL with endpoint appended
|
||||
if targetURL == nil {
|
||||
func handleProtocolMapping(route *model.Route, npURI, endpoint string) (*model.Route, error) {
|
||||
target := strings.TrimSpace(npURI)
|
||||
if len(target) == 0 {
|
||||
if route.URL == nil {
|
||||
return nil, fmt.Errorf("could not determine destination for endpoint '%s': neither request contained a %s URI nor was a default URL configured in routing rules", endpoint, strings.ToUpper(route.TargetType))
|
||||
}
|
||||
|
||||
targetURL = &url.URL{
|
||||
Scheme: route.URL.Scheme,
|
||||
Host: route.URL.Host,
|
||||
Path: path.Join(route.URL.Path, endpoint),
|
||||
}
|
||||
return &model.Route{
|
||||
TargetType: targetTypeURL,
|
||||
URL: &url.URL{
|
||||
Scheme: route.URL.Scheme,
|
||||
Host: route.URL.Host,
|
||||
Path: path.Join(route.URL.Path, endpoint),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
targetURL, err := url.Parse(target)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid %s URI - %s in request body for %s: %w", strings.ToUpper(route.TargetType), target, endpoint, err)
|
||||
}
|
||||
|
||||
return &definition.Route{
|
||||
return &model.Route{
|
||||
TargetType: targetTypeURL,
|
||||
URL: targetURL,
|
||||
URL: &url.URL{
|
||||
Scheme: targetURL.Scheme,
|
||||
Host: targetURL.Host,
|
||||
Path: path.Join(targetURL.Path, endpoint),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
definition "github.com/beckn/beckn-onix/pkg/plugin/definition"
|
||||
schemaValidator "github.com/beckn/beckn-onix/pkg/plugin/implementation/schemaValidator"
|
||||
"github.com/beckn/beckn-onix/pkg/plugin/definition"
|
||||
"github.com/beckn/beckn-onix/pkg/plugin/implementation/schemavalidator"
|
||||
)
|
||||
|
||||
// schemaValidatorProvider provides instances of schemaValidator.
|
||||
@@ -24,10 +24,10 @@ func (vp schemaValidatorProvider) New(ctx context.Context, config map[string]str
|
||||
}
|
||||
|
||||
// Create a new schemaValidator instance with the provided configuration
|
||||
return schemaValidator.New(ctx, &schemaValidator.Config{
|
||||
return schemavalidator.New(ctx, &schemavalidator.Config{
|
||||
SchemaDir: schemaDir,
|
||||
})
|
||||
}
|
||||
|
||||
// Provider is the exported symbol that the plugin manager will look for.
|
||||
var Provider definition.SchemaValidatorProvider = schemaValidatorProvider{}
|
||||
var Provider = schemaValidatorProvider{}
|
||||
@@ -1,4 +1,4 @@
|
||||
package schemaValidator
|
||||
package schemavalidator
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
response "github.com/beckn/beckn-onix/pkg/response"
|
||||
"github.com/beckn/beckn-onix/pkg/model"
|
||||
|
||||
"github.com/santhosh-tekuri/jsonschema/v6"
|
||||
)
|
||||
@@ -23,8 +23,8 @@ type payload struct {
|
||||
} `json:"context"`
|
||||
}
|
||||
|
||||
// SchemaValidator implements the Validator interface.
|
||||
type SchemaValidator struct {
|
||||
// schemaValidator implements the Validator interface.
|
||||
type schemaValidator struct {
|
||||
config *Config
|
||||
schemaCache map[string]*jsonschema.Schema
|
||||
}
|
||||
@@ -35,12 +35,12 @@ type Config struct {
|
||||
}
|
||||
|
||||
// New creates a new ValidatorProvider instance.
|
||||
func New(ctx context.Context, config *Config) (*SchemaValidator, func() error, error) {
|
||||
func New(ctx context.Context, config *Config) (*schemaValidator, func() error, error) {
|
||||
// Check if config is nil
|
||||
if config == nil {
|
||||
return nil, nil, fmt.Errorf("config cannot be nil")
|
||||
}
|
||||
v := &SchemaValidator{
|
||||
v := &schemaValidator{
|
||||
config: config,
|
||||
schemaCache: make(map[string]*jsonschema.Schema),
|
||||
}
|
||||
@@ -53,7 +53,7 @@ func New(ctx context.Context, config *Config) (*SchemaValidator, func() error, e
|
||||
}
|
||||
|
||||
// Validate validates the given data against the schema.
|
||||
func (v *SchemaValidator) Validate(ctx context.Context, url *url.URL, data []byte) error {
|
||||
func (v *schemaValidator) Validate(ctx context.Context, url *url.URL, data []byte) error {
|
||||
var payloadData payload
|
||||
err := json.Unmarshal(data, &payloadData)
|
||||
if err != nil {
|
||||
@@ -61,14 +61,14 @@ func (v *SchemaValidator) Validate(ctx context.Context, url *url.URL, data []byt
|
||||
}
|
||||
|
||||
// Extract domain, version, and endpoint from the payload and uri.
|
||||
cxt_domain := payloadData.Context.Domain
|
||||
cxtDomain := payloadData.Context.Domain
|
||||
version := payloadData.Context.Version
|
||||
version = fmt.Sprintf("v%s", version)
|
||||
|
||||
endpoint := path.Base(url.String())
|
||||
// ToDo Add debug log here
|
||||
fmt.Println("Handling request for endpoint:", endpoint)
|
||||
domain := strings.ToLower(cxt_domain)
|
||||
domain := strings.ToLower(cxtDomain)
|
||||
domain = strings.ReplaceAll(domain, ":", "_")
|
||||
|
||||
// Construct the schema file name.
|
||||
@@ -89,20 +89,20 @@ func (v *SchemaValidator) Validate(ctx context.Context, url *url.URL, data []byt
|
||||
// Handle schema validation errors
|
||||
if validationErr, ok := err.(*jsonschema.ValidationError); ok {
|
||||
// Convert validation errors into an array of SchemaValError
|
||||
var schemaErrors []response.Error
|
||||
var schemaErrors []model.Error
|
||||
for _, cause := range validationErr.Causes {
|
||||
// Extract the path and message from the validation error
|
||||
path := strings.Join(cause.InstanceLocation, ".") // JSON path to the invalid field
|
||||
message := cause.Error() // Validation error message
|
||||
|
||||
// Append the error to the schemaErrors array
|
||||
schemaErrors = append(schemaErrors, response.Error{
|
||||
schemaErrors = append(schemaErrors, model.Error{
|
||||
Paths: path,
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
// Return the array of schema validation errors
|
||||
return &response.SchemaValidationErr{Errors: schemaErrors}
|
||||
return &model.SchemaValidationErr{Errors: schemaErrors}
|
||||
}
|
||||
// Return a generic error for non-validation errors
|
||||
return fmt.Errorf("validation failed: %v", err)
|
||||
@@ -117,7 +117,7 @@ type ValidatorProvider struct{}
|
||||
|
||||
// Initialise initialises the validator provider by compiling all the JSON schema files
|
||||
// from the specified directory and storing them in a cache indexed by their schema filenames.
|
||||
func (v *SchemaValidator) initialise() error {
|
||||
func (v *schemaValidator) initialise() error {
|
||||
schemaDir := v.config.SchemaDir
|
||||
// Check if the directory exists and is accessible.
|
||||
info, err := os.Stat(schemaDir)
|
||||
@@ -1,4 +1,4 @@
|
||||
package schemaValidator
|
||||
package schemavalidator
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -272,7 +272,7 @@ func TestValidator_Initialise(t *testing.T) {
|
||||
}
|
||||
|
||||
config := &Config{SchemaDir: schemaDir}
|
||||
v := &SchemaValidator{
|
||||
v := &schemaValidator{
|
||||
config: config,
|
||||
schemaCache: make(map[string]*jsonschema.Schema),
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/beckn/beckn-onix/pkg/plugin/definition"
|
||||
|
||||
verifier "github.com/beckn/beckn-onix/pkg/plugin/implementation/signVerifier"
|
||||
)
|
||||
|
||||
// VerifierProvider provides instances of Verifier.
|
||||
type VerifierProvider struct{}
|
||||
|
||||
// New initializes a new Verifier instance.
|
||||
func (vp VerifierProvider) New(ctx context.Context, config map[string]string) (definition.Verifier, func() error, error) {
|
||||
if ctx == nil {
|
||||
return nil, nil, errors.New("context cannot be nil")
|
||||
}
|
||||
|
||||
return verifier.New(ctx, &verifier.Config{})
|
||||
}
|
||||
|
||||
// Provider is the exported symbol that the plugin manager will look for.
|
||||
var Provider definition.VerifierProvider = VerifierProvider{}
|
||||
@@ -21,4 +21,4 @@ func (p SignerProvider) New(ctx context.Context, config map[string]string) (defi
|
||||
}
|
||||
|
||||
// Provider is the exported symbol that the plugin manager will look for.
|
||||
var Provider definition.SignerProvider = SignerProvider{}
|
||||
var Provider = SignerProvider{}
|
||||
|
||||
@@ -23,7 +23,7 @@ type Signer struct {
|
||||
func New(ctx context.Context, config *Config) (*Signer, func() error, error) {
|
||||
s := &Signer{config: config}
|
||||
|
||||
return s, s.Close, nil
|
||||
return s, nil, nil
|
||||
}
|
||||
|
||||
// hash generates a signing string using BLAKE-512 hashing.
|
||||
@@ -71,8 +71,3 @@ func (s *Signer) Sign(ctx context.Context, body []byte, privateKeyBase64 string,
|
||||
|
||||
return base64.StdEncoding.EncodeToString(signature), nil
|
||||
}
|
||||
|
||||
// Close releases resources (mock implementation returning nil).
|
||||
func (s *Signer) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
24
pkg/plugin/implementation/signvalidator/cmd/plugin.go
Normal file
24
pkg/plugin/implementation/signvalidator/cmd/plugin.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/beckn/beckn-onix/pkg/plugin/definition"
|
||||
"github.com/beckn/beckn-onix/pkg/plugin/implementation/signvalidator"
|
||||
)
|
||||
|
||||
// provider provides instances of Verifier.
|
||||
type provider struct{}
|
||||
|
||||
// New initializes a new Verifier instance.
|
||||
func (vp provider) New(ctx context.Context, config map[string]string) (definition.SignValidator, func() error, error) {
|
||||
if ctx == nil {
|
||||
return nil, nil, errors.New("context cannot be nil")
|
||||
}
|
||||
|
||||
return signvalidator.New(ctx, &signvalidator.Config{})
|
||||
}
|
||||
|
||||
// Provider is the exported symbol that the plugin manager will look for.
|
||||
var Provider = provider{}
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
|
||||
// TestVerifierProviderSuccess tests successful creation of a verifier.
|
||||
func TestVerifierProviderSuccess(t *testing.T) {
|
||||
provider := VerifierProvider{}
|
||||
provider := provider{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -52,7 +52,7 @@ func TestVerifierProviderSuccess(t *testing.T) {
|
||||
|
||||
// TestVerifierProviderFailure tests cases where verifier creation should fail.
|
||||
func TestVerifierProviderFailure(t *testing.T) {
|
||||
provider := VerifierProvider{}
|
||||
provider := provider{}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -1,4 +1,4 @@
|
||||
package verifier
|
||||
package signvalidator
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -16,36 +16,36 @@ import (
|
||||
type Config struct {
|
||||
}
|
||||
|
||||
// Verifier implements the Verifier interface.
|
||||
type Verifier struct {
|
||||
// validator implements the validator interface.
|
||||
type validator struct {
|
||||
config *Config
|
||||
}
|
||||
|
||||
// New creates a new Verifier instance.
|
||||
func New(ctx context.Context, config *Config) (*Verifier, func() error, error) {
|
||||
v := &Verifier{config: config}
|
||||
func New(ctx context.Context, config *Config) (*validator, func() error, error) {
|
||||
v := &validator{config: config}
|
||||
|
||||
return v, v.Close, nil
|
||||
return v, nil, nil
|
||||
}
|
||||
|
||||
// Verify checks the signature for the given payload and public key.
|
||||
func (v *Verifier) Verify(ctx context.Context, body []byte, header []byte, publicKeyBase64 string) (bool, error) {
|
||||
createdTimestamp, expiredTimestamp, signature, err := parseAuthHeader(string(header))
|
||||
func (v *validator) Validate(ctx context.Context, body []byte, header string, publicKeyBase64 string) error {
|
||||
createdTimestamp, expiredTimestamp, signature, err := parseAuthHeader(header)
|
||||
if err != nil {
|
||||
// TODO: Return appropriate error code when Error Code Handling Module is ready
|
||||
return false, fmt.Errorf("error parsing header: %w", err)
|
||||
return fmt.Errorf("error parsing header: %w", err)
|
||||
}
|
||||
|
||||
signatureBytes, err := base64.StdEncoding.DecodeString(signature)
|
||||
if err != nil {
|
||||
// TODO: Return appropriate error code when Error Code Handling Module is ready
|
||||
return false, fmt.Errorf("error decoding signature: %w", err)
|
||||
return fmt.Errorf("error decoding signature: %w", err)
|
||||
}
|
||||
|
||||
currentTime := time.Now().Unix()
|
||||
if createdTimestamp > currentTime || currentTime > expiredTimestamp {
|
||||
// TODO: Return appropriate error code when Error Code Handling Module is ready
|
||||
return false, fmt.Errorf("signature is expired or not yet valid")
|
||||
return fmt.Errorf("signature is expired or not yet valid")
|
||||
}
|
||||
|
||||
createdTime := time.Unix(createdTimestamp, 0)
|
||||
@@ -56,15 +56,15 @@ func (v *Verifier) Verify(ctx context.Context, body []byte, header []byte, publi
|
||||
decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKeyBase64)
|
||||
if err != nil {
|
||||
// TODO: Return appropriate error code when Error Code Handling Module is ready
|
||||
return false, fmt.Errorf("error decoding public key: %w", err)
|
||||
return fmt.Errorf("error decoding public key: %w", err)
|
||||
}
|
||||
|
||||
if !ed25519.Verify(ed25519.PublicKey(decodedPublicKey), []byte(signingString), signatureBytes) {
|
||||
// TODO: Return appropriate error code when Error Code Handling Module is ready
|
||||
return false, fmt.Errorf("signature verification failed")
|
||||
return fmt.Errorf("signature verification failed")
|
||||
}
|
||||
|
||||
return true, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseAuthHeader extracts signature values from the Authorization header.
|
||||
@@ -113,8 +113,3 @@ func hash(payload []byte, createdTimestamp, expiredTimestamp int64) string {
|
||||
|
||||
return fmt.Sprintf("(created): %d\n(expires): %d\ndigest: BLAKE-512=%s", createdTimestamp, expiredTimestamp, digestB64)
|
||||
}
|
||||
|
||||
// Close releases resources (mock implementation returning nil).
|
||||
func (v *Verifier) Close() error {
|
||||
return nil
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package verifier
|
||||
package signvalidator
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -52,14 +52,11 @@ func TestVerifySuccess(t *testing.T) {
|
||||
`", signature="` + signature + `"`
|
||||
|
||||
verifier, close, _ := New(context.Background(), &Config{})
|
||||
valid, err := verifier.Verify(context.Background(), tt.body, []byte(header), publicKeyBase64)
|
||||
err := verifier.Validate(context.Background(), tt.body, header, publicKeyBase64)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Expected no error, but got: %v", err)
|
||||
}
|
||||
if !valid {
|
||||
t.Fatal("Expected signature verification to succeed")
|
||||
}
|
||||
if close != nil {
|
||||
if err := close(); err != nil {
|
||||
t.Fatalf("Test %q failed: cleanup function returned an error: %v", tt.name, err)
|
||||
@@ -135,14 +132,11 @@ func TestVerifyFailure(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
verifier, close, _ := New(context.Background(), &Config{})
|
||||
valid, err := verifier.Verify(context.Background(), tt.body, []byte(tt.header), tt.pubKey)
|
||||
err := verifier.Validate(context.Background(), tt.body, tt.header, tt.pubKey)
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("Expected an error but got none")
|
||||
}
|
||||
if valid {
|
||||
t.Fatal("Expected verification to fail")
|
||||
}
|
||||
if close != nil {
|
||||
if err := close(); err != nil {
|
||||
t.Fatalf("Test %q failed: cleanup function returned an error: %v", tt.name, err)
|
||||
Reference in New Issue
Block a user