|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + |
| 7 | + "github.com/SUSE/openplatform-kubewarden-policies/policies/harvester-restricted-vlan-namespace/internal" |
| 8 | + "github.com/SUSE/openplatform-kubewarden-policies/policies/harvester-restricted-vlan-namespace/internal/logger" |
| 9 | + "github.com/francoispqt/onelog" |
| 10 | + kubewarden "github.com/kubewarden/policy-sdk-go" |
| 11 | + kubewardenProtocol "github.com/kubewarden/policy-sdk-go/protocol" |
| 12 | +) |
| 13 | + |
| 14 | +func validateRequest(ctx context.Context, payload []byte) ([]byte, error) { |
| 15 | + validationRequest := kubewardenProtocol.ValidationRequest{} |
| 16 | + err := json.Unmarshal(payload, &validationRequest) |
| 17 | + if err != nil { |
| 18 | + return kubewarden.RejectRequest( |
| 19 | + kubewarden.Message(err.Error()), |
| 20 | + kubewarden.Code(httpBadRequestStatusCode)) |
| 21 | + } |
| 22 | + |
| 23 | + settings, err := parseSettings(validationRequest.Settings) |
| 24 | + if err != nil { |
| 25 | + return kubewarden.RejectRequest( |
| 26 | + kubewarden.Message(err.Error()), |
| 27 | + kubewarden.Code(httpBadRequestStatusCode)) |
| 28 | + } |
| 29 | + |
| 30 | + networkAttachmentDefinition := internal.NetworkAttachmentDefinition{} |
| 31 | + err = json.Unmarshal(validationRequest.Request.Object, &networkAttachmentDefinition) |
| 32 | + if err != nil { |
| 33 | + return kubewarden.RejectRequest( |
| 34 | + kubewarden.Message(err.Error()), |
| 35 | + kubewarden.Code(httpBadRequestStatusCode)) |
| 36 | + } |
| 37 | + |
| 38 | + namespace := networkAttachmentDefinition.Metadata.Namespace |
| 39 | + vlan := networkAttachmentDefinition.Spec.Config.VLAN |
| 40 | + l := logger.FromContext(ctx).With(func(entry onelog.Entry) { |
| 41 | + entry.String("namespace", namespace) |
| 42 | + entry.Int("vlan", vlan) |
| 43 | + }) |
| 44 | + |
| 45 | + l.Info("NETWORK_CHECK namespace") |
| 46 | + if !settings.IsVLANAllowed(ctx, namespace, vlan) { |
| 47 | + l.Info("NETWORK_REJECTED namespace") |
| 48 | + return kubewarden.RejectRequest("Invalid request", kubewarden.Code(httpBadRequestStatusCode)) |
| 49 | + } |
| 50 | + l.Info("NETWORK_ALLOWED namespace") |
| 51 | + |
| 52 | + return kubewarden.AcceptRequest() |
| 53 | +} |
0 commit comments