Skip to content

Commit dd1ff7b

Browse files
committed
fix(email): verify the rollback-safe mailbox configuration
1 parent da2bbbe commit dd1ff7b

2 files changed

Lines changed: 133 additions & 19 deletions

File tree

‎scripts/diagnose-email-startup/main.go‎

Lines changed: 77 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ import (
2020
)
2121

2222
const approvedImage = "ghcr.io/devantler-tech/platform-private-mail-bootstrap@sha256:05ce801246615043ecd613c082f7b79216131f49831462a83e5c2afff237d9c1"
23+
const approvedRoutedImage = "ghcr.io/devantler-tech/platform-private-mail-bootstrap@sha256:c00cd848d47cab10f60301facba02387cf34832f7d560cfaf206a008ed9e0ff9"
24+
const approvedStorageSelectorSHA = "d11ea321157b321f3e5a6c6b96dc7ab4eccb116157edada63cade186df1ffb9e"
2325
const approvedProxyMap = "email-client-proxy-kkm788c4m9"
2426
const approvedProxyConfigSHA = "400a77329e2fcda3fea17c821593ef18f7ad2ca8f1fa32acfbf3b5f36aa6fb4c"
2527
const maxOutput = 16384
@@ -62,26 +64,33 @@ type pod struct {
6264
NodeName string
6365
ShareProcessNamespace bool
6466
Containers []container
67+
InitContainers []container
6568
Volumes []struct {
6669
Name string
6770
ConfigMap *struct{ Name string }
71+
EmptyDir *struct{ Medium, SizeLimit string }
6872
}
6973
}
7074
Status struct {
71-
ContainerStatuses []containerStatus
75+
ContainerStatuses []containerStatus
76+
InitContainerStatuses []containerStatus
7277
}
7378
}
7479
type containerStatus struct {
7580
Name, ContainerID, ImageID string
7681
RestartCount int
7782
Ready bool
78-
State struct{ Running *struct{ StartedAt string } }
83+
State struct {
84+
Running *struct{ StartedAt string }
85+
Terminated *struct{ ExitCode *int }
86+
}
7987
}
8088
type binding struct {
8189
UID, Node, ContainerID, ImageID, StartedAt string
8290
Restarts int
8391
ProxyConfig, ProxyContainerID, ProxyImageID, ProxyStartedAt string
8492
ProxyRestarts int
93+
StorageSelectorID string
8594
}
8695
type configMap struct {
8796
Metadata metadata
@@ -217,28 +226,20 @@ func bindPod(b []byte) (binding, bool, bool, error) {
217226
if c.Name == "client-proxy" && len(p.Spec.Containers) == 2 {
218227
c = p.Spec.Containers[1]
219228
}
220-
if c.Name != "private-mail" || c.Image != approvedImage || !reflect.DeepEqual(c.Command, []string{"/usr/local/bin/stalwart"}) ||
229+
if c.Name != "private-mail" || !reflect.DeepEqual(c.Command, []string{"/usr/local/bin/stalwart"}) ||
221230
!reflect.DeepEqual(c.Args, []string{"--config", "/etc/stalwart/config.json"}) || len(c.Env) != 0 || len(c.EnvFrom) != 0 {
222231
return binding{}, false, false, invalid
223232
}
224-
mounted := false
225-
for _, mount := range c.VolumeMounts {
226-
if mount.MountPath == "/etc/stalwart/config.json" && mount.SubPath == "config.json" && mount.ReadOnly {
227-
for _, volume := range p.Spec.Volumes {
228-
if volume.Name == mount.Name && volume.ConfigMap != nil && volume.ConfigMap.Name == "private-mail-datastore" {
229-
mounted = true
230-
}
231-
}
232-
}
233-
}
234-
if !mounted {
233+
selector, ok := bindDatastoreMount(p, c)
234+
if !ok {
235235
return binding{}, false, false, invalid
236236
}
237237
s, ok := statusFor(p, "private-mail")
238238
if !ok || s.RestartCount < 0 {
239239
return binding{}, false, false, invalid
240240
}
241-
id := binding{UID: p.Metadata.UID, Node: p.Spec.NodeName, ContainerID: s.ContainerID, ImageID: s.ImageID, Restarts: s.RestartCount}
241+
id := binding{UID: p.Metadata.UID, Node: p.Spec.NodeName, ContainerID: s.ContainerID, ImageID: s.ImageID,
242+
Restarts: s.RestartCount, StorageSelectorID: selector}
242243
if s.State.Running == nil {
243244
return id, false, s.Ready, nil
244245
}
@@ -249,13 +250,70 @@ func bindPod(b []byte) (binding, bool, bool, error) {
249250
return binding{}, false, false, invalid
250251
}
251252
id.StartedAt = s.State.Running.StartedAt
252-
proxyRunning, proxyReady, err := bindProxy(p, &id)
253+
proxyRunning, proxyReady, err := bindProxy(p, &id, c.Image)
253254
if err != nil {
254255
return binding{}, false, false, invalid
255256
}
256257
return id, proxyRunning, s.Ready && proxyReady, nil
257258
}
258259

260+
func bindDatastoreMount(p pod, c container) (string, bool) {
261+
for _, mount := range c.VolumeMounts {
262+
if mount.MountPath != "/etc/stalwart/config.json" || mount.SubPath != "config.json" || !mount.ReadOnly {
263+
continue
264+
}
265+
for _, volume := range p.Spec.Volumes {
266+
if volume.Name != mount.Name {
267+
continue
268+
}
269+
switch c.Image {
270+
case approvedImage:
271+
return "", volume.ConfigMap != nil && volume.ConfigMap.Name == "private-mail-datastore"
272+
case approvedRoutedImage:
273+
if volume.Name == "serving-storage" && volume.EmptyDir != nil &&
274+
volume.EmptyDir.Medium == "Memory" && volume.EmptyDir.SizeLimit == "1Mi" {
275+
return bindStorageSelector(p)
276+
}
277+
}
278+
}
279+
}
280+
return "", false
281+
}
282+
283+
func bindStorageSelector(p pod) (string, bool) {
284+
writers := 0
285+
for _, init := range p.Spec.InitContainers {
286+
for _, mount := range init.VolumeMounts {
287+
if mount.Name != "serving-storage" || mount.ReadOnly {
288+
continue
289+
}
290+
if init.Name != "select-mail-store" || init.Image != approvedRoutedImage || mount.MountPath != "/store-selection" ||
291+
mount.SubPath != "" || len(init.Env) != 0 || len(init.EnvFrom) != 0 ||
292+
!reflect.DeepEqual(init.Command, []string{"/usr/bin/sh", "-c"}) || len(init.Args) != 1 ||
293+
hashBytes([]byte(init.Args[0])) != approvedStorageSelectorSHA {
294+
return "", false
295+
}
296+
writers++
297+
}
298+
}
299+
if writers != 1 {
300+
return "", false
301+
}
302+
selector := ""
303+
for _, status := range p.Status.InitContainerStatuses {
304+
if status.Name != "select-mail-store" {
305+
continue
306+
}
307+
state := status.State.Terminated
308+
if selector != "" || status.ContainerID == "" || status.ImageID == "" || state == nil ||
309+
state.ExitCode == nil || *state.ExitCode != 0 {
310+
return "", false
311+
}
312+
selector = status.ContainerID
313+
}
314+
return selector, selector != ""
315+
}
316+
259317
// statusFor refuses duplicate identities, independent of Kubernetes list ordering.
260318
func statusFor(p pod, name string) (containerStatus, bool) {
261319
var result containerStatus
@@ -272,7 +330,7 @@ func statusFor(p pod, name string) (containerStatus, bool) {
272330
}
273331

274332
// bindProxy admits only the declared adapter, with no environment or credential mounts.
275-
func bindProxy(p pod, id *binding) (bool, bool, error) {
333+
func bindProxy(p pod, id *binding, image string) (bool, bool, error) {
276334
if len(p.Spec.Containers) == 1 {
277335
return true, true, nil
278336
}
@@ -281,7 +339,7 @@ func bindProxy(p pod, id *binding) (bool, bool, error) {
281339
if p.Spec.Containers[0].Name == "client-proxy" {
282340
c = p.Spec.Containers[0]
283341
}
284-
if c.Name != "client-proxy" || c.Image != approvedImage ||
342+
if c.Name != "client-proxy" || c.Image != image ||
285343
!reflect.DeepEqual(c.Command, []string{"/usr/local/bin/caddy"}) ||
286344
!reflect.DeepEqual(c.Args, []string{"run", "--config", "/etc/email-client-proxy/Caddyfile", "--adapter", "caddyfile"}) ||
287345
len(c.Env) != 0 || len(c.EnvFrom) != 0 || len(c.VolumeMounts) != 1 {
@@ -371,7 +429,7 @@ func collect(ctx context.Context, run executor, pause func(context.Context) erro
371429
return unknown()
372430
}
373431
id, running, _, e := bindPod(raw)
374-
if e != nil {
432+
if e != nil || id.StorageSelectorID != "" {
375433
return unknown()
376434
}
377435
if running {

‎scripts/diagnose-email-startup/main_test.go‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,66 @@ import (
66
"encoding/json"
77
"errors"
88
"io"
9+
"os"
910
"strings"
1011
"testing"
12+
13+
"sigs.k8s.io/yaml"
1114
)
1215

16+
func TestBindPodRecognizesOnlyReviewedFencedStorageProducer(t *testing.T) {
17+
const routedImage = "ghcr.io/devantler-tech/platform-private-mail-bootstrap@sha256:c00cd848d47cab10f60301facba02387cf34832f7d560cfaf206a008ed9e0ff9"
18+
raw, err := os.ReadFile("../../k8s/providers/hetzner/apps/private-mail/patches/select-mail-store.yaml")
19+
if err != nil {
20+
t.Fatal(err)
21+
}
22+
var patch []struct{ Value map[string]any }
23+
if err := yaml.Unmarshal(raw, &patch); err != nil || len(patch) != 1 {
24+
t.Fatal("invalid reviewed route selector")
25+
}
26+
routed := changePod(t, fixturePod(t), func(p map[string]any) {
27+
spec := p["spec"].(map[string]any)
28+
main := spec["containers"].([]any)[0].(map[string]any)
29+
main["image"] = routedImage
30+
main["volumeMounts"].([]any)[0].(map[string]any)["name"] = "serving-storage"
31+
spec["volumes"] = append(spec["volumes"].([]any), map[string]any{
32+
"name": "serving-storage", "emptyDir": map[string]any{"medium": "Memory", "sizeLimit": "1Mi"},
33+
})
34+
patch[0].Value["image"] = routedImage
35+
spec["initContainers"] = []any{patch[0].Value}
36+
p["status"].(map[string]any)["initContainerStatuses"] = []any{map[string]any{
37+
"name": "select-mail-store", "imageID": "sha256:selector", "containerID": "containerd://selector",
38+
"state": map[string]any{"terminated": map[string]any{"exitCode": 0}},
39+
}}
40+
})
41+
if _, running, ready, err := bindPod(routed); err != nil || !running || !ready {
42+
t.Fatalf("reviewed fenced route refused: running=%t ready=%t err=%v", running, ready, err)
43+
}
44+
for _, tc := range []struct {
45+
name string
46+
change func(map[string]any)
47+
}{
48+
{"changed selector", func(p map[string]any) {
49+
p["spec"].(map[string]any)["initContainers"].([]any)[0].(map[string]any)["args"] = []string{"unexpected"}
50+
}},
51+
{"unfinished selector", func(p map[string]any) {
52+
delete(p["status"].(map[string]any), "initContainerStatuses")
53+
}},
54+
{"other initializer can write the route", func(p map[string]any) {
55+
spec := p["spec"].(map[string]any)
56+
spec["initContainers"] = append(spec["initContainers"].([]any), map[string]any{
57+
"name": "other", "volumeMounts": []any{map[string]any{"name": "serving-storage", "mountPath": "/other"}},
58+
})
59+
}},
60+
} {
61+
t.Run(tc.name, func(t *testing.T) {
62+
if _, _, _, err := bindPod(changePod(t, routed, tc.change)); err == nil {
63+
t.Fatal("unqualified route producer was accepted")
64+
}
65+
})
66+
}
67+
}
68+
1369
// goodMeasurement supplies one complete synthetic healthy observation.
1470
func goodMeasurement() measurement {
1571
return measurement{PID1Stalwart: true, UID2000: true, ConfigSHA256: strings.Repeat("a", 64),

0 commit comments

Comments
 (0)