Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
Signed-off-by: Maksim Paskal <paskal.maksim@gmail.com>
  • Loading branch information
maksim-paskal committed Dec 12, 2023
1 parent 91cc2a1 commit 60bde8c
Show file tree
Hide file tree
Showing 53 changed files with 2,225 additions and 732 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@
coverage.out
/deploy-*
/config.yaml
/.cr-*
/.cr-*
/patch.json
3 changes: 2 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ linters:
- exhaustruct
- varnamelen
- musttag
- depguard
- depguard
- maligned
7 changes: 6 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ image=paskalmaksim/pod-admission-controller:$(tag)
config=config.yaml
testnamespace=test-pod-admission-controller

namespace=
pod=

test:
./scripts/validate-license.sh
go mod tidy
Expand Down Expand Up @@ -38,7 +41,9 @@ run:
-cert=./certs/server.crt \
-key=./certs/server.key \
-listen=127.0.0.1:8443 \
-metrics.listen=127.0.0.1:31080
-metrics.listen=127.0.0.1:31080 \
-test.pod=$(pod) \
-test.namespace=$(namespace)

sslInit:
rm -rf ./certs
Expand Down
2 changes: 1 addition & 1 deletion charts/pod-admission-controller/Chart.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
apiVersion: v2
icon: https://helm.sh/img/helm.svg
name: pod-admission-controller
version: 0.0.4
version: 0.0.5
description: pod mutating admission controller
maintainers:
- name: maksim-paskal # Maksim Paskal
Expand Down
10 changes: 6 additions & 4 deletions charts/pod-admission-controller/templates/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,10 @@ spec:
{{ toYaml .Values.args | indent 8 }}
{{ end }}
ports:
- containerPort: 8443
- containerPort: 31080
- name: https
containerPort: 8443
- name: metrics
containerPort: 31080
volumeMounts:
- name: config
mountPath: /config
Expand All @@ -74,13 +76,13 @@ spec:
httpGet:
scheme: HTTPS
path: /ready
port: 8443
port: https
initialDelaySeconds: 3
periodSeconds: 5
livenessProbe:
httpGet:
scheme: HTTPS
path: /healthz
port: 8443
port: https
initialDelaySeconds: 10
periodSeconds: 10
3 changes: 3 additions & 0 deletions charts/pod-admission-controller/templates/rbac.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ rules:
- apiGroups: [""]
resources: ["namespaces"]
verbs: ["get"]
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get","delete","create"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
Expand Down
6 changes: 5 additions & 1 deletion charts/pod-admission-controller/templates/webhook.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ metadata:
app: pod-admission-controller
webhooks:
- name: pod-admission-controller.pod-admission-controller.svc.cluster.local
failurePolicy: Ignore
failurePolicy: {{ .Values.webhook.failurePolicy }}
clientConfig:
caBundle: {{ tpl .Values.webhook.caBundle . | quote }}
service:
Expand All @@ -18,6 +18,10 @@ webhooks:
apiGroups: [""]
apiVersions: ["v1"]
resources: ["pods"]
- operations: ["UPDATE"]
apiGroups: [""]
apiVersions: ["v1"]
resources: ["namespaces"]
admissionReviewVersions: ["v1"]
sideEffects: None
timeoutSeconds: 5
Expand Down
2 changes: 2 additions & 0 deletions charts/pod-admission-controller/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ certificates:
webhook:
caBundle: "{{ b64enc .Values.certificates.caCert }}"
# Fail/Ignore
failurePolicy: Ignore
namespaceSelector:
- key: environment
operator: In
Expand Down
2 changes: 1 addition & 1 deletion e2e/requirements/Pods/1/InitContainers/0/Env.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion e2e/requirements/Pods/1/InitContainers/0/Resources.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion e2e/requirements/Pods/1/InitContainers/1/Env.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion e2e/requirements/Pods/1/InitContainers/1/Resources.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion e2e/requirements/Pods/1/containers/0/Env.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion e2e/requirements/Pods/1/containers/1/Env.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion e2e/requirements/Pods/1/containers/2/Env.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion e2e/requirements/Pods/1/containers/3/Env.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 16 additions & 1 deletion e2e/testdata/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,19 @@ rules:
- name: TEST_PORT
value: "6831"
- name: SERVICE_NAME
value: "{{ .Image.Slug }}"
value: "{{ .Image.Slug }}"

- name: "rule-replaceContainerImageHost-1"
replaceContainerImageHost:
enabled: true
to: docker.io
conditions:
- key: .Image.Domain
operator: regexp
value: ^(test-fake.test.com)$

