oficina / fichas Public

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

Plain git — no account needed to clone.

Download

Download this file

1package fichas
2
3import (
4 "encoding/base64"
5 "errors"
6 "fmt"
7 "net"
8 "net/url"
9 "strconv"
10 "strings"
11
12 "amadan.net/oficina/fichas/internal/fichas/seal"
13 "amadan.net/oficina/suite/server"
14)
15
16// Config is everything fichas needs from platform config.
17//
18// This is a type with a constructor rather than a run of os.Getenv calls in
19// main, for one reason: the refusals below are a safety property, and a
20// safety property needs a test. memoria's config.go records why — an
21// earlier version of the same validation lived inline in main and was
22// "checked" by grepping for os.Exit near each variable name, which passed
23// even when the refusal was deleted, because a neighbouring error path
24// supplied the os.Exit the grep was looking for.
25type Config struct {
26 ContractRelease *ContractReleaseConfig
27
28 Origin string
29 Sealer *seal.Sealer
30 // InstanceKey seals auth's pending blob. auth.New refuses an empty
31 // one, and rightly: an empty input hashes to a fixed, publicly
32 // computable value identical across every deployment.
33 InstanceKey string
34 // Owners is the admission list. In the LONE shape it is the whole
35 // admitted set; in the SUITE shape it answers the narrower question
36 // of who operates the instance (ruling 5, memoria §2).
37 Owners []string
38 // MailConfigured reports whether real mail is wired: CARLOS mail
39 // submission or SMTP. False means mail.Logged, which writes sign-in
40 // links into the process log.
41 MailConfigured bool
42 // Shape is "lone" or "suite" — ruling 5's one switch. Suite is the
43 // intended default; see ErrSuiteNotBuilt.
44 Shape string
45 // AllowLoggedMail permits booting with no SMTP, which makes rastrillo
46 // substitute mail.Logged — and mail.Logged writes the magic link, a
47 // live credential, into the process log. Platform log storage is not
48 // something we can grep and retract, so that is a credential we
49 // cannot take back. Opt in explicitly, for local development.
50 AllowLoggedMail bool
51 // Directory is the hub directory's origin (HOME_DIRECTORY_ORIGIN, the
52 // name Home and the other apps use), the account menu's "All apps".
53 // Empty — a standalone instance — and there is no "All apps".
54 Directory string
55 // SuiteConsumers are the siblings allowed to call the suite routes
56 // (spec §6.5), from FICHAS_SUITE_CONSUMERS. None, and the routes do
57 // not exist.
58 SuiteConsumers []server.Consumer
59 // Locale is the team's formatting locale (level-up §6.8), from
60 // FICHAS_LOCALE: the CLDR locale a reader's numbers and dates are
61 // written in when their browser names none Fichas can use.
62 Locale string
63}
64
65// ErrMissing is returned when required platform config is absent.
66var ErrMissing = errors.New("fichas: required configuration is missing")
67
68// defaultOrigin is what an unset FICHAS_ORIGIN falls back to. Local only:
69// it is the CSRF yardstick, so on a real host it must be the host the
70// browser is actually on.
71const defaultOrigin = "http://127.0.0.1:8824"
72
73// LoadConfig reads and validates configuration. getenv is a parameter so a
74// test can supply an environment without mutating the process's.
75//
76// **There is deliberately no generated-fallback DEK.** A fallback would
77// seal this boot's cards under a key the next boot cannot derive, losing
78// the data quietly instead of refusing loudly. Failing to start is the
79// correct behaviour and the only honest one.
80func LoadConfig(getenv func(string) string) (Config, error) {
81 var c Config
82
83 dekRaw := getenv("FICHAS_DEK")
84 if dekRaw == "" {
85 return c, fmt.Errorf("%w: FICHAS_DEK", ErrMissing)
86 }
87 dek, err := base64.StdEncoding.DecodeString(dekRaw)
88 if err != nil {
89 return c, fmt.Errorf("fichas: FICHAS_DEK is not valid base64: %w", err)
90 }
91 sealer, err := seal.New(dek)
92 if err != nil {
93 return c, fmt.Errorf("fichas: FICHAS_DEK rejected: %w", err)
94 }
95 c.Sealer = sealer
96
97 c.Origin = getenv("FICHAS_ORIGIN")
98 if c.Origin == "" {
99 c.Origin = defaultOrigin
100 }
101
102 c.InstanceKey = getenv("FICHAS_INSTANCE_KEY")
103 if c.InstanceKey == "" {
104 return Config{}, fmt.Errorf("%w: FICHAS_INSTANCE_KEY", ErrMissing)
105 }
106
107 // There is no default owner list. An empty admission gate on a public
108 // hostname admits anyone who can receive mail, so the app refuses to
109 // start rather than serving in that state.
110 c.Owners = ParseOwners(getenv("FICHAS_OWNERS"))
111 if len(c.Owners) == 0 {
112 return Config{}, fmt.Errorf("%w: FICHAS_OWNERS", ErrMissing)
113 }
114
115 c.AllowLoggedMail = getenv("FICHAS_ALLOW_LOGGED_MAIL") == "1"
116 if c.AllowLoggedMail && !isLocal(c.Origin) {
117 return Config{}, fmt.Errorf(
118 "fichas: FICHAS_ALLOW_LOGGED_MAIL writes a live sign-in credential into the process log "+
119 "and is local-development only, but FICHAS_ORIGIN is %s", c.Origin)
120 }
121
122 // **Refusing the flag was only half the guard, and the first deploy
123 // proved it.** rastrillo's mail.FromEnv falls back to mail.Logged
124 // with nothing but a Warn when SMTP is unset, so fichas booted on a
125 // public origin wired to write every magic link — a live credential,
126 // usable by anyone who can read the log — into platform log storage
127 // we cannot grep and cannot retract. Nothing failed; a WARN scrolled
128 // past. memoria refuses to start in this state and this app claimed
129 // to without doing it.
130 //
131 // Mail is either channel rastrillo's mail.FromCarlos takes (Mailer,
132 // mailer.go): CARLOS mail submission, which the agent turns on with
133 // CARLOS_MAIL=submit beside its control socket, or SMTP under the
134 // suite's prefix, CARLOS_SMTP_*.
135 submit := getenv("CARLOS_MAIL") == "submit"
136 smtp := getenv("CARLOS_SMTP_HOST") != "" && getenv("CARLOS_SMTP_FROM") != ""
137 c.MailConfigured = submit || smtp
138 if !c.MailConfigured && !c.AllowLoggedMail {
139 return Config{}, fmt.Errorf(
140 "%w: CARLOS_MAIL=submit, or CARLOS_SMTP_HOST and CARLOS_SMTP_FROM — without one every sign-in link is written "+
141 "to the log instead of sent, which is a live credential in storage we cannot retract; "+
142 "set FICHAS_ALLOW_LOGGED_MAIL=1 to accept that on a loopback origin", ErrMissing)
143 }
144
145 if c.Directory, err = directoryOrigin(getenv("HOME_DIRECTORY_ORIGIN")); err != nil {
146 return Config{}, err
147 }
148 c.Shape = strings.ToLower(strings.TrimSpace(getenv("FICHAS_SHAPE")))
149 if c.Shape == "" {
150 c.Shape = ShapeLone
151 }
152 switch c.Shape {
153 case ShapeLone:
154 case ShapeSuite:
155 // Ruling 5: a suite instance takes identity AND membership from
156 // the home, and never one without the other. fichas has neither
157 // yet. Refusing is the honest answer — the alternative is booting
158 // in a shape whose admission gate is the owners list while the
159 // operator believes it is the home's roster, which is a roster
160 // invented in the wrong app.
161 return Config{}, ErrSuiteNotBuilt
162 default:
163 return Config{}, fmt.Errorf("fichas: FICHAS_SHAPE is %q; it is %q or %q", c.Shape, ShapeLone, ShapeSuite)
164 }
165 // Parsed at boot: a malformed list refuses to start rather than
166 // silently serving nobody, or serving somebody it should not.
167 if c.SuiteConsumers, err = server.ConsumersFromEnv(getenv, "fichas"); err != nil {
168 return Config{}, fmt.Errorf("fichas: FICHAS_SUITE_CONSUMERS: %w", err)
169 }
170 c.ContractRelease, err = loadContractRelease(getenv, c.Origin)
171 if err != nil {
172 return Config{}, err
173 }
174 if c.Locale, err = teamLocale(getenv("FICHAS_LOCALE")); err != nil {
175 return Config{}, err
176 }
177 return c, nil
178}
179
180// The two shapes, ruling 5. "Membership authority follows identity
181// authority; an instance never has one without the other."
182const (
183 ShapeLone = "lone"
184 ShapeSuite = "suite"
185)
186
187// ErrSuiteNotBuilt is returned for FICHAS_SHAPE=suite.
188//
189// The suite shape is the intended default — Paul, 2026-09-21 — and it is
190// specified rather than built, the way the suite's own S6 is. It needs the
191// home's identity bridge and its roster pull (suite call 8), and neither
192// exists in this app. Named as its own error so the day it lands there is
193// one place to delete.
194var ErrSuiteNotBuilt = errors.New(
195 "fichas: FICHAS_SHAPE=suite is the intended default and is not built yet — " +
196 "it needs the home's identity bridge and roster pull; run lone for now")
197
198// isLocal reports whether an origin is a loopback address. Deliberately
199// strict: a hostname that merely looks local is not one.
200func isLocal(origin string) bool {
201 for _, p := range []string{"http://127.0.0.1:", "http://localhost:", "http://[::1]:"} {
202 if strings.HasPrefix(origin, p) {
203 return true
204 }
205 }
206 return origin == "http://127.0.0.1" || origin == "http://localhost"
207}
208
209// UsedDefaultOrigin reports whether Origin fell back, so main can say so
210// out loud. A silently defaulted origin is a CSRF yardstick pointing at
211// the wrong host.
212func (c Config) UsedDefaultOrigin() bool { return c.Origin == defaultOrigin }
213
214// directoryOrigin validates HOME_DIRECTORY_ORIGIN: empty, or an origin
215// and nothing else — https, or http on a loopback host for local
216// development — returned without a trailing slash. It becomes a link in
217// every page, so anything else is refused at boot rather than drawn.
218//
219// The host and the port are judged apart, on the parsed URL: a prefix
220// test on the string refused loopback with no port and let a host-less
221// "https://:443" through (Astra, fichas #7).
222func directoryOrigin(v string) (string, error) {
223 v = strings.TrimSuffix(strings.TrimSpace(v), "/")
224 if v == "" {
225 return "", nil
226 }
227 refuse := fmt.Errorf("fichas: HOME_DIRECTORY_ORIGIN is %q; it is the hub directory's origin, https://host", v)
228 u, err := url.Parse(v)
229 if err != nil || u.Opaque != "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || u.ForceQuery {
230 return "", refuse
231 }
232 host := u.Hostname()
233 if host == "" {
234 return "", refuse
235 }
236 // A port, if the URL has a colon after the host, is 1-65535 in digits.
237 if strings.HasSuffix(u.Host, ":") {
238 return "", refuse
239 }
240 if p := u.Port(); p != "" {
241 n, err := strconv.Atoi(p)
242 if err != nil || n < 1 || n > 65535 {
243 return "", refuse
244 }
245 }
246 switch u.Scheme {
247 case "https":
248 case "http":
249 if !loopbackHost(host) {
250 return "", refuse
251 }
252 default:
253 return "", refuse
254 }
255 return u.Scheme + "://" + u.Host, nil
256}
257
258// loopbackHost is a loopback hostname, exactly: localhost, or a loopback
259// IP address. A name that merely starts like one is not.
260func loopbackHost(host string) bool {
261 if host == "localhost" {
262 return true
263 }
264 ip := net.ParseIP(host)
265 return ip != nil && ip.IsLoopback()
266}
267