Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: refining resource exclusion logic based on built-in or custom ownership #215

Merged
merged 1 commit into from
Aug 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions examples/trivy.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,19 @@ func main() {

fmt.Println("Current namespace:", cluster.GetCurrentNamespace())

trivyk8s := trivyk8s.New(cluster, logger.Sugar())
trivyk8s := trivyk8s.New(cluster, logger.Sugar(), trivyk8s.WithExcludeOwned(true))

fmt.Println("Scanning kind 'pods' with exclude-owned=true")
artifacts, err := trivyk8s.Resources("pod").AllNamespaces().ListArtifacts(ctx)
if err != nil {
log.Fatal(err)
}
printArtifacts(artifacts)

fmt.Println("Scanning cluster")

//trivy k8s #cluster
artifacts, err := trivyk8s.ListArtifacts(ctx)
artifacts, err = trivyk8s.ListArtifacts(ctx)
if err != nil {
log.Fatal(err)
}
Expand Down
18 changes: 15 additions & 3 deletions pkg/trivyk8s/trivyk8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,21 @@ func (c *client) ListArtifacts(ctx context.Context) ([]*artifacts.Artifact, erro
continue
}

// if excluding owned resources is enabled, we check if the resource has an owner
// if it does, then skip it
if c.excludeOwned && len(resource.GetOwnerReferences()) > 0 {
// assume that the owner is a built-in workload by default
ownerIsBuiltIn := true
if len(resource.GetOwnerReferences()) > 0 {
// if the resource has an owner, we check if it is a built-in workload
// this ensures that we don't skip resources that are owned by custom resources
for _, owner := range resource.GetOwnerReferences() {
if !k8s.IsBuiltInWorkload(&owner) {
ownerIsBuiltIn = false
break
}
}
}

// if excludeOwned is enabled and workload is a built-in workload, we skip it
if c.excludeOwned && ownerIsBuiltIn {
continue
}

Expand Down