Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(kube-api-rewriter): renaming before refactoring rewrites #153

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
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
4 changes: 3 additions & 1 deletion images/kube-api-proxy/cmd/kube-api-proxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
logutil "kube-api-proxy/pkg/log"
"kube-api-proxy/pkg/proxy"
"kube-api-proxy/pkg/rewriter"
"kube-api-proxy/pkg/rewriter/rules"
"kube-api-proxy/pkg/server"
"kube-api-proxy/pkg/target"
)
Expand Down Expand Up @@ -70,9 +71,10 @@ func main() {
})

// Load rules from file or use default kubevirt rules.
// WARNING: loading of declarative rules is just a PoC and not working yet.
rewriteRules := kubevirt.KubevirtRewriteRules
if os.Getenv("RULES_PATH") != "" {
rulesFromFile, err := rewriter.LoadRules(os.Getenv("RULES_PATH"))
rulesFromFile, err := rules.LoadRules(os.Getenv("RULES_PATH"))
if err != nil {
log.Error("Load rules from %s: %v", os.Getenv("RULES_PATH"), err)
os.Exit(1)
Expand Down
2 changes: 1 addition & 1 deletion images/kube-api-proxy/pkg/kubevirt/kubevirt_rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ limitations under the License.
package kubevirt

import (
. "kube-api-proxy/pkg/rewriter"
. "kube-api-proxy/pkg/rewriter/rules"
)

const (
Expand Down
13 changes: 7 additions & 6 deletions images/kube-api-proxy/pkg/proxy/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (

logutil "kube-api-proxy/pkg/log"
"kube-api-proxy/pkg/rewriter"
"kube-api-proxy/pkg/rewriter/rules"
)

type ProxyMode string
Expand All @@ -42,18 +43,18 @@ const (
ToRenamed ProxyMode = "renamed"
)

func ToTargetAction(proxyMode ProxyMode) rewriter.Action {
func ToTargetAction(proxyMode ProxyMode) rules.Action {
if proxyMode == ToRenamed {
return rewriter.Rename
return rules.Rename
}
return rewriter.Restore
return rules.Restore
}

func FromTargetAction(proxyMode ProxyMode) rewriter.Action {
func FromTargetAction(proxyMode ProxyMode) rules.Action {
if proxyMode == ToRenamed {
return rewriter.Restore
return rules.Restore
}
return rewriter.Rename
return rules.Rename
}

type Handler struct {
Expand Down
3 changes: 2 additions & 1 deletion images/kube-api-proxy/pkg/proxy/stream_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import (

logutil "kube-api-proxy/pkg/log"
"kube-api-proxy/pkg/rewriter"
"kube-api-proxy/pkg/rewriter/rules"
)

// StreamHandler reads a stream from the target, transforms events
Expand Down Expand Up @@ -206,7 +207,7 @@ func (s *StreamHandler) transformWatchEvent(ev *metav1.WatchEvent) (*metav1.Watc
s.log.Debug(fmt.Sprintf("Receive '%s' watch event with %s/%s %s/%s object", ev.Type, group, kind, ns, name))

// Restore object in the event. Watch responses are always from the Kubernetes API server, so rename is not needed.
rwrObjBytes, err := s.rewriter.RewriteJSONPayload(s.targetReq, ev.Object.Raw, rewriter.Restore)
rwrObjBytes, err := s.rewriter.RewriteJSONPayload(s.targetReq, ev.Object.Raw, rules.Restore)
if err != nil {
return nil, fmt.Errorf("error rewriting object: %w", err)
}
Expand Down
13 changes: 8 additions & 5 deletions images/kube-api-proxy/pkg/rewriter/3rdparty.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,20 @@ limitations under the License.

package rewriter

import (
"kube-api-proxy/pkg/rewriter/rules"
"kube-api-proxy/pkg/rewriter/transform"
)

// Rewrite routines for 3rd party resources, i.e. ServiceMonitor.

const (
PrometheusRuleKind = "PrometheusRule"
PrometheusRuleListKind = "PrometheusRuleList"
ServiceMonitorKind = "ServiceMonitor"
ServiceMonitorListKind = "ServiceMonitorList"
)

func RewriteServiceMonitorOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error) {
return TransformObject(obj, "spec.selector", func(obj []byte) ([]byte, error) {
return rewriteLabelSelector(rules, obj, action)
func RewriteServiceMonitor(rwRules *rules.RewriteRules, obj []byte, action rules.Action) ([]byte, error) {
return transform.Object(obj, "spec.selector", func(obj []byte) ([]byte, error) {
return RewriteLabelSelector(rwRules, obj, action)
})
}
63 changes: 23 additions & 40 deletions images/kube-api-proxy/pkg/rewriter/admission_configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@ limitations under the License.

package rewriter

import "github.com/tidwall/gjson"
import (
"github.com/tidwall/gjson"

"kube-api-proxy/pkg/rewriter/rules"
"kube-api-proxy/pkg/rewriter/transform"
)

const (
ValidatingWebhookConfigurationKind = "ValidatingWebhookConfiguration"
Expand All @@ -25,62 +30,40 @@ const (
MutatingWebhookConfigurationListKind = "MutatingWebhookConfigurationList"
)

func RewriteValidatingOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error) {
if action == Rename {
return RewriteResourceOrList(obj, ValidatingWebhookConfigurationListKind, func(singleObj []byte) ([]byte, error) {
return RewriteArray(singleObj, "webhooks", func(webhook []byte) ([]byte, error) {
return RewriteArray(webhook, "rules", func(item []byte) ([]byte, error) {
return renameRoleRule(rules, item)
})
})
})
}
return RewriteResourceOrList(obj, ValidatingWebhookConfigurationListKind, func(singleObj []byte) ([]byte, error) {
return RewriteArray(singleObj, "webhooks", func(webhook []byte) ([]byte, error) {
return RewriteArray(webhook, "rules", func(item []byte) ([]byte, error) {
return restoreRoleRule(rules, item)
})
func RewriteValidating(rwRules *rules.RewriteRules, validatingObj []byte, action rules.Action) ([]byte, error) {
return transform.Array(validatingObj, "webhooks", func(webhookObj []byte) ([]byte, error) {
return transform.Array(webhookObj, "rules", func(ruleObj []byte) ([]byte, error) {
return RewriteRoleRule(rwRules, ruleObj, action)
})
})
}

func RewriteMutatingOrList(rules *RewriteRules, obj []byte, action Action) ([]byte, error) {
if action == Rename {
return RewriteResourceOrList(obj, MutatingWebhookConfigurationListKind, func(singleObj []byte) ([]byte, error) {
return RewriteArray(singleObj, "webhooks", func(webhook []byte) ([]byte, error) {
return RewriteArray(webhook, "rules", func(item []byte) ([]byte, error) {
return renameRoleRule(rules, item)
})
})
})
}
return RewriteResourceOrList(obj, MutatingWebhookConfigurationListKind, func(singleObj []byte) ([]byte, error) {
return RewriteArray(singleObj, "webhooks", func(webhook []byte) ([]byte, error) {
return RewriteArray(webhook, "rules", func(item []byte) ([]byte, error) {
return restoreRoleRule(rules, item)
})
func RewriteMutating(rwRules *rules.RewriteRules, mutatingObj []byte, action rules.Action) ([]byte, error) {
return transform.Array(mutatingObj, "webhooks", func(webhookObj []byte) ([]byte, error) {
return transform.Array(webhookObj, "rules", func(ruleObj []byte) ([]byte, error) {
return RewriteRoleRule(rwRules, ruleObj, action)
})
})
}

func RenameWebhookConfigurationPatch(rules *RewriteRules, obj []byte) ([]byte, error) {
obj, err := RenameMetadataPatch(rules, obj)
func RenameWebhookConfigurationPatch(rwRules *rules.RewriteRules, obj []byte) ([]byte, error) {
obj, err := RenameMetadataPatch(rwRules, obj)
if err != nil {
return nil, err
}

return TransformPatch(obj, func(mergePatch []byte) ([]byte, error) {
return RewriteArray(mergePatch, "webhooks", func(webhook []byte) ([]byte, error) {
return RewriteArray(webhook, "rules", func(item []byte) ([]byte, error) {
return restoreRoleRule(rules, item)
return transform.Patch(obj, func(mergePatch []byte) ([]byte, error) {
return transform.Array(mergePatch, "webhooks", func(webhook []byte) ([]byte, error) {
return transform.Array(webhook, "rules", func(ruleObj []byte) ([]byte, error) {
return RewriteRoleRule(rwRules, ruleObj, rules.Rename)
})
})
}, func(jsonPatch []byte) ([]byte, error) {
path := gjson.GetBytes(jsonPatch, "path").String()
if path == "/webhooks" {
return RewriteArray(jsonPatch, "value", func(webhook []byte) ([]byte, error) {
return RewriteArray(webhook, "rules", func(item []byte) ([]byte, error) {
return renameRoleRule(rules, item)
return transform.Array(jsonPatch, "value", func(webhook []byte) ([]byte, error) {
return transform.Array(webhook, "rules", func(ruleObj []byte) ([]byte, error) {
return RewriteRoleRule(rwRules, ruleObj, rules.Rename)
})
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"testing"

"github.com/stretchr/testify/require"

"kube-api-proxy/pkg/rewriter/rules"
)

func TestValidatingRename(t *testing.T) {
Expand All @@ -30,8 +32,8 @@ func TestValidatingRename(t *testing.T) {
}{
{
"mixed resources",
`{"webhooks":[{"rules":[{"apiGroups":[""],"resources":["pods"]},{"apiGroups": ["original.group.io"], "resources": ["someresources"]}]}]}`,
`{"webhooks":[{"rules":[{"apiGroups":[""],"resources":["pods"]},{"apiGroups": ["prefixed.resources.group.io"], "resources": ["prefixedsomeresources"]}]}]}`,
`{"kind":"ValidatingWebhookConfiguration","webhooks":[{"rules":[{"apiGroups":[""],"resources":["pods"]},{"apiGroups": ["original.group.io"], "resources": ["someresources"]}]}]}`,
`{"kind":"ValidatingWebhookConfiguration","webhooks":[{"rules":[{"apiGroups":[""],"resources":["pods"]},{"apiGroups": ["prefixed.resources.group.io"], "resources": ["prefixedsomeresources"]}]}]}`,
},
{
"empty object",
Expand All @@ -44,7 +46,7 @@ func TestValidatingRename(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
rwr := createTestRewriter()

resBytes, err := RewriteValidatingOrList(rwr.Rules, []byte(tt.manifest), Rename)
resBytes, err := RewriteValidating(rwr.Rules, []byte(tt.manifest), rules.Rename)
require.NoError(t, err, "should rename validating webhook configuration")

actual := string(resBytes)
Expand All @@ -61,8 +63,8 @@ func TestValidatingRestore(t *testing.T) {
}{
{
"mixed resources",
`{"webhooks":[{"rules":[{"apiGroups":[""],"resources":["pods"]},{"apiGroups": ["prefixed.resources.group.io"], "resources": ["prefixedsomeresources"]}]}]}`,
`{"webhooks":[{"rules":[{"apiGroups":[""],"resources":["pods"]},{"apiGroups": ["original.group.io"], "resources": ["someresources"]}]}]}`,
`{"kind":"ValidatingWebhookConfiguration","webhooks":[{"rules":[{"apiGroups":[""],"resources":["pods"]},{"apiGroups": ["prefixed.resources.group.io"], "resources": ["prefixedsomeresources"]}]}]}`,
`{"kind":"ValidatingWebhookConfiguration","webhooks":[{"rules":[{"apiGroups":[""],"resources":["pods"]},{"apiGroups": ["original.group.io"], "resources": ["someresources"]}]}]}`,
},
{
"empty object",
Expand All @@ -75,7 +77,7 @@ func TestValidatingRestore(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
rwr := createTestRewriter()

resBytes, err := RewriteValidatingOrList(rwr.Rules, []byte(tt.manifest), Restore)
resBytes, err := RewriteValidating(rwr.Rules, []byte(tt.manifest), rules.Restore)
require.NoError(t, err, "should rename validating webhook configuration")

actual := string(resBytes)
Expand Down
24 changes: 13 additions & 11 deletions images/kube-api-proxy/pkg/rewriter/admission_review.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@ package rewriter
import (
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"

"kube-api-proxy/pkg/rewriter/rules"
)

// RewriteAdmissionReview rewrites AdmissionReview request and response.
// NOTE: only one rewrite direction is supported for now:
// - Restore object in AdmissionReview request.
// - Do nothing for AdmissionReview response.
func RewriteAdmissionReview(rules *RewriteRules, obj []byte, origGroup string) ([]byte, error) {
func RewriteAdmissionReview(rwRules *rules.RewriteRules, obj []byte, origGroup string) ([]byte, error) {
response := gjson.GetBytes(obj, "response")
if response.Exists() {
// TODO rewrite response with the Patch.
Expand All @@ -34,7 +36,7 @@ func RewriteAdmissionReview(rules *RewriteRules, obj []byte, origGroup string) (

request := gjson.GetBytes(obj, "request")
if request.Exists() {
newRequest, err := RestoreAdmissionReviewRequest(rules, []byte(request.Raw), origGroup)
newRequest, err := RestoreAdmissionReviewRequest(rwRules, []byte(request.Raw), origGroup)
if err != nil {
return nil, err
}
Expand All @@ -51,7 +53,7 @@ func RewriteAdmissionReview(rules *RewriteRules, obj []byte, origGroup string) (

// RestoreAdmissionReviewRequest restores apiVersion, kind and other fields in an AdmissionReview request.
// Only restoring is required, as AdmissionReview request only comes from API Server.
func RestoreAdmissionReviewRequest(rules *RewriteRules, obj []byte, origGroup string) ([]byte, error) {
func RestoreAdmissionReviewRequest(rwRules *rules.RewriteRules, obj []byte, origGroup string) ([]byte, error) {
var err error

// Rewrite "resource" field and find rules.
Expand All @@ -60,10 +62,10 @@ func RestoreAdmissionReviewRequest(rules *RewriteRules, obj []byte, origGroup st
group := resourceObj.Get("group")
resource := resourceObj.Get("resource")
// Ignore reviews for unknown renamed group.
if group.String() != rules.RenamedGroup {
if group.String() != rwRules.RenamedGroup {
return nil, nil
}
newResource := rules.RestoreResource(resource.String())
newResource := rwRules.RestoreResource(resource.String())
obj, err = sjson.SetBytes(obj, "resource.resource", newResource)
if err != nil {
return nil, err
Expand All @@ -80,10 +82,10 @@ func RestoreAdmissionReviewRequest(rules *RewriteRules, obj []byte, origGroup st
group := fieldObj.Get("group")
resource := fieldObj.Get("resource")
// Ignore reviews for unknown renamed group.
if group.String() != rules.RenamedGroup {
if group.String() != rwRules.RenamedGroup {
return nil, nil
}
newResource := rules.RestoreResource(resource.String())
newResource := rwRules.RestoreResource(resource.String())
obj, err = sjson.SetBytes(obj, "requestResource.resource", newResource)
if err != nil {
return nil, err
Expand All @@ -106,7 +108,7 @@ func RestoreAdmissionReviewRequest(rules *RewriteRules, obj []byte, origGroup st
{
fieldObj := gjson.GetBytes(obj, "kind")
kind := fieldObj.Get("kind")
newKind := rules.RestoreKind(kind.String())
newKind := rwRules.RestoreKind(kind.String())
obj, err = sjson.SetBytes(obj, "kind.kind", newKind)
if err != nil {
return nil, err
Expand All @@ -121,7 +123,7 @@ func RestoreAdmissionReviewRequest(rules *RewriteRules, obj []byte, origGroup st
{
fieldObj := gjson.GetBytes(obj, "requestKind")
kind := fieldObj.Get("kind")
newKind := rules.RestoreKind(kind.String())
newKind := rwRules.RestoreKind(kind.String())
obj, err = sjson.SetBytes(obj, "requestKind.kind", newKind)
if err != nil {
return nil, err
Expand All @@ -136,7 +138,7 @@ func RestoreAdmissionReviewRequest(rules *RewriteRules, obj []byte, origGroup st
{
fieldObj := gjson.GetBytes(obj, "object")
if fieldObj.Exists() {
newField, err := RestoreResource(rules, []byte(fieldObj.Raw), origGroup)
newField, err := RestoreResource(rwRules, []byte(fieldObj.Raw), origGroup)
if err != nil {
return nil, err
}
Expand All @@ -153,7 +155,7 @@ func RestoreAdmissionReviewRequest(rules *RewriteRules, obj []byte, origGroup st
{
fieldObj := gjson.GetBytes(obj, "oldObject")
if fieldObj.Exists() {
newField, err := RestoreResource(rules, []byte(fieldObj.Raw), origGroup)
newField, err := RestoreResource(rwRules, []byte(fieldObj.Raw), origGroup)
if err != nil {
return nil, err
}
Expand Down
Loading
Loading