Commit Graph

37 Commits

Author SHA1 Message Date
Dave Protasowski ee1db869c7
Update linter config and address lint warnings/failures (#3068)
* fix whitespace linter

* fix usestdlibvars

* fix staticheck

* ignore spancheck warning

* fix linter perfsprint

* fix nolintlint feedback

* fix nilerr lint checks

* fix misspell

* fix mirror lint

* fix intrange linter

* fix gofumpt linter

* fix gosec linter - ignore warning since default min tls version is 1.3

* fix gocritic linter

* fix whitespace

* fix fatcontext linter

* fix errorlint

* fix errname linter

* fix copyloopvar (go1.22) linter

* fix bodyclose linter

* update linter config

* add script to format code

* fix unit test
2024-06-25 14:49:36 +00:00
Dave Protasowski 8535fcc248
gofumpt the repo (#3067)
* gofumpt the repo

* don't prefix numbers with 0 - otherwise they're octal
2024-06-25 07:27:07 +00:00
Ville Aikas f1f36a2c97
Fix subresource update logic. (#2546)
* Fix subresource update logic.

Signed-off-by: Ville Aikas <vaikas@chainguard.dev>

* Rename IsInSubResourceUpdate => GetUpdatedSubresource

Signed-off-by: Ville Aikas <vaikas@chainguard.dev>
2022-07-15 18:32:28 +00:00
Paul Schweigert 5569169b0c
update boilerplate date (#2539)
Signed-off-by: Paul S. Schweigert <paulschw@us.ibm.com>
2022-06-30 22:25:31 +00:00
Matt Moore 16b36b7fca
Add support for admission webhook warnings. (#2498)
* Add support for admission webhook warnings.

This extends `apis.FieldError` to support designating certain FieldErrors as "warnings" (or explicitly as "errors", however, this is the default for back-compat).

You can turn an `apis.FieldError` into a warning using: `fe.At(apis.WarningLevel)` or force it into an error using: `fe.At(apis.ErrorLevel)`.

You can get the errors at a particular diagnostic level using: `fe.Filter(apis.WarningLevel)`.

This change also hooks this into the admission webhook infrastructure to support surfacing the "warning" level `apis.FieldError`s via the `Warnings` section of the `AdmissionResponse`.

Fixes: #2497

* Add a comment about the use of defer.
2022-05-02 21:56:57 +00:00
Pierangelo Di Pilato 0a429cba1c
Allow Unstructured callback from Defaulting Webhook (#2363)
* Add support for callback defaults

Signed-off-by: Pierangelo Di Pilato <pdipilat@redhat.com>

* Put unstr object in ctx and set user info

Signed-off-by: Pierangelo Di Pilato <pdipilat@redhat.com>

* Move get callback at the top

Signed-off-by: Pierangelo Di Pilato <pdipilat@redhat.com>

* Panic when using delete verb

Signed-off-by: Pierangelo Di Pilato <pdipilat@redhat.com>

* Split tests and add callback ctx tests

Signed-off-by: Pierangelo Di Pilato <pdipilat@redhat.com>

* Set user info annotations

Signed-off-by: Pierangelo Di Pilato <pdipilat@redhat.com>

* Register Webhook Rules from callbacks

Signed-off-by: Pierangelo Di Pilato <pdipilat@redhat.com>

* Adapt unstructured objects to apis.HasSpec

Signed-off-by: Pierangelo Di Pilato <pierdipi@redhat.com>

* Change json tag name to match struct field name

Signed-off-by: Pierangelo Di Pilato <pierdipi@redhat.com>
2022-01-14 06:18:42 -08:00
knative-automation e61a20dd64
Update actions (#2313)
Signed-off-by: Knative Automation <automation@knative.team>
2021-10-15 12:26:13 -07:00
Dave Protasowski 6484377731
update boilerplate date (#2134) 2021-05-28 13:21:29 -07:00
Markus Thömmes 980a33719a
Fix revive related linting issues (#2131) 2021-05-26 01:10:28 -07:00
Victor Agababov a371418524
v2 (#1754) 2020-09-29 13:18:29 -07:00
Markus Thömmes 5fbbde31b3
Align linters with serving (enables stylecheck and asciicheck) (#1738) 2020-09-23 07:37:40 -07:00
Victor Agababov f6cfa4c47c
Clean context.TODO in pkg and other minor nits (#1337)
- TODO is for migration, we know we want background there
- other nits
2020-05-15 10:58:02 -07:00
whaught d22642244e
Allow Unstructured callback from Validating Webhook (#1172)
* Add new callback pattern to pkg

* include the context

* typo

* Remove the empty instance of unstructured

* initialize the unstructured var

* Eliminate the unneeded pointer

* Pass a pointer to unstructured callback

* Create a validation specific context struct

* Move callback tests to own unit test case

* Switch from converting to decoding

* Update webhook/resourcesemantics/validation/validation.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* don't wrap context and include params

* split validation files

* include 2020 copyright

* include unit test for WithKubeClient

* Don't bother updating copyright date

* Inclue a unit test for panic

* Move dryRun to context

* Include context dry run unit test

* put the request operation in the context

* eliminate circular dep

* move kubeclient test out of context_test

* dont bother iterating callback map

* Callback takes a list of supported verbs

* Remove extra type

* Ensure Callback interface is public

* Alias Operation into validation

* alias Operation right in Webhook

* Update webhook/resourcesemantics/validation/validation_admit.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* Update webhook/resourcesemantics/validation/validation_admit_test.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* Update webhook/resourcesemantics/validation/validation_admit_test.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* Update webhook/resourcesemantics/validation/validation_admit.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* Update webhook/resourcesemantics/validation/validation_admit.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* Update webhook/resourcesemantics/validation/validation_admit_test.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>

* correct parens

* minor style fixes

* Rename Callback to Func

* Fix build error

* Switch callback to take a list with a factory

* keep descriptive names

* update comment

* Drop pointer, correct comments

* Add a unit test to disallow duplicate verbs

* fix comments, struct{} for set

* switch to variadic arg for NewCallback

Co-authored-by: Victor Agababov <vagababov@gmail.com>
2020-04-06 12:22:19 -07:00
Scott Nichols 298f22bea6 update boilerplate to use 2020 (#979) 2020-01-07 16:04:51 -08:00
Matt Moore 891c2876dd Implement a base library for implementing "Pod Spec"-able bindings. (#915)
This PR adds facilities to make it easier to create both components of a Binding
over "Pod Spec"-able resources.  Rather than rehashing it all here, please look
at `./pkg/webhook/psbinding/README.md` for more details.
2019-12-02 08:58:34 -08:00
Matt Moore 9f41433241 Add a simple ToUnstructured method for converting our types to unstructured. (#900)
This adds a ToUnstructured method to complement the FromUnstructured method
we have had for some time.  The ToUnstructured method is effectively scoped
to Knative-style types since we expect it to implement both kmeta.Accessor
and kmeta.OwnerRefable in order to ensure that the TypeMeta is always
properly populated.
2019-11-26 10:05:21 -08:00
Matt Moore 4836f680bb Split the resource semantic webhooks into separate AdmissionControllers (#848)
By combining our validation logic into our mutating webhook we were previously allowing for mutating webhooks evaluated after our own to modify our resources into invalid shapes.  There are no guarantees around ordering of mutating webhooks (that I could find), so the only way to remedy this properly is to split apart the two into separate webhook configurations:
 - `defaulting`: which runs during the mutating admission webhook phase
 - `validation`: which runs during the validating admission webhook phase.

The diagram in [this post](https://kubernetes.io/blog/2019/03/21/a-guide-to-kubernetes-admission-controllers/) is very helpful in illustrating the flow of webhooks.

Fixes: https://github.com/knative/pkg/issues/847
2019-11-14 16:51:02 -08:00
Matt Moore e4ac97c252 Update our dependency on K8s libs to 1.15.3 (#686)
With a minimum K8s version of 1.14 (starting in 0.10), 1.15.3 puts us in the center of the +/-1 version window of support.
2019-09-18 13:36:48 -07:00
mattmoor-sockpuppet 1864f499dc golang format tools (#497)
Produced via:
  `gofmt -s -w $(find -path './vendor' -prune -o -type f -name '*.go' -print))`
  `goimports -w $(find -name '*.go' | grep -v vendor)`
/assign @mattmoor
2019-06-27 07:37:08 -07:00
Matt Moore 222dd25986 Migrate pkg to use the knative.dev/pkg import path (#489)
* Manual changes.

* scripted changes.
2019-06-26 13:02:06 -07:00
Ali Ok 9f8e0692b7 #457 Duck type user annotation logic (#467)
* #457 Duck type user annotation logic

* #457 Duck type user annotation logic - tests

* #457 Revert updater annotation key from lastModifier to updater

* #457 Rename HasSpec#GetSpec() to HasSpec#GetUntypedSpec()

* #457 Fix some indentation

* #457 Get group for user info annotations from the request

* #457 Reduce confusuion in webhook testing by using same group
2019-06-24 18:20:05 -07:00
mattmoor-sockpuppet 105f928666 golang format tools (#397)
Produced via:
  `gofmt -s -w $(find -path './vendor' -prune -o -type f -name '*.go' -print))`
  `goimports -w $(find -name '*.go' | grep -v vendor)`
2019-04-28 07:59:30 -07:00
Scott Nichols 70ab9cc77d Adding Strict Validation based on struct.*Deprecated*Foo (#339)
* have simple tests. working on impl.

* strict setting, reflection based.

* ran codegen.

* adding license.

* update based on feedback and merge better.

* getting closer to something  simpler assuming shallow reflect.

* adding validation test.

* use the json tag.

* Golang things nil typed pointers are not nil.

* Use real value of reflect invalid.

* add a missing test.

* two methods, one for update, one for single check.

* checkdep is now in apis.

* fix pkg.

* Update apis/deprecated_test.go

Co-Authored-By: n3wscott <32305648+n3wscott@users.noreply.github.com>

* add code clarity.

* include inlined struct objects recursively.

* Update commnets and add a flatten error test for inlined.
2019-04-19 09:19:27 -07:00
Matt Moore 2b574edcd7 Deprecate apis.Immutable and apis.Annotatable. (#368)
This deprecates the `apis.Immutable` and `apis.Annotatable` interfaces,
which were both awkward niche extensions of `apis.Validatable` and
`apis.SetDefaults` for specific contexts that the former set didn't
cover well.

With this change, the expectation is that types that want to check
for immutability will instead access the "baseline" object via the
context from within updates.  For example:

```
func (new *Type) Validate(ctx context.Context) *apis.FieldError {
  if apis.IsInUpdate(ctx) {
    old := apis.GetBaseline(ctx).(*Type)
    // Update specific validation based on new and old.
  }
}
```

For applying user annotations, the type writer can write:

```
func (new *Type) SetDefaults(ctx context.Context) {
  if apis.IsInCreate(ctx) {
    ui := apis.GetUserInfo(ctx)
    // Set creator annotation from ui
  }

  if apis.IsInUpdate(ctx) {
    ui := apis.GetUserInfo(ctx)
    old := apis.GetBaseline(ctx).(*Type)
    // Compare old.Spec vs. new.Spec and on changes
    // update the "updater" annotation from ui.
  }
}
```

One of the key motivations for this refactoring was to enable us
to do more powerful validation in `apis.Validate` beyond the niche
of immutability checking (and without introducing yet-another
one-off niche interface).  In the BYO Revision name PoC I abused
`apis.Immutable` to do more arbitrary before/after validation,
which with this can simply be a part of `apis.Validatable`.

See: https://github.com/knative/serving/pull/3562

The general stance on deprecating interfaces such as these will be
to deprecate them in a non-breaking way (via a comment for now). They
will be hollowed out when the functionality is removed from the webhook,
but left in because of diamond dependency problems.  In this change
we remove the `apis.Annotatable` functionality and deprecate the
`apis.Immutable` functionality.
2019-04-08 10:26:58 -07:00
Matt Moore 281cda84ce Move Condition stuff to apis, add a v1beta1 Status. (#361)
This moves the common Condition stuff to apis, and creates a v1beta1 form of Status that uses the Condition it defines (changing this in v1alpha1 is too breaking).

There aren't really any meaningful changes in this PR, mostly reorganization.  Enumerating what I did:
1. Copied `condition_set*.go` to `apis/`,
1. Copied the `Condition` portions of `conditions_types.go` to `apis/`,
1. Copied the balance of `conditions_types.go` to `apis/duck/v1beta1/status_types.go`,
1. Changed the parts of the above to reference things in the appropriate new places,
1. Removed the reflection-based `ConditionsAccessor` stuff, implementing it instead on `duckv1beta1.Status`.
1. Incorporate: https://github.com/knative/pkg/pull/358
2019-04-02 09:51:55 -07:00
Thomas Shafer 1d9d8f8871 Fix lint error: Address struct field naming (#352)
Ran ./hack/update-codegen.sh
2019-03-29 10:23:54 -07:00
Matt Moore 0f749ef7d5 This creates a way for clients of the webhook to decorate the request context. (#342)
Clients of webhook can now decorate the request context with additional metadata
via:
```
  ac := &AdmissionController{
    ... // As before
    WithContext: func(ctx context.Context) context.Context {
      // logic to attach stuff to ctx
    }
  }
```

This metadata can then be accessed off of the context in methods like
`SetDefaults` and `Validate` on types registered as webhook handlers.

Fixes: https://github.com/knative/pkg/issues/306
2019-03-26 21:33:51 -07:00
Matt Moore 60fdcbcabd This threads a context.Context through the webhook interfaces we expose. (#332)
Related to: https://github.com/knative/pkg/issues/306
2019-03-21 10:48:48 -07:00
Dave Protasowski 0183bf9cdc Drop spec.generation support (#234)
* Drop webhook logic to increment spec.generation

With Kubernetes 1.11+ metadata.generation now increments properly
when the status subresource is enabled on CRDs

For more details see: https://github.com/knative/serving/issues/643

* Drop the generational duck type
2019-02-14 08:29:45 -08:00
Victor Agababov 1982208dd9 Initial commit for the webhook to set the annotations about mutator. (#275)
* Initial commit for the webhook to set the annotations about mutator.

The user that created or updated the resource will be set in the
annotations.

* update comments

* remove debug logging

* logging :/

* logging :/, returns

* logging :/ III

* error wrap

* simplify test

* rename the test

* add pkg/errors to the deps for better errors

* do not require CRD to implement Annotatable

* review issues

* fix interface as required by review
2019-02-12 21:03:43 -08:00
Adam Harwayne 25b3f456f0 Webhook creates a patch for all fields generated by Go (#243)
* Webhook creates a patch for all fields generated by round tripping the JSON through Golang types.

* Add unit tests for InnerDefaultResource.

* Linter errors.

* PR comments - test changes

* t.Helper()

* PR comments.
2019-02-06 14:32:40 -08:00
Matt Moore c267dfecb7 This exempts defaulting from the rules governing field immutability. (#191)
Immutable fields with default values may now be changed iff they change is to populate their default value.  This is to support defaulting in the scenario where an object was created long ago and a new field (with a default!) is added.  When controllers attempt to mutate the object status today, this would create a webhook rejection!  With this change, we compare against a freshly defaulted "old" object to exclude newly defaulted fields from the immutability check.

We saw this in knative/serving for the newly added TimeoutSeconds field in Revision (otherwise immutable), which I believe it leading to upgrade testing flakes since post-upgrade Revision status updates will fail.
2018-12-05 13:40:26 -08:00
Vincent Demeester 781d6bbc47 Move the use of `VerifyType` in tests (#98)
* Change VerifyType to return an error instead of panicking

Signed-off-by: Vincent Demeester <vdemeest@redhat.com>

* Move the use of `VerifyType` in tests

Those calls to `duck.VerifyType` are done at runtime and thus could be
costly at program startup. Putting them under tests ensure we still
assert those types but during unit testing.

Signed-off-by: Vincent Demeester <vdemeest@redhat.com>
2018-09-27 15:16:22 -07:00
Matt Moore 3473880674 Informers / Listers for Duck Types. (#86)
This starts to sketch common libraries for instantiating informers/listers for a particular GroupVersionResource as one of our duck types.

You can instantiate a duck.InformerFactory like so:
```go
        dynaClient, err := dynamic.NewForConfig(cfg)
        if err != nil {
                logger.Fatalf("Error building dynamic clientset: %v", err)
        }

	// Cache as the outermost layer so we only register the EventHandler once.
        dif := &duck.CachedInformerFactory{
                Delegate: &duck.EnqueueInformerFactory{
			Delegate: &duck.TypedInformerFactory{
        	                Client:       dynaClient,
                	        Type:         &duckv1alpha1.Target{},
                        	ResyncPeriod: 30 * time.Second,
	                        StopChannel:  stopCh,
			},
			EventHandler: cache.ResourceEventHandlerFuncs{
				AddFunc: func(obj interface{}) {
					// Enqueue, obj is: *duckerv1alpha1.Target
				},
				UpdateFunc: func(old, new interface{}) {
					// Enqueue, old and new are: *duckerv1alpha1.Target
				},
			},
                },
        }
```

Then, as you come across new GroupVersionResources that you want to handle:
```go
        informer, lister, err := dif.Get(gvr)
        if err != nil {
               logger.Fatalf("Error starting shared index informer: %v", err)
        }
```

With the `duck.TypedInformerFactory` the objects will be returned as the provided `Type:`, so in this example, you could safely write:
```go
        elt, err := lister.ByNamespace(ns).Get(name)
        if err != nil { ... }

        target := elt.(*duckv1alpha1.Target)
        // Stuff involving target.
```
2018-09-24 20:10:20 -07:00
Matt Moore f81d0f8f0f Define an interface for interacting with Listable objects. (#85)
This will help us build informers from the dynamic API client.
2018-09-21 14:34:19 -07:00
Matt Moore c15d7c8f22 Eliminate custom methods from GenericCRD (#78)
* Prune the GenericCRD spec to what is used.

Encapsulate our change detection slightly.

* Support common spec mutations via duck typing.

This adds support for performing common mutations to objects via duck types and JSON patching.

Fixes: https://github.com/knative/pkg/issues/76

* Eliminate getSpecJSON thru schemaless duck typing.

This leverages a one-off trick to get the JSON of the spec field from arbitrary types.
2018-09-18 14:25:19 -07:00
Matt Moore fdf2fdcd93 Move the test resource out of `./webhook`. (#32)
This is so that other things can more naturally write tests using this same test resource.
2018-07-31 16:02:37 -07:00