oficina / calendar Public

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

Plain git — no account needed to clone.

Download

Download this file

1package calendar
2
3import (
4 "amadan.net/oficina/home/connect"
5 "encoding/base64"
6 "fmt"
7 "log/slog"
8 "net/http"
9 "net/url"
10 "strings"
11 "time"
12
13 "amadan.net/oficina/home/roster"
14 "amadan.net/oficina/home/teammode"
15 "amadan.net/rastrillo/rastrillo/mail"
16)
17
18// DefaultOrigin is what an Env == "development" instance falls back to
19// when Config.Origin is empty. Every other Env refuses instead: see
20// resolveOrigin.
21const DefaultOrigin = "http://localhost:8080"
22
23// Config is everything the app needs from its environment, resolved by
24// cmd/calendar/main.go and handed to New. Every field with a
25// fail-closed rule states it here, and New applies the rule at boot —
26// the family's shape: a misconfigured instance refuses to start, never
27// quietly does the wrong thing.
28type Config struct {
29 Home *connect.Credentials
30
31 // Team is roster team mode's configuration (teammode.ConfigFromEnv
32 // with prefix CALENDAR: the five CALENDAR_TEAM_* variables, all or
33 // none), nil with team mode off. It exists only beside Home, and in
34 // team mode AllowedAddresses is optional: if set it only admits local
35 // sign-in, and gives nobody team standing (team_config.go).
36 Team *teammode.Config
37 // teamTransport and teamClock are for tests: a directory that answers
38 // in memory and a clock a test can step (teammodetest). Production
39 // leaves both nil.
40 teamTransport http.RoundTripper
41 teamClock roster.Clock
42 AgentIssuer, AgentTeam string
43 // DBPath is the SQLite file this instance owns. The platform hands
44 // it in as activation argv; a developer passes -db.
45 DBPath string
46
47 // Env is "production" unless a developer said otherwise with the
48 // literal -env flag. It is never honoured as "development" when it
49 // arrives from the process environment — see chooseEnv in
50 // cmd/calendar/main.go for why that one direction is asymmetric.
51 Env string
52
53 // Origin is this instance's external origin, scheme included
54 // ("https://calendar.bds.oncarlos.com"). It is the CSRF check's
55 // yardstick, the base of every emailed sign-in link, the decider
56 // of Secure/__Host- cookie attributes, and — because a calendar
57 // subscription URL has to be absolute to be subscribable — the
58 // base of every published .ics feed URL. Empty is refused outside
59 // development.
60 Origin string
61
62 // InstanceKey seals the sign-in flow's pending blob. Empty is
63 // refused outside development: an empty key hashes to one fixed,
64 // publicly computable value, identical across every deployment
65 // that left it unset.
66 InstanceKey string
67
68 // Mailer delivers sign-in links, and the reminders themselves.
69 // Nil is refused outside development — a sign-in that cannot send
70 // its link is not sign-in, and a reminder that cannot be delivered
71 // is not a reminder.
72 Mailer mail.Sender
73
74 // DEK is the base64 data encryption key, exactly 32 bytes decoded
75 // ($CALENDAR_DEK, set with `carlos secrets set`). It seals every
76 // title, place and note, and it is never written to the database it
77 // decrypts. Empty is refused outside development: the one rule is
78 // not optional, and an instance that booted without a key would
79 // write plaintext into a file the platform replicates to object
80 // storage.
81 DEK string
82
83 // AllowedAddresses is the comma-separated admission allowlist
84 // ($CALENDAR_ALLOWED_ADDRESSES). Empty is refused outside
85 // development rather than defaulting to "admit nobody": an
86 // instance that silently admitted nobody would look identical from
87 // the outside to one working correctly. See resolveAllowlist. In team
88 // mode it is optional and only admits local sign-in: empty admits
89 // nobody locally, in every Env.
90 AllowedAddresses string
91
92 Logger *slog.Logger
93
94 // homeNow is the Home bridge's clock; nil is time.Now. Unexported:
95 // only this package's tests set it, to age a navigation marker.
96 homeNow func() time.Time
97}
98
99// resolveOrigin applies Config.Origin's fail-closed rule: a valid
100// non-empty origin always wins; empty is fine only in development,
101// where it defaults to DefaultOrigin; anywhere else it is a startup
102// refusal.
103func resolveOrigin(cfg Config) (string, error) {
104 trimmed := strings.TrimSpace(cfg.Origin)
105 switch {
106 case trimmed == "" && cfg.Env != "development":
107 return "", fmt.Errorf("calendar: Config.Origin is empty and Env is %q, not %q — refusing to start with an unset origin; set $CALENDAR_ORIGIN to this instance's real origin", cfg.Env, "development")
108 case trimmed == "":
109 return DefaultOrigin, nil
110 }
111 if err := validateOrigin(trimmed); err != nil {
112 return "", fmt.Errorf("calendar: Config.Origin is invalid: %w", err)
113 }
114 return trimmed, nil
115}
116
117// devDEK is resolveDEK's development-only fallback: a fixed, public,
118// all-zero key. Not a secret, and spelled out here rather than left
119// implicit so that nothing can mistake it for one. It seals nothing
120// outside a throwaway development database.
121var devDEK = make([]byte, 32)
122
123// resolveDEK applies Config.DEK's fail-closed rule. The length check is
124// exact rather than a minimum: AES-256 wants 32 bytes, and a shorter
125// value that got padded somewhere would produce ciphertext that looks
126// entirely fine and is not.
127func resolveDEK(cfg Config) ([]byte, error) {
128 raw := strings.TrimSpace(cfg.DEK)
129 if raw == "" {
130 if cfg.Env == "development" {
131 return devDEK, nil
132 }
133 return nil, fmt.Errorf("calendar: Config.DEK is empty and Env is %q, not %q — refusing to start: an event's contents are sealed at rest, and a boot without a key would write plaintext titles into a file the platform replicates to object storage; set $CALENDAR_DEK to 32 base64 bytes with `carlos secrets set`", cfg.Env, "development")
134 }
135 key, err := base64.StdEncoding.DecodeString(raw)
136 if err != nil {
137 return nil, fmt.Errorf("calendar: $CALENDAR_DEK is not valid base64: %w", err)
138 }
139 if len(key) != 32 {
140 return nil, fmt.Errorf("calendar: $CALENDAR_DEK decodes to %d bytes, want exactly 32", len(key))
141 }
142 return key, nil
143}
144
145// validateOrigin rejects anything that is not a bare scheme://host[:port].
146// A path, query or fragment on an origin is the tell that someone pasted
147// a page URL into the setting; carried into a magic link's base or the
148// CSRF yardstick it produces links that 404 and an origin comparison
149// that never matches, both of which surface later looking like unrelated
150// bugs.
151func validateOrigin(origin string) error {
152 u, err := url.Parse(origin)
153 if err != nil {
154 return fmt.Errorf("parse %q: %w", origin, err)
155 }
156 if u.Scheme != "http" && u.Scheme != "https" {
157 return fmt.Errorf("origin %q: scheme must be http or https, got %q", origin, u.Scheme)
158 }
159 // Hostname(), not Host: "http://:8099" parses with an empty
160 // hostname and a port, and reads as valid to anything that only
161 // checks Host != "".
162 if u.Hostname() == "" {
163 return fmt.Errorf("origin %q: no host", origin)
164 }
165 if u.Path != "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
166 return fmt.Errorf("origin %q: an origin is scheme://host[:port] and nothing else — no path, query, fragment or userinfo", origin)
167 }
168 return nil
169}
170