oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "context"
5 "encoding/base64"
6 "io"
7 "log/slog"
8 "net"
9 "net/http"
10 "os"
11 "path/filepath"
12 "strings"
13 "testing"
14
15 "amadan.net/rastrillo/rastrillo/mail"
16)
17
18// b64 is a valid, correctly-sized value for whichever secret needs one.
19func b64(n int) string {
20 b := make([]byte, n)
21 for i := range b {
22 b[i] = byte(i)
23 }
24 return base64.StdEncoding.EncodeToString(b)
25}
26
27func quietLogger() *slog.Logger {
28 return slog.New(slog.NewTextHandler(io.Discard, nil))
29}
30
31// setSecretEnv clears every variable LoadSecrets reads, then applies the
32// overrides. Clearing first matters: t.Setenv restores on cleanup but does
33// not isolate a variable the developer happens to have exported, and a
34// test that passes only on a machine with CARLOS_SMTP_HOST set is worse
35// than no test.
36func setSecretEnv(t *testing.T, overrides map[string]string) {
37 t.Helper()
38 complete := map[string]string{
39 "HOME_DEK": b64(32),
40 "HOME_PEPPER": b64(32),
41 "HOME_SIGNIN_KEY": b64(32),
42 "CARLOS_SMTP_HOST": "smtp.example.invalid",
43 "CARLOS_SMTP_FROM": "home@example.invalid",
44 "CARLOS_SMTP_PASS": "hunter2",
45 // CARLOS mail submission's variables, cleared by default so a
46 // case is on SMTP unless it says otherwise.
47 "CARLOS_MAIL": "",
48 "CARLOS_CONTROL_SOCKET": "",
49 "CARLOS_ADMIN_TOKEN": "",
50 "CARLOS_MAIL_FROM": "",
51 }
52 for k, v := range complete {
53 if o, ok := overrides[k]; ok {
54 v = o
55 }
56 t.Setenv(k, v)
57 }
58}
59
60func TestLoadSealerRefusals(t *testing.T) {
61 cases := map[string]string{
62 "unset": "",
63 "not base64": "not-base64!!",
64 "31 bytes": b64(31),
65 "33 bytes": b64(33),
66 }
67 for name, val := range cases {
68 t.Run(name, func(t *testing.T) {
69 t.Setenv("HOME_DEK", val)
70 if _, err := LoadSealer(); err == nil {
71 t.Fatalf("LoadSealer accepted HOME_DEK=%q", val)
72 }
73 })
74 }
75}
76
77func TestLoadSealerAcceptsA32ByteKey(t *testing.T) {
78 t.Setenv("HOME_DEK", b64(32))
79 s, err := LoadSealer()
80 if err != nil {
81 t.Fatalf("LoadSealer: %v", err)
82 }
83 if s == nil {
84 t.Fatal("LoadSealer returned a nil Sealer and no error")
85 }
86}
87
88func TestLoadSecretsAcceptsCompleteConfig(t *testing.T) {
89 setSecretEnv(t, nil)
90 got, err := LoadSecrets("/tmp/home.db", quietLogger())
91 if err != nil {
92 t.Fatalf("LoadSecrets: %v", err)
93 }
94 if got.Sealer == nil {
95 t.Error("no Sealer")
96 }
97 if len(got.Pepper) != 32 {
98 t.Errorf("Pepper is %d bytes, want 32", len(got.Pepper))
99 }
100 if got.SigninKey == ([32]byte{}) {
101 t.Error("SigninKey is the zero value, which signin.Flow refuses")
102 }
103 if got.Mailer == nil {
104 t.Error("no Mailer")
105 }
106}
107
108// Each secret missing is its own refusal, and the message must name the
109// variable an operator has to set — an error that says "not configured"
110// without saying which one costs a support round-trip.
111func TestLoadSecretsRefusesEachMissingSecret(t *testing.T) {
112 for _, name := range []string{"HOME_DEK", "HOME_PEPPER", "HOME_SIGNIN_KEY", "CARLOS_SMTP_PASS"} {
113 t.Run(name, func(t *testing.T) {
114 setSecretEnv(t, map[string]string{name: ""})
115 _, err := LoadSecrets("/tmp/home.db", quietLogger())
116 if err == nil {
117 t.Fatalf("LoadSecrets accepted a missing %s", name)
118 }
119 if !strings.Contains(err.Error(), name) {
120 t.Errorf("error %q does not name %s", err, name)
121 }
122 })
123 }
124}
125
126func TestLoadSecretsRefusesMalformedSecrets(t *testing.T) {
127 for _, name := range []string{"HOME_DEK", "HOME_PEPPER", "HOME_SIGNIN_KEY"} {
128 for _, bad := range []string{"not-base64!!", b64(31)} {
129 t.Run(name+"/"+bad, func(t *testing.T) {
130 setSecretEnv(t, map[string]string{name: bad})
131 if _, err := LoadSecrets("/tmp/home.db", quietLogger()); err == nil {
132 t.Fatalf("LoadSecrets accepted %s=%q", name, bad)
133 }
134 })
135 }
136 }
137}
138
139// mail.FromEnv falls back to a logging sender when HOST or FROM is
140// absent, and mail.Logged's Send logs "to", to — an address into
141// platform-held logs on every sign-in. A warning is not enough: the log
142// is storage we cannot grep or redact.
143func TestLoadSecretsRefusesWithoutSMTPHostOrFrom(t *testing.T) {
144 for _, name := range []string{"CARLOS_SMTP_HOST", "CARLOS_SMTP_FROM"} {
145 t.Run(name, func(t *testing.T) {
146 setSecretEnv(t, map[string]string{name: ""})
147 _, err := LoadSecrets("/tmp/home.db", quietLogger())
148 if err == nil {
149 t.Fatalf("LoadSecrets accepted a missing %s, so links would be logged", name)
150 }
151 if !strings.Contains(err.Error(), name) {
152 t.Errorf("error %q does not name %s", err, name)
153 }
154 })
155 }
156}
157
158// SQLite treats an empty filename as a private temporary database: the
159// app comes up, works, and loses every person on restart. On the
160// platform the path is never empty — cmd/home sets a relative default
161// that Resolve joins to $STATE_DIRECTORY — so this guards a caller that
162// builds its own Options, not the deployed boot path.
163func TestLoadSecretsRefusesEmptyDBPath(t *testing.T) {
164 setSecretEnv(t, nil)
165 if _, err := LoadSecrets("", quietLogger()); err == nil {
166 t.Fatal("LoadSecrets accepted an empty database path")
167 }
168}
169
170// An all-zero key is well-formed: right length, valid base64, and every
171// other check passes it. It is also the canonical placeholder, and
172// signin.Flow refuses a zero Key per request rather than at
173// construction — so without this the app boots, answers /healthz, and
174// breaks sign-in for keymail addresses while leaving the magic link
175// working, since Flow reads Key only on the keymail path. A silently
176// half-broken sign-in is if anything worse than a wholly broken one.
177func TestLoadSecretsRefusesAllZeroKeys(t *testing.T) {
178 zero := base64.StdEncoding.EncodeToString(make([]byte, 32))
179 for _, name := range []string{"HOME_DEK", "HOME_PEPPER", "HOME_SIGNIN_KEY"} {
180 t.Run(name, func(t *testing.T) {
181 setSecretEnv(t, map[string]string{name: zero})
182 _, err := LoadSecrets("/tmp/home.db", quietLogger())
183 if err == nil {
184 t.Fatalf("LoadSecrets accepted 32 zero bytes for %s", name)
185 }
186 if !strings.Contains(err.Error(), name) {
187 t.Errorf("error %q does not name %s", err, name)
188 }
189 })
190 }
191}
192
193// New guards every construction path that is not the boot path — which
194// is every test, and every caller written from here on.
195func TestNewRefusesIncompleteWiring(t *testing.T) {
196 full, _ := testSecrets(t)
197 d := newTestApp(t).db
198
199 noPepper := full
200 noPepper.Pepper = nil
201 noKey := full
202 noKey.SigninKey = [32]byte{}
203 noSealer := full
204 noSealer.Sealer = nil
205 noMailer := full
206 noMailer.Mailer = nil
207
208 for name, s := range map[string]Secrets{
209 "zero value": {},
210 "no Sealer": noSealer,
211 "no pepper": noPepper,
212 "no sign key": noKey,
213 "no mailer": noMailer,
214 } {
215 t.Run(name, func(t *testing.T) {
216 if _, err := New(s, d, quietLogger()); err == nil {
217 t.Fatal("New accepted it")
218 }
219 })
220 }
221
222 if _, err := New(full, nil, quietLogger()); err == nil {
223 t.Fatal("New accepted a nil database")
224 }
225 if _, err := New(full, d, quietLogger()); err != nil {
226 t.Fatalf("New refused complete wiring: %v", err)
227 }
228}
229
230// CARLOS platform mail submission (carlos plan Task 9). Once Home is
231// switched, the agent sets CARLOS_MAIL=submit beside its control
232// socket and admin token, the platform delivers CARLOS_MAIL_FROM, and
233// the five CARLOS_SMTP_* leave the bundle: no HOST, no FROM, no PASS.
234
235// smtpGone is a switched instance's bundle: none of the SMTP five.
236var smtpGone = map[string]string{"CARLOS_SMTP_HOST": "",
237 "CARLOS_SMTP_FROM": "", "CARLOS_SMTP_PASS": ""}
238
239// switched is smtpGone plus the overrides.
240func switched(overrides map[string]string) map[string]string {
241 out := map[string]string{}
242 for k, v := range smtpGone {
243 out[k] = v
244 }
245 for k, v := range overrides {
246 out[k] = v
247 }
248 return out
249}
250
251// mailVerb stands in for the agent's control socket, answering POST
252// /v1/mail and reporting each request's method and path.
253func mailVerb(t *testing.T) (string, chan string) {
254 t.Helper()
255 // A short directory: a unix socket path has a 104-byte limit.
256 dir, err := os.MkdirTemp("/tmp", "home-mail")
257 if err != nil {
258 t.Fatal(err)
259 }
260 t.Cleanup(func() { os.RemoveAll(dir) })
261 socket := filepath.Join(dir, "control.sock")
262 listener, err := net.Listen("unix", socket)
263 if err != nil {
264 t.Fatal(err)
265 }
266 paths := make(chan string, 1)
267 server := &http.Server{Handler: http.HandlerFunc(
268 func(w http.ResponseWriter, r *http.Request) {
269 paths <- r.Method + " " + r.URL.Path
270 w.Write([]byte(`{"message_id":"m-1"}`))
271 })}
272 go server.Serve(listener)
273 t.Cleanup(func() { server.Close() })
274 return socket, paths
275}
276
277// A switched Home boots with no SMTP variable at all, CARLOS_SMTP_PASS
278// included, and its sign-in goes to the agent's mail verb.
279func TestLoadSecretsBootsOnMailSubmission(t *testing.T) {
280 socket, paths := mailVerb(t)
281 setSecretEnv(t, switched(map[string]string{
282 "CARLOS_MAIL": "submit", "CARLOS_CONTROL_SOCKET": socket,
283 "CARLOS_ADMIN_TOKEN": "token",
284 "CARLOS_MAIL_FROM": "noreply@oficina.works"}))
285 got, err := LoadSecrets("/tmp/home.db", quietLogger())
286 if err != nil {
287 t.Fatalf("a switched Home refused to boot: %v", err)
288 }
289 if err := got.Mailer.Send(context.Background(), "ana@example.com",
290 "Sign in", "link"); err != nil {
291 t.Fatal(err)
292 }
293 if path := <-paths; path != "POST /v1/mail" {
294 t.Fatalf("the sign-in went to %s, not the mail verb", path)
295 }
296}
297
298// SMTP alone is what Home has always booted on, unchanged.
299func TestLoadSecretsBootsOnSMTPAlone(t *testing.T) {
300 setSecretEnv(t, nil)
301 got, err := LoadSecrets("/tmp/home.db", quietLogger())
302 if err != nil {
303 t.Fatal(err)
304 }
305 if !mail.IsConfigured(got.Mailer) {
306 t.Fatal("SMTP is configured but the sender only logs")
307 }
308}
309
310// With neither channel Home refuses, naming both ways out.
311func TestLoadSecretsRefusesWithNeitherChannel(t *testing.T) {
312 setSecretEnv(t, smtpGone)
313 _, err := LoadSecrets("/tmp/home.db", quietLogger())
314 if err == nil {
315 t.Fatal("booted with no mail channel, so links would be logged")
316 }
317 for _, want := range []string{"CARLOS_MAIL", "CARLOS_SMTP_HOST"} {
318 if !strings.Contains(err.Error(), want) {
319 t.Errorf("refusal %q does not name %s", err, want)
320 }
321 }
322}
323
324// A submission missing any part the agent delivers is a boot refusal,
325// never SMTP or logged mail in its place: not even with the SMTP five
326// still in the bundle.
327func TestLoadSecretsRefusesHalfASubmission(t *testing.T) {
328 socket, _ := mailVerb(t)
329 whole := map[string]string{"CARLOS_MAIL": "submit",
330 "CARLOS_CONTROL_SOCKET": socket, "CARLOS_ADMIN_TOKEN": "token",
331 "CARLOS_MAIL_FROM": "noreply@oficina.works"}
332 for _, missing := range []string{"CARLOS_CONTROL_SOCKET",
333 "CARLOS_ADMIN_TOKEN", "CARLOS_MAIL_FROM"} {
334 t.Run(missing, func(t *testing.T) {
335 env := map[string]string{}
336 for k, v := range whole {
337 env[k] = v
338 }
339 env[missing] = ""
340 setSecretEnv(t, env)
341 _, err := LoadSecrets("/tmp/home.db", quietLogger())
342 if err == nil {
343 t.Fatalf("booted on submission with no %s", missing)
344 }
345 if !strings.Contains(err.Error(), missing) {
346 t.Errorf("refusal %q does not name %s", err, missing)
347 }
348 })
349 }
350}
351