- name: "rule-replaceContainerImageHost-2"
replaceContainerImageHost:
enabled: true
from: test.test.com
to: docker.io
14 changes: 7 additions & 7 deletions e2e/testdata/pods/test-pod-1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ spec:
initContainers:
# init containers must be unchanged
- name: test-init-0
image: alpine:latest
image: test.test.com/alpine:latest
securityContext:
runAsUser: 1002
command:
- echo
- ok
- name: test-init-1
image: alpine:latest
image: test-fake.test.com/alpine:latest
env:
- name: TEST
value: ok
Expand All @@ -39,7 +39,7 @@ spec:
# 2. new memory limit
# 3. securitycontext
- name: test-0
image: alpine:latest
image: test.test.com/alpine:latest
command:
- sleep
- 1d
Expand All @@ -56,7 +56,7 @@ spec:
# 2. do not change memory limit (pod-admission-controller/ignoreAddDefaultResources)
# 3. securitycontext
- name: test-1
image: alpine:latest
image: test.test.com/alpine:latest
command:
- sleep
- 1d
Expand All @@ -72,7 +72,7 @@ spec:
# 2. new resources
# 3. securitycontext without change (pod-admission-controller/ignoreRunAsNonRoot)
- name: test-2
image: alpine:latest
image: test.test.com/alpine:latest
command:
- sleep
- 1d
Expand All @@ -82,7 +82,7 @@ spec:
# 2. do not change memory limit (pod-admission-controller/ignoreAddDefaultResources)
# 3. securitycontext without change (pod-admission-controller/ignoreRunAsNonRoot)
- name: test-3
image: alpine:latest
image: test.test.com/alpine:latest
command:
- sleep
- 1d
Expand All @@ -92,7 +92,7 @@ spec:
# 2. new resources
# 3. securitycontext, replace runAsUser=0 to runAsUser=82
- name: test-4
image: alpine:latest
image: test.test.com/alpine:latest
command:
- sleep
- 1d
Expand Down
60 changes: 39 additions & 21 deletions internal/internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,17 @@ package internal
import (
"context"
"crypto/tls"
"crypto/x509"
"flag"
"net/http"
"os"
"time"

logrushooksentry "github.com/maksim-paskal/logrus-hook-sentry"
"github.com/maksim-paskal/pod-admission-controller/pkg/api"
"github.com/maksim-paskal/pod-admission-controller/pkg/config"
"github.com/maksim-paskal/pod-admission-controller/pkg/metrics"
"github.com/maksim-paskal/pod-admission-controller/pkg/sentry"
"github.com/maksim-paskal/pod-admission-controller/pkg/types"
"github.com/maksim-paskal/pod-admission-controller/pkg/utils"
"github.com/maksim-paskal/pod-admission-controller/pkg/web"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
Expand All @@ -33,6 +34,11 @@ import (
// webhook spec timeoutSeconds.
const serverTimeout = 5 * time.Second

var (
testPod = flag.String("test.pod", "", "test pod")
testNamespace = flag.String("test.namespace", "", "test namespace")
)

func Start(ctx context.Context) error {
hook, err := logrushooksentry.NewHook(ctx, logrushooksentry.Options{
SentryDSN: *config.Get().SentryDSN,
Expand All @@ -46,19 +52,36 @@ func Start(ctx context.Context) error {

log.Infof("Starting %s...", config.GetVersion())

if err := CheckConfigRules(); err != nil {
return errors.Wrap(err, "error in config rules")
}

if err := sentry.CreateCache(ctx); err != nil {
return errors.Wrap(err, "failed to create sentry cache")
}

if len(*testPod)+len(*testNamespace) > 0 {
patchBytes, err := api.TestPOD(ctx, *testNamespace, *testPod)
if err != nil {
log.WithError(err).Error()
}

log.Info("Creating patch.json...")

if err := os.WriteFile("patch.json", patchBytes, 0o600); err != nil { //nolint:gomnd
log.WithError(err).Error()
}

os.Exit(0)

return nil
}

sCert, err := tls.LoadX509KeyPair(*config.Get().CertFile, *config.Get().KeyFile)
if err != nil {
return errors.Wrap(err, "can not load certificates")
}

if err := printCertInfo(sCert); err != nil {
return errors.Wrap(err, "can not print certificate info")
}

go startServerTLS(ctx, sCert)
go startMetricsServer(ctx)

Expand Down Expand Up @@ -89,7 +112,7 @@ func startServerTLS(ctx context.Context, sCert tls.Certificate) {

log.Infof("Listening on address %s", server.Addr)

if err := server.ListenAndServeTLS("", ""); err != nil {
if err := server.ListenAndServeTLS("", ""); err != nil && ctx.Err() == nil {
log.WithError(err).Fatal()
}
}
Expand Down Expand Up @@ -118,27 +141,22 @@ func startMetricsServer(ctx context.Context) {

log.Infof("Listening metrics on address %s", server.Addr)

if err := server.ListenAndServe(); err != nil {
if err := server.ListenAndServe(); err != nil && ctx.Err() == nil {
log.WithError(err).Fatal()
}
}

// check config for templating errors.
func CheckConfigRules() error {
for _, containerConfig := range config.Get().Rules {
containerInfo := types.ContainerInfo{
Image: &types.ContainerImage{},
}

_, err := utils.CheckConditions(containerInfo, containerConfig.Conditions)
func printCertInfo(sCert tls.Certificate) error {
for _, cert := range sCert.Certificate {
x509Cert, err := x509.ParseCertificate(cert)
if err != nil {
return errors.Wrap(err, "error in conditions")
return errors.Wrap(err, "can not parse certificate")
}

_, err = api.FormatEnv(containerInfo, containerConfig.Env)
if err != nil {
return errors.Wrap(err, "error in env")
}
log.Infof("Certificate valid for %s till %s",
x509Cert.Subject.CommonName,
x509Cert.NotAfter.String(),
)
}

return nil
Expand Down
Loading

0 comments on commit 60bde8c

Please sign in to comment.