Commit Graph

54 Commits

Author SHA1 Message Date
Dave Protasowski cff115c2dd Refactor webhook to allow adding conversion support (#989)
* Refactor webhook to allow adding conversion support

* pr feedback

* fix memory leak

* We can use mux.Handle

* move admission integration tests to separate file
2020-01-20 09:20:05 -08:00
Slavomir Kaslev f890690397 De-race webhook integration tests (#938)
Webhook integration tests occasionally fail with on testgrid, e.g.
  https://prow.knative.dev/view/gcs/knative-prow/logs/ci-knative-pkg-continuous/1204193472353931264
  https://prow.knative.dev/view/gcs/knative-prow/logs/ci-knative-pkg-continuous/1203166664988823552

Fix this by waiting for all goroutines to finish before each test ends.
2019-12-13 06:59:54 -08:00
Matt Moore a55e24e80c Remove temporary logic to allow shared paths in webhook. (#943)
* Remove temporary logic to allow shared paths in webhook.

* Update webhook/webhook.go

Co-Authored-By: Victor Agababov <vagababov@gmail.com>
2019-12-12 11:14:52 -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
Markus Thömmes 56c2594e4f Assorted linting fixes. (#840)
* Remove unused code.

* Remove unneeded loops.

* Remove unneeded Printf calls.

* Use time.Since instead of time.Now().Sub.

* Remove unused values.

* Rename error variable according to conventions.

* Return error last.

* Simplify array allocations.

* Remove leaky ticker.

* Remove Yoda conditions.

* Remove deprecated function to talk to GKE.

* Remove dot import.

* Remove empty critical section and replace with a channel operation.

* Add linter directives to explicitly state wanted weirdness.

* Update deps.

* Fix broken line.
2019-11-01 12:49:12 -07:00
Matt Moore d4ce001394 This refactors our core webhook logic to be reconciler-based. (#833)
This is the culmination of a large number of changes to refactor our webhook logic, and adopt a reconciler-based approach to make it resilient to unexected system events (e.g. rogue GCs!).

For more details on how this is consumed, see the new `webhook/README.md`.

Fixes: https://github.com/knative/pkg/issues/782
Closes: https://github.com/knative/pkg/issues/529
Fixes: https://github.com/knative/pkg/issues/450
Related: https://github.com/knative/pkg/issues/141
2019-10-31 10:17:13 -07:00
Matt Moore 3732de5802 Split secret creation into our reconciler resources style. (#830) 2019-10-29 23:08:11 -07:00
Matt Moore 7772e2f583 Drive GetCertificate from the lister cache of a secret informer. (#825) 2019-10-29 07:11:12 -07:00
Matt Moore bfff3b7d72 Switch to using GetCertificate in tls.Config. (#823)
GetCertificate allows us to start in TLS mode and dynamically fetch new certificates as they change.  This will eventually allow us to decouple the cert creation process from the core webhook logic, and in a subsequent change service this from a secret lister cache.
2019-10-28 17:32:11 -07:00
Matt Moore da49e89aa8 Remove options to specify ClientAuth. (#822)
We don't use this anywhere in Knative downstream and it adds a bunch of complexity.
2019-10-28 16:50:11 -07:00
Matt Moore 763c642d3c Streamline `webhook.New`. (#821)
This now pulls most of its configuration from context, which brings it a step closer to aligning with our `sharedmain` package.
2019-10-28 16:12:11 -07:00
Matt Moore 3f2100ca91 Move WithContext into the resource admission controller. (#820) 2019-10-28 15:05:11 -07:00
Matt Moore aaf36e26c7 Accept a list of AdmissionControllers instead of a map (#819) 2019-10-28 14:09:11 -07:00
Matt Moore de53b8f09f Move hook-specific configuration options out of shared options. (#818)
This builds on https://github.com/knative/pkg/pull/817 and makes further
breaking changes. The options pertinent to each admission controller are
now passed to their respective constructors, which leads to a cleaner
options struct, and better prepares for greater webhook diversity.
2019-10-28 13:31:11 -07:00
Matt Moore 070396a075 Eliminate the Namespace config option in favor of system.Namespace. (#817) 2019-10-28 11:41:43 -07:00
Matt Moore cad41c40cc Stop using OwnerRefs for webhook config lifecycle (#802)
* Stop using OwnerRefs for webhook config lifecycle

This changes the model by which we manage the lifecycle of our
`{mutating,validating}webhookconfiguration`, which previously used an owner ref
from the cluster-scoped configuration to the namespace-scoped Deployment.  The
new model adds an explicit yaml file for the webhook, which omits the fields
filled in by the deployment as it starts.

A few notable elements of this change:
1. Clear out OwnerReferences explicitly (avoids the linked bug),
2. Periodically reruna `Register()` to ensure our webhook exists,
3. Simplified logic around registration (all we need now is update!).

Related: https://github.com/knative/serving/issues/5845

* Incorporate feedback from @dgerd and a few other nits I noticed.
2019-10-25 11:53:35 -07:00
Nima Kaviani d90ec6a015 add config validation as admission controller (#636) 2019-09-22 07:23:10 -07:00
Nima Kaviani c39ee25c42 rename the variable for resource validation webhook (#653) 2019-09-11 06:40:29 -07:00
mattmoor-sockpuppet 014d54e62f golang format tools (#637)
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-09-06 07:26:05 -07:00
Nima Kaviani c270532140 introduce an interface for AdmissionControllers (#622) 2019-09-04 09:03:02 -07:00
Nima Kaviani 9118872a32 Refactor admission webhook (#595)
- decouple the webhool server from the controller
- move tests to respective files
2019-08-27 20:39:40 -07:00
Victor Agababov 74c5d67ea0 Fix the issues pointed out by staticcheck (#541)
* Fix the issues pointed out by staticcheck

* review fix
2019-07-23 13:13:36 -07:00
Annie Fu a68e009041 Add check for nil StatsReporter in webhook package (#518)
* Prevent nil StatsReporter for existing webhook package consumers

* Pass StatsReporter by pointer and have tests test constructor

* Make constructor return error instead of panicking

* Move StatsReporter to ControllerOptions to consolidate constructors
2019-07-09 17:23:58 -07:00
Annie Fu 84d3910c56 Add metrics to webhook package (#503)
* Add metrics to webhook package

Add metricstest package for shared helper functions for testing metrics

* Address PR

* Cleanup

* Fix import paths to fix build issues

* Fix import package path for test file

* Remove unnecessary formatting from error message

* Remove helper function only used once

* Add metric name to all error messages, make checkRowTags testing helper function

* Add common histogram bucket generator function to metrics package

* Fix CheckStatsNotReported check

* Reset metrics before each test so the tests are idempotent

* Make CheckStatsNotReported conditional clearer
2019-07-08 16:00:44 -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
Matt Moore 262650b2c0 Incorporate the sub-resource context into the context state populated by the webhook. (#442) 2019-06-05 20:36:39 -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 2adf7f0c98 Add a few more general contexts built in serving. (#384)
Fix the user info annotation bug introduced along with the context stuff.

Fixes: https://github.com/knative/pkg/issues/383
2019-04-11 07:44:59 -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
Ville Aikas 8b3dc0d76d Use apps.Deployment instead of extensions.Deployment (#345)
* Use apps.Deployment instead of extensions.Deployment

* import as appsv1 instead of v1
2019-03-27 13:17:52 -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 04154dda9a Allow webhook implementations to optionally disallow unknown fields. (#338)
Related: https://github.com/knative/serving/issues/3309
2019-03-25 17:52:49 -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
Matt Moore 35d3a1b0d4 Modify the webhook to allow the use of duck types. (#323)
* Modify the webhook to allow the use of duck types.

This change enables us to define a duck type that applies to a whole class of GroupVersionKinds and leverage it to perform generic validation, defaulting, etc.

Fixes: #322

* Fix typo
2019-03-16 11:10:45 -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
Dave Protasowski 829b886f7e Don't close the http.Request body (#277)
As per net.http package for `http.Request.Body`

```
        // The Server will close the request body. The ServeHTTP
        // Handler does not need to.
```
2019-02-14 07:01:44 -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
Victor Agababov dc1adcf1df Cleanup the webhook code. (#272)
* Cleanup the webhook code.

- add more tests
- fix formatting
- fix logging and errors
- use shorthands
- some optimizations in types
- make code more Go'ey from C'ey.

* raise test coverage
2019-02-12 09:12:44 -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
Zrss d3fbe1d459 Clean useless unregister mutatingwebhookconfiguration process (#136) 2018-10-25 09:23:32 -07:00
Zrss 2b28d46464 Make clientAuth of webhook server into a configuration option (#125) 2018-10-24 08:42:31 -07:00
Zrss d82a0a3d1c Exit when bootstrap http server of webhook error (#131)
* Exit when bootstrap http server of webhook error

* Clean useless newRunningTestAdmissionController func

* return server.Close() err
2018-10-23 13:56:31 -07:00
lichuqiang 3c11bc6a2f fix bug of generating plural in webhook (#133)
* fix bug when generating plural in webhook

* dep ensure

* remove unused comment
2018-10-22 21:02:30 -07:00
jonjohnsonjr c1fcae7b28 Allow unknown JSON fields (#129)
This enables us to make additive changes without breaking downgrades.

Unfortunate side effect is that we don't get a nice typo checker in the
webhook :(
2018-10-21 06:23:29 -07:00
Zrss 2b0d4fc1cc Prints requestheader-client-ca-file instead of ca.crt (#123) 2018-10-11 07:24:26 -07: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 e71b1a477d Create a helper for synthesizing patches. (#87) 2018-09-24 15:36:20 -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