Skip to content

Commit

Permalink
feat: auto-generate rla's namespace on 'convert' subcommand
Browse files Browse the repository at this point in the history
  • Loading branch information
GGabriele committed Feb 5, 2024
1 parent 4548a0e commit 62847c9
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions convert/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package convert

import (
"context"
"crypto/rand"
"fmt"
"math/big"
"strings"

"github.com/blang/semver/v4"
Expand All @@ -27,6 +29,9 @@ const (
FormatKongGateway2x Format = "kong-gateway-2.x"
// FormatKongGateway3x represents the Kong gateway 3.x format.
FormatKongGateway3x Format = "kong-gateway-3.x"

rateLimitingAdvancedPluginName = "rate-limiting-advanced"
rlaNamespaceDefaultLength = 32
)

// AllFormats contains all available formats.
Expand Down Expand Up @@ -100,6 +105,22 @@ func Convert(
return err
}

func randomString(n int) (string, error) {
const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzj"
charsetLength := big.NewInt(int64(len(charset)))

ret := make([]byte, n)
for i := 0; i < n; i++ {
num, err := rand.Int(rand.Reader, charsetLength)
if err != nil {
return "", fmt.Errorf("error generating random string: %w", err)
}
ret[i] = charset[num.Int64()]
}

return string(ret), nil
}

func convertKongGateway2xTo3x(input *file.Content, filename string) (*file.Content, error) {
if input == nil {
return nil, fmt.Errorf("input content is nil")
Expand Down Expand Up @@ -140,6 +161,22 @@ func convertKongGateway2xTo3x(input *file.Content, filename string) (*file.Conte
filename, changedRoutesLen, strings.Join(changedRoutes, "\n"))
}

for _, plugin := range outputContent.Plugins {
if *plugin.Name == rateLimitingAdvancedPluginName {
if plugin.Config != nil {
ns, ok := plugin.Config["namespace"]
if !ok || ns == nil {
// namespace is not set, generate one.
randomNamespace, err := randomString(rlaNamespaceDefaultLength)
if err != nil {
return nil, fmt.Errorf("error generating random namespace: %w", err)
}
plugin.Config["namespace"] = randomNamespace
}
}
}
}

cprint.UpdatePrintf(
"From the '%s' config file,\n"+
"the _format_version field has been migrated from '%s' to '%s'.\n"+
Expand Down

0 comments on commit 62847c9

Please sign in to comment.