Skip to content

Commit

Permalink
Merge branch 'master' into opent
Browse files Browse the repository at this point in the history
Signed-off-by: Jaydipkumar Arvindbhai Gabani <[email protected]>
  • Loading branch information
JaydipGabani authored Oct 24, 2023
2 parents ecfbaac + c5798c9 commit 118cf5f
Show file tree
Hide file tree
Showing 11 changed files with 112 additions and 11 deletions.
2 changes: 2 additions & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# These owners are the maintainers and approvers of this repo
* @open-policy-agent/gatekeeper-maintainers
6 changes: 6 additions & 0 deletions config/crd/kustomization.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ patchesJson6902:
kind: CustomResourceDefinition
name: assignimage.mutations.gatekeeper.sh
path: patches/max_name_size.yaml
- target:
group: apiextensions.k8s.io
version: v1
kind: CustomResourceDefinition
name: expansiontemplate.expansion.gatekeeper.sh
path: patches/max_name_size.yaml

patchesStrategicMerge:
#- patches/max_name_size_for_modifyset.yaml
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ spec:
description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
type: string
metadata:
properties:
name:
maxLength: 63
type: string
type: object
spec:
description: ExpansionTemplateSpec defines the desired state of ExpansionTemplate.
Expand Down
4 changes: 4 additions & 0 deletions manifest_staging/deploy/gatekeeper.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2311,6 +2311,10 @@ spec:
description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
type: string
metadata:
properties:
name:
maxLength: 63
type: string
type: object
spec:
description: ExpansionTemplateSpec defines the desired state of ExpansionTemplate.
Expand Down
3 changes: 3 additions & 0 deletions pkg/expansion/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ func ValidateTemplate(template *expansionunversioned.ExpansionTemplate) error {
if k == "" {
return fmt.Errorf("ExpansionTemplate has empty name field")
}
if len(k) >= 64 {
return fmt.Errorf("ExpansionTemplate name must be less than 64 characters")
}
if template.Spec.TemplateSource == "" {
return fmt.Errorf("ExpansionTemplate %s has empty source field", k)
}
Expand Down
18 changes: 18 additions & 0 deletions pkg/expansion/system_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,24 @@ func TestValidateTemplate(t *testing.T) {
}),
errFn: matchErr("empty name"),
},
{
name: "name too long",
temp: *fixtures.NewTemplate(&fixtures.TemplateData{
Name: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
Apply: []match.ApplyTo{{
Groups: []string{"apps"},
Kinds: []string{"Deployment"},
Versions: []string{"v1"},
}},
Source: "spec.template",
GenGVK: expansionunversioned.GeneratedGVK{
Group: "",
Version: "v1",
Kind: "Pod",
},
}),
errFn: matchErr("less than 64"),
},
{
name: "missing source",
temp: *fixtures.NewTemplate(&fixtures.TemplateData{
Expand Down
3 changes: 0 additions & 3 deletions pkg/gator/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,6 @@ var (
// object or oldObject for the underlying framework to review.
// This mimicks the k8s api server behvaior.
ErrNoObjectForReview = errors.New("no object or oldObject found to review")
// ErrNilOldObject indicates that the AdmissionRequest did not provide an oldObject.
// Gatekeeper expects oldObject to be non nil on DELETE operations.
ErrNilOldObject = errors.New("oldObject is nil")
// ErrInvalidYAML indicates that a .yaml/.yml file was not parseable.
ErrInvalidYAML = errors.New("invalid yaml")
// ErrUnmarshallObject happens when the yaml defines an invalid object or oldObject.
Expand Down
3 changes: 1 addition & 2 deletions pkg/gator/verify/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,10 +358,9 @@ func (r *Runner) validateAndReviewAdmissionReviewRequest(ctx context.Context, c
}
}

// parse into webhook/admission type
req := &admission.Request{AdmissionRequest: *ar.Request}
if err := util.SetObjectOnDelete(req); err != nil {
return nil, fmt.Errorf("%w: %w", gator.ErrNilOldObject, err)
return nil, fmt.Errorf("%w: %w", gator.ErrInvalidK8sAdmissionReview, err)
}

arr := target.AugmentedReview{
Expand Down
2 changes: 1 addition & 1 deletion pkg/gator/verify/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1155,7 +1155,7 @@ func TestRunner_Run(t *testing.T) {
{Name: "invalid admission review object", Error: gator.ErrInvalidK8sAdmissionReview},
{Name: "missing admission request object", Error: gator.ErrMissingK8sAdmissionRequest},
{Name: "no objects to review", Error: gator.ErrNoObjectForReview},
{Name: "no oldObject on delete", Error: gator.ErrNilOldObject},
{Name: "no oldObject on delete", Error: gator.ErrInvalidK8sAdmissionReview},
},
},
{
Expand Down
2 changes: 1 addition & 1 deletion pkg/util/request_validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
)

// nolint: revive // Moved error out of pkg/webhook/admission; needs capitalization for backwards compat.
var ErrOldObjectIsNil = errors.New("For admission webhooks registered for DELETE operations, please use Kubernetes v1.15.0+.")
var ErrOldObjectIsNil = errors.New("oldObject cannot be nil for DELETE operations")

// SetObjectOnDelete enforces that we use at least K8s API v1.15.0+ on DELETE operations
// and copies over the oldObject into the Object field for the given AdmissionRequest.
Expand Down
76 changes: 72 additions & 4 deletions website/docs/gator.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,14 +260,12 @@ the `run` flag:
gator verify path/to/suites/... --run "disallowed"
```
#### Validating Metadata-Based Constraint Templates
### Validating Metadata-Based Constraint Templates
`gator verify` may be used with an [`AdmissionReview`](https://pkg.go.dev/k8s.io/kubernetes/pkg/apis/admission#AdmissionReview)
object to test your constraints. This can be helpful to simulate a certain operation (`CREATE`, `UPDATE`, `DELETE`, etc.)
or [`UserInfo`](https://pkg.go.dev/k8s.io/[email protected]/pkg/apis/authentication#UserInfo) metadata.
Recall that the `input.review.user` can be accessed in the Rego code (see [Input Review](howto.md#input-review) for more guidance).
A few examples for how to structure your yaml can be found [here](https://github.com/open-policy-agent/gatekeeper/blob/03e6adb74f1714242cf936fd27eee19a0eda2d52/pkg/gator/fixtures/fixtures.go#L506-L528).
The `AdmissionReview` object can be specified where you would specify the object under test above:
Recall that the `input.review.user` can be accessed in the Rego code (see [Input Review](howto.md#input-review) for more guidance). The `AdmissionReview` object can be specified where you would specify the object under test above:
```yaml
- name: both-disallowed
Expand All @@ -276,6 +274,76 @@ The `AdmissionReview` object can be specified where you would specify the object
- violations: 1
```

Example for testing the `UserInfo` metadata:

AdmissionReview, ConstraintTemplate, Constraint:
```yaml
kind: AdmissionReview
apiVersion: admission.k8s.io/v1beta1
request:
operation: "UPDATE"
userInfo:
username: "system:foo"
object:
kind: Pod
labels:
- app: "bar"
---
kind: ConstraintTemplate
apiVersion: templates.gatekeeper.sh/v1
metadata:
name: validateuserinfo
spec:
crd:
spec:
names:
kind: ValidateUserInfo
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8svalidateuserinfo
violation[{"msg": msg}] {
username := input.review.userInfo.username
not startswith(username, "system:")
msg := sprintf("username is not allowed to perform this operation: %v", [username])
}
---
kind: ValidateUserInfo
apiVersion: constraints.gatekeeper.sh/v1
metadata:
name: always-validate
```
Gator Suite:
```yaml
apiVersion: test.gatekeeper.sh/v1alpha1
kind: Suite
tests:
- name: userinfo
template: template.yaml
constraint: constraint.yaml
cases:
- name: system-user
object: admission-review.yaml
assertions:
- violations: no
```
Note for `DELETE` operation, the `oldObject` should be the object being deleted:

```yaml
kind: AdmissionReview
apiVersion: admission.k8s.io/v1beta1
request:
operation: "DELETE"
userInfo:
username: "system:foo"
oldObject:
kind: Pod
labels:
- app: "bar"
```

Note that [`audit`](audit.md) or `gator test` are different enforcement points and they don't have the `AdmissionReview` request metadata.

Run `gator verify --help` for more information.
Expand Down

0 comments on commit 118cf5f

Please sign in to comment.