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 "crypto/subtle"
5 "encoding/base64"
6 "errors"
7 "fmt"
8 "log/slog"
9 "os"
10 "strings"
11
12 "amadan.net/rastrillo/rastrillo/mail"
13
14 "amadan.net/oficina/home/internal/home/seal"
15)
16
17// Secrets is everything the home needs from platform config, already
18// validated. Building it is the only place these variable names appear.
19//
20// Every field here is a refusal rather than a default. The failure they
21// guard against is the same one each time: an app that boots, answers
22// /healthz perfectly well, and is broken or leaking in a way nobody
23// notices until it matters. A generated DEK makes every previously
24// sealed value unreadable; a generated pepper orphans every person row,
25// because the blind index is the only way back from an address to a
26// person. Neither is recoverable, and both look like data loss long
27// after the boot that caused them.
28type Secrets struct {
29 // Sealer seals addresses, team display names and queue payloads at
30 // rest. From HOME_DEK.
31 Sealer *seal.Sealer
32
33 // Pepper keys the blind index — HMAC(pepper, lowercased address).
34 // From HOME_PEPPER.
35 Pepper []byte
36
37 // SigninKey seals signin.Flow's pending blob. It must come from
38 // config and never from an instance data key: sign-in runs before
39 // any session exists. From HOME_SIGNIN_KEY.
40 //
41 // signin.Flow.Key is a [32]byte and Flow refuses a zero one with
42 // ErrNoKey, so the size is the package's requirement, not ours.
43 SigninKey [32]byte
44
45 // Mailer delivers magic links.
46 Mailer mail.Sender
47}
48
49// LoadSealer reads HOME_DEK and returns the process Sealer.
50//
51// It refuses to boot rather than generating a key. A generated key would
52// let the app start with every previously sealed link unreadable, which
53// looks like data loss and is discovered late.
54func LoadSealer() (*seal.Sealer, error) {
55 dek, err := key32("HOME_DEK")
56 if err != nil {
57 return nil, err
58 }
59 return seal.New(dek[:])
60}
61
62// key32 reads a base64 environment variable that must decode to exactly
63// 32 bytes, naming the variable in every error.
64//
65// Exactly, not "at least": a short value is the interesting case, and
66// accepting one would let a truncated secret — a copy-paste that lost
67// its trailing characters — key real ciphertext with silently less
68// entropy than intended.
69func key32(name string) ([32]byte, error) {
70 var out [32]byte
71 raw := strings.TrimSpace(os.Getenv(name))
72 if raw == "" {
73 return out, fmt.Errorf("%s is not set", name)
74 }
75 b, err := base64.StdEncoding.DecodeString(raw)
76 if err != nil {
77 return out, fmt.Errorf("%s is not valid base64: %w", name, err)
78 }
79 if len(b) != 32 {
80 return out, fmt.Errorf("%s decodes to %d bytes, want exactly 32", name, len(b))
81 }
82 // An all-zero key is the canonical placeholder — the value a
83 // generated config, a truncated copy-paste or a `head -c 32
84 // /dev/zero` produces — and it is well-formed, so every other check
85 // here passes it.
86 //
87 // The consequence, stated accurately: signin.Flow reads Key only on
88 // the keymail path (beginKeymail and CompleteKeymail), so a zero
89 // HOME_SIGNIN_KEY breaks sign-in for addresses at a keymail domain
90 // and leaves the magic link working. Not "every sign-in", which an
91 // earlier version of this comment claimed. A silently half-broken
92 // sign-in is if anything a worse failure than a wholly broken one,
93 // and this loader is the only place the refusal can happen at boot.
94 if subtle.ConstantTimeCompare(b, make([]byte, 32)) == 1 {
95 return out, fmt.Errorf("%s is 32 zero bytes, which is a placeholder rather than a key", name)
96 }
97 copy(out[:], b)
98 return out, nil
99}
100
101// LoadSecrets reads the three secrets and the mail channel whose
102// absence is silent, and refuses to boot on any of them.
103//
104// HOME_DEK seals link state, team names and queue payloads
105// HOME_PEPPER the blind index
106// HOME_SIGNIN_KEY seals signin.Flow's Keymail pending blob
107// mail CARLOS mail submission (CARLOS_MAIL=submit), or
108// CARLOS_SMTP_HOST, _FROM and _PASS (loadMailer)
109//
110// dbPath is passed in rather than read from the environment because
111// rastrillo.Resolve owns it, and it is checked here so that every boot
112// refusal lives in one function an operator can read.
113//
114// On the platform it is never empty: cmd/home sets Options.DBPath to a
115// relative "home.db", which Resolve joins to $STATE_DIRECTORY, and a
116// -db flag overrides it only if one is passed. This check therefore
117// guards a caller that constructs its own Options without one — a test,
118// a future command — rather than the deployed boot path.
119func LoadSecrets(dbPath string, logger *slog.Logger) (Secrets, error) {
120 if logger == nil {
121 logger = slog.Default()
122 }
123
124 // SQLite treats an empty filename as a private temporary database:
125 // the app comes up, works, and loses every person on restart. There
126 // is no warning for this anywhere below us, which is why it is
127 // checked here.
128 if strings.TrimSpace(dbPath) == "" {
129 return Secrets{}, errors.New("no database path: set Options.DBPath or pass -db, or SQLite opens a private temporary database and every person is lost on restart")
130 }
131
132 var s Secrets
133 var err error
134
135 // Through LoadSealer rather than beside it, so HOME_DEK is read in
136 // one place. Two readers of the same variable is how one of them
137 // ends up with a check the other does not have.
138 s.Sealer, err = LoadSealer()
139 if err != nil {
140 return Secrets{}, err
141 }
142
143 pepper, err := key32("HOME_PEPPER")
144 if err != nil {
145 return Secrets{}, err
146 }
147 s.Pepper = pepper[:]
148
149 s.SigninKey, err = key32("HOME_SIGNIN_KEY")
150 if err != nil {
151 return Secrets{}, err
152 }
153
154 s.Mailer, err = loadMailer(logger)
155 if err != nil {
156 return Secrets{}, err
157 }
158
159 return s, nil
160}
161
162// loadMailer builds the magic-link sender through rastrillo's
163// mail.FromCarlos, from one of two channels, and refuses to boot with
164// neither.
165//
166// CARLOS mail submission: the agent sets CARLOS_MAIL=submit beside its
167// control socket and admin token, and the platform delivers the From as
168// CARLOS_MAIL_FROM (the stem of Home's declared CARLOS_SMTP prefix).
169// The instance then holds no mail credential at all, which is why
170// CARLOS_SMTP_PASS is not asked for on this channel. FromCarlos refuses
171// a submission missing its socket, token or From, so a half-switched
172// instance stops here rather than at its first sign-in.
173//
174// SMTP: exactly the checks this function has always made, in the same
175// order with the same reasons.
176//
177// mail.FromEnv falls back to mail.Logged with a warning when HOST or
178// FROM is absent, and Logged's Send logs "to", to — an address into
179// platform-held logs on every single sign-in. A warning is not enough:
180// that log is storage we cannot grep or redact, so this is the one
181// fallback we refuse instead of accept. FromCarlos has no such
182// fallback, and it is only reached once the refusals below have passed.
183//
184// CARLOS_SMTP_PASS is a different failure and is refused for a
185// different reason, so the message below distinguishes them. It leaks
186// nothing: with HOST and FROM set, the SMTP sender is built whether or
187// not PASS is present. What a missing PASS costs is delivery — every
188// link fails at send time on an app that otherwise looks healthy. (It
189// is inert without CARLOS_SMTP_USER, which `carlos email enable`
190// delivers alongside it; refusing on PASS is a bet that the platform
191// sets both or neither.)
192//
193// Deliberately no loopback relaxation. Sheets' LoadAuthEnv allows one
194// for local development, keyed on its instance origin being an http
195// loopback host. The home has no origin variable at this step, so the
196// equivalent carve-out would have to invent one, and a carve-out that
197// turns off the leak guard is not a thing to invent in passing. Local
198// development without SMTP is deferred until there is somewhere to put
199// it.
200//
201// Called only from LoadSecrets, so only where Home serves: a CARLOS
202// seed or `cmd` one-shot has no control socket and the agent strips
203// CARLOS_MAIL from it, and Home's own one-shots (team-keygen,
204// operator-v1) return before LoadRuntime.
205func loadMailer(logger *slog.Logger) (mail.Sender, error) {
206 if os.Getenv("CARLOS_MAIL") == "submit" {
207 return mail.FromCarlos("CARLOS", logger)
208 }
209 var leaking, undeliverable []string
210 for _, name := range []string{"CARLOS_SMTP_HOST", "CARLOS_SMTP_FROM"} {
211 if strings.TrimSpace(os.Getenv(name)) == "" {
212 leaking = append(leaking, name)
213 }
214 }
215 if strings.TrimSpace(os.Getenv("CARLOS_SMTP_PASS")) == "" {
216 undeliverable = append(undeliverable, "CARLOS_SMTP_PASS")
217 }
218 if len(leaking) > 0 {
219 return nil, fmt.Errorf(
220 "mail is not configured: CARLOS_MAIL is not \"submit\" and %s not set, so magic links would be written to the log instead of emailed. Run `carlos email enable --app home`",
221 strings.Join(leaking, ", "))
222 }
223 if len(undeliverable) > 0 {
224 return nil, fmt.Errorf(
225 "mail is not configured: %s not set, so every magic link would fail at send time. Run `carlos email enable --app home`",
226 strings.Join(undeliverable, ", "))
227 }
228 return mail.FromCarlos("CARLOS", logger)
229}
230