File kube-review-0.5.0.obscpio of Package kube-review

07070100000000000081A40000000000000000000000016807DDE800000510000000000000000000000000000000000000002100000000kube-review-0.5.0/.golangci.yamlversion: "2"
linters:
  default: all
  disable:
    - cyclop
    - err113
    - exhaustruct
    - forcetypeassert
    - funlen
    - gochecknoglobals
    - gochecknoinits
    - gocognit
    - goconst
    - gocyclo
    - godox
    - gomoddirectives
    - inamedparam
    - ireturn
    - mnd
    - nestif
    - nonamedreturns
    - testpackage
    - varnamelen
    - wrapcheck
  settings:
    depguard:
      rules:
        main:
          deny:
            - pkg: gopkg.in/yaml.v2
              desc: use yaml.v3 only
    revive:
      rules:
        - name: unused-parameter
          arguments:
            - allowRegex: ^_
          severity: warning
          disabled: false
        - name: unused-receiver
          arguments:
            - allowRegex: ^_
          severity: warning
          disabled: false
  exclusions:
    generated: lax
    presets:
      - comments
      - common-false-positives
      - legacy
      - std-error-handling
    paths:
      - third_party$
      - builtin$
      - examples$
formatters:
  enable:
    - gci
    - gofmt
    - gofumpt
    - goimports
  settings:
    gci:
      sections:
        - standard
        - default
        - blank
        - dot
  exclusions:
    generated: lax
    paths:
      - third_party$
      - builtin$
      - examples$
07070100000001000081A40000000000000000000000016807DDE8000003BB000000000000000000000000000000000000001F00000000kube-review-0.5.0/CHANGELOG.md# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.5.0] - 2025-04-22

### Changed

