Skip to content

Commit

Permalink
mockkubeapiserver: Support stringData when creating a secret
Browse files Browse the repository at this point in the history
This is an edge case in the kube apiserver, but there is special
handling for the stringData field of a secret, that is mapped to
base64 data.
  • Loading branch information
justinsb committed Jun 8, 2024
1 parent 187c2bb commit e09355f
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 50 deletions.
35 changes: 35 additions & 0 deletions mockkubeapiserver/postresource.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package mockkubeapiserver

import (
"context"
"encoding/base64"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -69,8 +70,42 @@ func (req *postResource) Run(ctx context.Context, s *MockKubeAPIServer) error {
return fmt.Errorf("name must be provided in payload")
}

if err := preCreateHook(ctx, obj); err != nil {
return err
}

if err := resource.CreateObject(ctx, id, obj); err != nil {
return err
}
return req.writeResponse(obj)
}

func preCreateHook(ctx context.Context, obj *unstructured.Unstructured) error {
gvk := obj.GroupVersionKind()
if gvk.Group == "" && gvk.Version == "v1" && gvk.Kind == "Secret" {
stringDataAny, found := obj.Object["stringData"]
if found {
stringDataMap, ok := stringDataAny.(map[string]any)
if !ok {
return fmt.Errorf("unexpected type for v1.Secret stringData, got %T", stringDataAny)
}
dataAny, dataFound := obj.Object["data"]
if !dataFound {
dataAny = make(map[string]any)
obj.Object["data"] = dataAny
}
dataMap, ok := dataAny.(map[string]any)
if !ok {
return fmt.Errorf("unexpected type for v1.Secret data, got %T", dataAny)
}
for k, vAny := range stringDataMap {
v, ok := vAny.(string)
if !ok {
return fmt.Errorf("unexpected type for v1.Secret stringData entry, got %T", vAny)
}
dataMap[k] = base64.StdEncoding.EncodeToString([]byte(v))
}
}
}
return nil
}
Loading

0 comments on commit e09355f

Please sign in to comment.