* Fix panic when parsing multi-doc YAML, where first doc is empty (#51)
* Bump Go to 1.24
* Bump all dependencies to the latest versions

## [0.4.0] - 2025-01-21

### Added

* `--indent` option

### Changed

* Bump all dependencies to the latest versions (Kubernetes v0.32.1)

## [0.3.0] - 2022-06-07
### Changed
* Bump to Kubernetes v0.27.0 and other dependencies
* Add simple test to verify basis functionality

## [0.2.1] - 2022-09-08
### Changed
* Bump dependencies, including Kubernetes v0.25.0

## [0.2.0] - 2022-04-14
### Changed
* Require subcommands like `create`, in order to allow others in the future

## [0.1.0] - 2021-12-25
### Added
* First release!
07070100000002000081A40000000000000000000000016807DDE800002C5D000000000000000000000000000000000000001A00000000kube-review-0.5.0/LICENSE                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
07070100000003000081A40000000000000000000000016807DDE800000340000000000000000000000000000000000000001B00000000kube-review-0.5.0/MakefileVERSION := "v0.4.0"

LDFLAGS := "-X 'github.com/anderseknert/kube-review/cmd.version=$(VERSION)'"

clean:
	rm -rf _release

lint:
	golangci-lint run

build:
	go build -ldflags=$(LDFLAGS)

prepare-release:
	mkdir -p _release

build-darwin-amd64: prepare-release
	GOOS=darwin GOARCH=amd64 go build -ldflags=$(LDFLAGS) -o _release/kube-review-darwin-amd64

build-darwin-arm64: prepare-release
	GOOS=darwin GOARCH=arm64 go build -ldflags=$(LDFLAGS) -o _release/kube-review-darwin-arm64

build-linux-amd64: prepare-release
	GOOS=linux GOARCH=amd64 go build -ldflags=$(LDFLAGS) -o _release/kube-review-linux-amd64

build-windows-amd64: prepare-release
	GOOS=windows GOARCH=amd64 go build -ldflags=$(LDFLAGS) -o _release/kube-review-windows-amd64.exe

build-all: build-darwin-amd64 build-darwin-arm64 build-linux-amd64 build-windows-amd64
07070100000004000081A40000000000000000000000016807DDE800001BEA000000000000000000000000000000000000001C00000000kube-review-0.5.0/README.md# kube-review

Simple command line utility to transform a provided Kubernetes resource into a Kubernetes AdmissionReview request, as
sent from the Kubernetes API server when [dynamic admission control](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/)
(i.e. webhook) is configured.

**deployment.yaml**
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx
        name: nginx
        ports:
        - containerPort: 8080
```
**Command**
```shell
$ kube-review create deployment.yaml
```
**Output**
```json
{
  "kind": "AdmissionReview",
  "apiVersion": "admission.k8s.io/v1",
  "request": {
    "uid": "2024ee9c-c374-413c-838d-e62bcb4826be",
    "kind": {
      "group": "apps",
      "version": "v1",
      "kind": "Deployment"
    },
    "resource": {
      "group": "apps",
      "version": "v1",
      "resource": "deployments"
    },
    "requestKind": {
      "group": "apps",
      "version": "v1",
      "kind": "Deployment"
    },
    "requestResource": {
      "group": "apps",
      "version": "v1",
      "resource": "deployments"
    },
    "name": "nginx",
    "operation": "CREATE",
    "userInfo": {
      "username": "kube-review",
      "uid": "611a19d7-6aa5-47d2-bba3-8c5df2bffbc7"
    },
    "object": {
      "kind": "Deployment",
      "apiVersion": "apps/v1",
      "metadata": {
        "name": "nginx",
        "creationTimestamp": null,
        "labels": {
          "app": "nginx"
        }
      },
      "spec": {
        "selector": {
          "matchLabels": {
            "app": "nginx"
          }
        },
        "template": {
          "metadata": {
            "creationTimestamp": null,
            "labels": {
              "app": "nginx"
            }
          },
          "spec": {
            "containers": [
              {
                "name": "nginx",
                "image": "nginx",
                "ports": [
                  {
                    "containerPort": 8080
                  }
                ],
                "resources": {}
              }
            ]
          }
        },
        "strategy": {}
      },
      "status": {}
    },
    "oldObject": null,
    "dryRun": true,
    "options": {
      "kind": "CreateOptions",
      "apiVersion": "meta.k8s.io/v1"
    }
  }
}
```

## Why?

* Testing Kubernetes admission webhook receivers without Kubernetes (CI/CD pipelines, faster integration tests, etc.)
* Quickly be able to author, and test, admission control policies with tools like [Open Policy Agent](https://www.openpolicyagent.org/)

## Installation

Find the latest release for your platform at the [release page](https://github.com/anderseknert/kube-review/releases/latest).
Once downloaded, rename it to `kube-review` (or `kube-review.exe` for Windows if not using WSL),
allow it to be executed, and put it somewhere on your `$PATH`.

## Running kube-review

`kube-review create` can either be provided a filename with a resource to create an admission review for, or can read
data from stdin. This allows easily piping resources from a kube cluster and into kube-review.

**Command**
```shell
$ kubectl get service gatekeeper-webhook-service -o yaml | kube-review create --action update
```
**Output**
```json
{
    "kind": "AdmissionReview",
    "apiVersion": "admission.k8s.io/v1",
    "request": {
        "uid": "b42420d7-5cc2-4644-992f-72ff67dc2889",
        "kind": {
            "group": "",
            "version": "v1",
            "kind": "Service"
        },
        "name": "gatekeeper-webhook-service",
        "namespace": "gatekeeper-system",
        "operation": "UPDATE",
        "userInfo": {
            "username": "kube-review",
            "uid": "42eac911-a8ec-4d72-9eb1-e6c466328085"
        },
        "...": "..."
    }
}
```
## Command line options

| Name         | Type   | Default     | Description                                                                                |
|--------------|--------|-------------|--------------------------------------------------------------------------------------------|
| `--action`   | string | create      | Type of operation to apply in admission review (create, update, delete, connect)           |
| `--as`       | string | kube-review | Name of user or service account for userInfo attributes                                    |
| `--as-group` | string | none        | Name of group this user or service account belongs to. May be repeated for multiple groups |
| `--indent`   | int    | 2           | Number of spaces to indent JSON output                                                     |

The `action` provided has the following effects on the produced `AdmissionReview` object:

* `create` and `connect`: `request.oldObject` is `null`
* `delete`: `request.object` is `null`
* All actions change the value of `request.operation` and `request.options`

## Using with Open Policy Agent

Assuming we have a policy that denies any deployment where the number of replicas is either undefined or below two:

```rego
package admission

deny contains "Deployment must have at least 2 replicas" if {
    input.request.object.spec.replicas < 2
}

deny contains "Deployment must define number of replicas explicitly" if {
    not input.request.object.spec.replicas
}
```

We could either run kube-review with a deployment from disk, and pipe the output into `opa eval`:

**Command**
```shell
$ kube-review create deployment.yaml \
| opa eval --format pretty --stdin-input --data policy.rego data.admission.deny
```
**Output**
```json
[
  "Deployment must define number of replicas explicitly"
]
```
Or we could run the policy against any resource in our cluster in the same manner:

**Command**
```shell
$ kubectl get deployment my-microservice -o yaml \
| kube-review create \
| opa eval --format pretty --stdin-input --data policy.rego data.admission.deny
```
**Output**
```json
[
  "Deployment must have at least 2 replicas"
]
```
Alternatively, we could use `curl` to send the data into a running OPA server:

**Command**
```shell
$ kubectl get deployment my-microservice -o yaml \
| kube-review create \
| curl --data-binary "@-" http://localhost:8181/v0/data/admission/deny
```
**Output**
```json
[
    "Deployment must define number of replicas explicitly"
]
```

If your policies are written for [OPA Gatekeeper](https://github.com/open-policy-agent/gatekeeper), simply rename the
`request` object in the admission request to `review`:

```shell
$ kube-review create deployment.yaml \
| opa eval --format pretty --stdin-input '{"review": input.request}' \
| opa eval --format pretty --stdin-input --data policy.rego data.admission.deny
```

## Limitations

* kube-review can create `AdmissionReview` objects from CRDs, or any "Kubernetes-like" manifest, but it makes no attempt
  to verify that they conform to the schema of the corresponding `CustomResourceDefinition`.
* Currently, kube-review doesn't handle subresource requests.
07070100000005000041ED0000000000000000000000026807DDE800000000000000000000000000000000000000000000001600000000kube-review-0.5.0/cmd07070100000006000081A40000000000000000000000016807DDE800000A50000000000000000000000000000000000000001E00000000kube-review-0.5.0/cmd/main.gopackage cmd

import (
	"fmt"
	"io"
	"log"
	"os"

	"github.com/anderseknert/kube-review/pkg/admission"
	"github.com/spf13/cobra"
)

type parameters struct {
	action string
	as     string
	groups []string
	indent uint8
}

//nolint:gochecknoglobals
var (
	params  parameters
	version = "" // Set by build command
	rootCmd = &cobra.Command{
		Use:   "kube-review",
		Short: "create admission review requests from provided kubernetes resources",
		Long: `kube-review is a tool to help create AdmissionReview objects from ordinary Kubernetes resource files.

This is useful when e.g. writing admission controller policies or offline tests of Kubernetes admission controller
webhooks`,
	}
	createCmd = &cobra.Command{
		Use:   "create",
		Short: "creates an admission review request from provided kubernetes resource",
		Run: func(_ *cobra.Command, args []string) {
			var filename string
			if len(args) > 0 {
				filename = args[0]
			}

			stat, err := os.Stdin.Stat()
			if err != nil {
				log.Fatal(err)
			}
			var input []byte

			// Read data either from stdin, or from file provided as argument
			if (filename == "" || filename == "-") && (stat.Mode()&os.ModeCharDevice) == 0 {
				input, err = io.ReadAll(os.Stdin)
				if err != nil {
					log.Fatal(err)
				}
			} else {
				if filename == "" {
					log.Fatal("No filename provided and no data to read from stdin")
				}
				input, err = os.ReadFile(filename)
				if err != nil {
					log.Fatal(err)
				}
			}

			req, err := admission.CreateAdmissionReviewRequest(input, params.action, params.as, params.groups, params.indent)
			if err != nil {
				log.Fatal(err)
			}

			fmt.Fprintln(os.Stdout, string(req))
		},
	}
	versionCmd = &cobra.Command{
		Use:   "version",
		Short: "Print the version of kube-review",
		Long:  `Print the version of kube-review`,
		Run: func(*cobra.Command, []string) {
			fmt.Fprintln(os.Stdout, version)
			os.Exit(0)
		},
	}
)

func Execute() {
	rootCmd.PersistentFlags().StringVar(
		&params.action,
		"action",
		"create",
		"Action to simulate (create | update | delete | connect) (default: create)",
	)
	rootCmd.PersistentFlags().StringVar(
		&params.as,
		"as",
		"kube-review",
		"Name of user",
	)
	rootCmd.PersistentFlags().StringSliceVar(
		&params.groups,
		"as-group",
		[]string{},
		"Group(s) of user (may be repeated) (default: empty)",
	)
	rootCmd.PersistentFlags().Uint8Var(
		&params.indent,
		"indent",
		2,
		"Number of spaces to indent JSON output (default: 2)",
	)
	rootCmd.AddCommand(createCmd)
	rootCmd.AddCommand(versionCmd)

	if err := rootCmd.Execute(); err != nil {
		_, _ = fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
07070100000007000081A40000000000000000000000016807DDE800000478000000000000000000000000000000000000001900000000kube-review-0.5.0/go.modmodule github.com/anderseknert/kube-review

go 1.24.2

require (
	github.com/spf13/cobra v1.9.1
	k8s.io/api v0.32.3
	k8s.io/apimachinery v0.32.3
	k8s.io/client-go v0.32.3
)

require (
	github.com/fxamacker/cbor/v2 v2.7.0 // indirect
	github.com/go-logr/logr v1.4.2 // indirect
	github.com/gogo/protobuf v1.3.2 // indirect
	github.com/google/gofuzz v1.2.0 // indirect
	github.com/google/uuid v1.6.0 // indirect
	github.com/inconshreveable/mousetrap v1.1.0 // indirect
	github.com/json-iterator/go v1.1.12 // indirect
	github.com/kr/text v0.2.0 // indirect
	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
	github.com/modern-go/reflect2 v1.0.2 // indirect
	github.com/spf13/pflag v1.0.6 // indirect
	github.com/x448/float16 v0.8.4 // indirect
	golang.org/x/net v0.38.0 // indirect
	golang.org/x/text v0.23.0 // indirect
	gopkg.in/inf.v0 v0.9.1 // indirect
	k8s.io/klog/v2 v2.130.1 // indirect
	k8s.io/utils v0.0.0-20241210054802-24370beab758 // indirect
	sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 // indirect
	sigs.k8s.io/structured-merge-diff/v4 v4.5.0 // indirect
	sigs.k8s.io/yaml v1.4.0 // indirect
)
07070100000008000081A40000000000000000000000016807DDE8000025BF000000000000000000000000000000000000001900000000kube-review-0.5.0/go.sumgithub.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E=
github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
k8s.io/api v0.32.3 h1:Hw7KqxRusq+6QSplE3NYG4MBxZw1BZnq4aP4cJVINls=
k8s.io/api v0.32.3/go.mod h1:2wEDTXADtm/HA7CCMD8D8bK4yuBUptzaRhYcYEEYA3k=
k8s.io/apimachinery v0.32.3 h1:JmDuDarhDmA/Li7j3aPrwhpNBA94Nvk5zLeOge9HH1U=
k8s.io/apimachinery v0.32.3/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE=
k8s.io/client-go v0.32.3 h1:RKPVltzopkSgHS7aS98QdscAgtgah/+zmpAogooIqVU=
k8s.io/client-go v0.32.3/go.mod h1:3v0+3k4IcT9bXTc4V2rt+d2ZPPG700Xy6Oi0Gdl2PaY=
k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk=
k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE=
k8s.io/utils v0.0.0-20241210054802-24370beab758 h1:sdbE21q2nlQtFh65saZY+rRM6x6aJJI8IUa1AmH/qa0=
k8s.io/utils v0.0.0-20241210054802-24370beab758/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 h1:gBQPwqORJ8d8/YNZWEjoZs7npUVDpVXUUOFfW6CgAqE=
sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg=
sigs.k8s.io/structured-merge-diff/v4 v4.5.0 h1:nbCitCK2hfnhyiKo6uf2HxUPTCodY6Qaf85SbDIaMBk=
sigs.k8s.io/structured-merge-diff/v4 v4.5.0/go.mod h1:N8f93tFZh9U6vpxwRArLiikrE5/2tiu1w1AGfACIGE4=
sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E=
sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY=
07070100000009000081A40000000000000000000000016807DDE8000000D9000000000000000000000000000000000000001A00000000kube-review-0.5.0/main.gopackage main

import (
	"log"

	"github.com/anderseknert/kube-review/cmd"
)

func main() {
	// Remove date/time from (likely fatal) log messages
	log.SetFlags(log.Flags() &^ (log.Ldate | log.Ltime))

	cmd.Execute()
}
0707010000000A000041ED0000000000000000000000026807DDE800000000000000000000000000000000000000000000001600000000kube-review-0.5.0/pkg0707010000000B000041ED0000000000000000000000026807DDE800000000000000000000000000000000000000000000002000000000kube-review-0.5.0/pkg/admission0707010000000C000081A40000000000000000000000016807DDE800001D4D000000000000000000000000000000000000002A00000000kube-review-0.5.0/pkg/admission/review.gopackage admission

import (
	"bytes"
	"encoding/json"
	"fmt"
	"strings"

	admissionv1 "k8s.io/api/admission/v1"
	v1 "k8s.io/api/authentication/v1"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/uuid"
	"k8s.io/apimachinery/pkg/util/yaml"
	"k8s.io/client-go/kubernetes/scheme"
)

func CreateAdmissionReviewRequest(
	input []byte,
	action string,
	username string,
	groups []string,
	indent uint8,
) ([]byte, error) {
	operation, err := actionToOperation(action)
	if err != nil {
		return nil, err
	}

	decode := scheme.Codecs.UniversalDeserializer().Decode

	object, kind, err := decode(input, nil, nil)
	if err != nil {
		// Failure to decode, likely due to unrecognized type, try unstructured
		return fromUnstructured(input, operation, username, groups, indent)
	}

	unstructured, err := runtime.DefaultUnstructuredConverter.ToUnstructured(object)
	if err != nil {
		return nil, fmt.Errorf("failed to parse object, %w", err)
	}

	return createAdmissionRequest(
		unstructured,
		*kind,
		operation,
		getUserInfo(username, groups),
		getNewObject(object, *operation),
		getOldObject(object, *operation),
		indent,
	)
}

func fromUnstructured(
	input []byte,
	operation *admissionv1.Operation,
	username string,
	groups []string,
	indent uint8,
) ([]byte, error) {
	var object any

	decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(input), 4096)

	// Try "brute forcre" serialization of unknown type
	err := decoder.Decode(&object)
	if err != nil {
		return nil, err
	}

	// If the first object is nil, it's likely an empty document.
	// We could keep reading until we have a non-nil object, but this feels like
	// an unusual case already..
	// https://github.com/anderseknert/kube-review/issues/51
	if object == nil {
		err = decoder.Decode(&object)
		if err != nil {
			return nil, err
		}
	}

	unstructured, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&object)
	if err != nil {
		return nil, fmt.Errorf("failed to parse object, %w", err)
	}

	version, err := schema.ParseGroupVersion(unstructured["apiVersion"].(string))
	if err != nil {
		return nil, err
	}

	withKind := version.WithKind(unstructured["kind"].(string))
	kind := &schema.GroupVersionKind{
		Group:   withKind.Group,
		Version: withKind.Version,
		Kind:    withKind.Kind,
	}
	userInfo := getUserInfo(username, groups)

	var unknown runtime.Unknown

	err = runtime.DefaultUnstructuredConverter.FromUnstructured(unstructured, &unknown)
	if err != nil {
		return nil, err
	}

	newObject := getUnknownRaw(&unknown, *operation)
	oldObject := getOldUnknownRaw(&unknown, *operation)

	return createAdmissionRequest(unstructured, *kind, operation, userInfo, newObject, oldObject, indent)
}

func createAdmissionRequest(
	unstructured map[string]any,
	gvk schema.GroupVersionKind,
	operation *admissionv1.Operation,
	user v1.UserInfo,
	object, oldObject runtime.RawExtension,
	indent uint8,
) ([]byte, error) {
	dryRun := true

	name, namespace := getNameAndNamespace(unstructured)
	r, _ := meta.UnsafeGuessKindToResource(gvk)
	resource := &metav1.GroupVersionResource{Group: r.Group, Version: r.Version, Resource: r.Resource}

	kind := gvkMeta(gvk.Group, gvk.Version, gvk.Kind)

	admissionRequest := &admissionv1.AdmissionRequest{
		UID:                uuid.NewUUID(),
		Kind:               *kind,
		Resource:           *resource,
		SubResource:        "", // TODO
		RequestKind:        kind,
		RequestResource:    resource,
		RequestSubResource: "", // TODO
		Name:               name,
		Operation:          *operation,
		UserInfo:           user,
		Object:             object,
		OldObject:          oldObject,
		DryRun:             &dryRun,
		Options:            getOptions(*operation),
	}
	if namespace != "" {
		admissionRequest.Namespace = namespace
	}

	admissionReview := &admissionv1.AdmissionReview{
		TypeMeta: metav1.TypeMeta{APIVersion: "admission.k8s.io/v1", Kind: "AdmissionReview"},
		Request:  admissionRequest,
	}

	var requestJSON []byte

	var err error

	if indent == 0 {
		requestJSON, err = json.Marshal(&admissionReview)
		if err != nil {
			return nil, fmt.Errorf("failed encoding object to JSON %w", err)
		}
	} else {
		requestJSON, err = json.MarshalIndent(&admissionReview, "", strings.Repeat(" ", int(indent)))
		if err != nil {
			return nil, fmt.Errorf("failed encoding object to JSON %w", err)
		}
	}

	return requestJSON, nil
}

func gvkMeta(group, version, kind string) *metav1.GroupVersionKind {
	return &metav1.GroupVersionKind{
		Group:   group,
		Version: version,
		Kind:    kind,
	}
}

func actionToOperation(action string) (*admissionv1.Operation, error) {
	actionMapper := map[string]admissionv1.Operation{
		"create":  admissionv1.Create,
		"update":  admissionv1.Update,
		"delete":  admissionv1.Delete,
		"connect": admissionv1.Connect,
	}

	var admissionAction admissionv1.Operation

	var found bool
	if admissionAction, found = actionMapper[action]; !found {
		return nil, fmt.Errorf("unknown action: %v, choose one of 'create', 'update', 'delete' or 'connect'", action)
	}

	return &admissionAction, nil
}

func getNameAndNamespace(unstructured map[string]any) (name string, namespace string) {
	metadata := unstructured["metadata"]
	if t, ok := metadata.(map[string]any); ok {
		if n, ok2 := t["name"].(string); ok2 {
			name = n
		}

		if n, ok2 := t["namespace"].(string); ok2 {
			namespace = n
		}
	}

	return name, namespace
}

func getUserInfo(username string, groups []string) v1.UserInfo {
	return v1.UserInfo{
		Username: username,
		Groups:   groups,
		UID:      string(uuid.NewUUID()),
		Extra:    map[string]v1.ExtraValue{},
	}
}

func getUnknownRaw(unknown *runtime.Unknown, action admissionv1.Operation) runtime.RawExtension {
	if action == admissionv1.Delete {
		return runtime.RawExtension{}
	}

	return runtime.RawExtension{
		Object: unknown,
	}
}

func getNewObject(object runtime.Object, action admissionv1.Operation) runtime.RawExtension {
	if action == admissionv1.Delete {
		return runtime.RawExtension{}
	}

	return runtime.RawExtension{
		Object: object.DeepCopyObject(),
	}
}

func getOldUnknownRaw(unknown *runtime.Unknown, action admissionv1.Operation) runtime.RawExtension {
	if action == admissionv1.Create || action == admissionv1.Connect {
		return runtime.RawExtension{}
	}

	return runtime.RawExtension{
		Object: unknown,
	}
}

func getOldObject(object runtime.Object, action admissionv1.Operation) runtime.RawExtension {
	if action == admissionv1.Create || action == admissionv1.Connect {
		return runtime.RawExtension{}
	}

	return runtime.RawExtension{
		Object: object.DeepCopyObject(),
	}
}

func getOptions(action admissionv1.Operation) runtime.RawExtension {
	switch action {
	case admissionv1.Create:
		return runtime.RawExtension{Object: &metav1.CreateOptions{
			TypeMeta: metav1.TypeMeta{
				Kind:       "CreateOptions",
				APIVersion: "meta.k8s.io/v1",
			},
		}}
	case admissionv1.Update:
		return runtime.RawExtension{Object: &metav1.UpdateOptions{
			TypeMeta: metav1.TypeMeta{
				Kind:       "UpdateOptions",
				APIVersion: "meta.k8s.io/v1",
			},
		}}
	case admissionv1.Delete:
		return runtime.RawExtension{Object: &metav1.DeleteOptions{
			TypeMeta: metav1.TypeMeta{
				Kind:       "DeleteOptions",
				APIVersion: "meta.k8s.io/v1",
			},
		}}
	case admissionv1.Connect:
		return runtime.RawExtension{}
	default:
		panic(fmt.Sprintf("unknown action: %v", action))
	}
}
0707010000000D000081A40000000000000000000000016807DDE80000043F000000000000000000000000000000000000002F00000000kube-review-0.5.0/pkg/admission/review_test.gopackage admission

import (
	"encoding/json"
	"os"
	"testing"

	v1 "k8s.io/api/admission/v1"
)

func TestBasicReview(t *testing.T) {
	t.Parallel()

	manifest := mustReadFileString(t, "testdata/in.yaml")

	reviewBytes, err := CreateAdmissionReviewRequest(
		[]byte(manifest),
		"create",
		"kube-review",
		[]string{"system:masters"},
		2,
	)
	if err != nil {
		t.Fatal(err)
	}

	var review v1.AdmissionReview

	err = json.Unmarshal(reviewBytes, &review)
	if err != nil {
		t.Fatal(err)
	}
}

func TestReviewMultipleDocsFirstOneEmpty(t *testing.T) {
	t.Parallel()

	manifest := mustReadFileString(t, "testdata/twodocsfirstempty.yaml")

	reviewBytes, err := CreateAdmissionReviewRequest(
		[]byte(manifest),
		"create",
		"kube-review",
		[]string{"system:masters"},
		2,
	)
	if err != nil {
		t.Fatal(err)
	}

	var review v1.AdmissionReview

	err = json.Unmarshal(reviewBytes, &review)
	if err != nil {
		t.Fatal(err)
	}
}

func mustReadFileString(t *testing.T, path string) string {
	t.Helper()

	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatal(err)
	}

	return string(data)
}
0707010000000E000041ED0000000000000000000000026807DDE800000000000000000000000000000000000000000000002900000000kube-review-0.5.0/pkg/admission/testdata0707010000000F000081A40000000000000000000000016807DDE800000137000000000000000000000000000000000000003100000000kube-review-0.5.0/pkg/admission/testdata/in.yamlapiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx
        name: nginx
        ports:
        - containerPort: 8080
07070100000010000081A40000000000000000000000016807DDE80000005C000000000000000000000000000000000000004000000000kube-review-0.5.0/pkg/admission/testdata/twodocsfirstempty.yaml# empty
---
apiVersion: foo/v1alpha1
kind: foo
metadata:
  name: foo-bar-123
spec:
  bar: 1
07070100000011000041ED0000000000000000000000026807DDE800000000000000000000000000000000000000000000001700000000kube-review-0.5.0/test07070100000012000041ED0000000000000000000000026807DDE800000000000000000000000000000000000000000000002100000000kube-review-0.5.0/test/manifests07070100000013000081A40000000000000000000000016807DDE800000141000000000000000000000000000000000000003100000000kube-review-0.5.0/test/manifests/deployment.yamlapiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - image: nginx
          name: nginx
          ports:
            - containerPort: 8080
07070100000014000081A40000000000000000000000016807DDE800000129000000000000000000000000000000000000002D00000000kube-review-0.5.0/test/manifests/policy.yamlapiVersion: config.kio.kasten.io/v1alpha1
kind: Policy
metadata:
  name: sample-custom-backup-policy
  namespace: kasten-io
spec:
  comment: My sample custom backup policy
  frequency: '@daily'
  retention:
    daily: 30
    weekly: 4
    monthly: 12
    yearly: 7
  actions:
    - action: backup
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!94 blocks
openSUSE Build Service is sponsored by