oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package config reads Base's settings from BASE_* environment variables.
2package config
3
4import (
5 "crypto/elliptic"
6 "encoding/base64"
7 "errors"
8 "fmt"
9 "net"
10 "net/url"
11 "regexp"
12 "strings"
13 "time"
14 _ "time/tzdata" // the release binary must not depend on host zoneinfo
15
16 "amadan.net/oficina/home/connect"
17 "amadan.net/rastrillo/rastrillo/assertion"
18 "amadan.net/rastrillo/rastrillo/crypto"
19
20 "amadan.net/oficina/base/internal/catalog"
21)
22
23// A host label is "<slug>-<appid>", at most 32 characters. App ids in the
24// catalogue are at most 12 characters, so the slug gets what is left.
25const (
26 maxLabel = 32
27 maxAppID = 12
28 maxSlug = maxLabel - 1 - maxAppID
29)
30
31var slugRE = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`)
32
33type Config struct {
34 Origin string
35 Name string
36 Slug string
37 Owner string
38 AppsDomain string
39 Timezone *time.Location
40 PlatformConsole string
41 PlatformAccount string
42 InstanceToken string
43 OperateToken string
44 AssertionKey *crypto.Keypair
45 AllowLoggedMail bool
46 // InstanceKey seals sign-in state (BASE_INSTANCE_KEY). Keep it secret and
47 // stable: changing it invalidates links and sign-ins in flight.
48 InstanceKey string
49 // EquipoOrigin is the Equipo instance whose coordinator answers "Ask
50 // Base anything" (BASE_EQUIPO_ORIGIN). Empty leaves the chat off.
51 EquipoOrigin string
52 // OficinaApps are the team's Oficina apps, in the order Home lists
53 // them (BASE_OFICINA_APPS). Empty leaves them off Home.
54 OficinaApps []OficinaApp
55 // Home turns on sign-in with Oficina ID. Nil (no BASE_HOME_* settings)
56 // leaves it off; LoadHome sets it.
57 Home *connect.DecodedCredentials
58}
59
60// Load reads the configuration. getenv is os.Getenv in production.
61func Load(getenv func(string) string) (Config, error) {
62 get := func(k string) string { return strings.TrimSpace(getenv("BASE_" + k)) }
63 cfg := Config{
64 Origin: strings.TrimRight(get("ORIGIN"), "/"),
65 Name: get("NAME"),
66 Slug: get("SLUG"),
67 Owner: strings.ToLower(get("OWNER")),
68 AppsDomain: strings.ToLower(get("APPS_DOMAIN")),
69 PlatformConsole: strings.TrimRight(get("PLATFORM_CONSOLE"), "/"),
70 PlatformAccount: get("PLATFORM_ACCOUNT"),
71 InstanceToken: get("PLATFORM_INSTANCE_TOKEN"),
72 OperateToken: get("PLATFORM_OPERATE_TOKEN"),
73 AllowLoggedMail: get("ALLOW_LOGGED_MAIL") == "1",
74 InstanceKey: get("INSTANCE_KEY"),
75 }
76 if cfg.Origin == "" {
77 return Config{}, errors.New("BASE_ORIGIN is required")
78 }
79 if cfg.Owner == "" {
80 return Config{}, errors.New("BASE_OWNER is required")
81 }
82 if cfg.Name == "" {
83 cfg.Name = "Base"
84 }
85 if cfg.Slug == "" {
86 cfg.Slug = "base"
87 }
88 if len(cfg.Slug) > maxSlug || !slugRE.MatchString(cfg.Slug) {
89 return Config{}, fmt.Errorf("BASE_SLUG %q must be 1 to %d characters of a-z, 0-9 and -, not starting or ending with -", cfg.Slug, maxSlug)
90 }
91 local, err := originIsLocal(cfg.Origin)
92 if err != nil {
93 return Config{}, err
94 }
95 if cfg.AllowLoggedMail && !local {
96 return Config{}, errors.New("BASE_ALLOW_LOGGED_MAIL=1 is only allowed with a loopback BASE_ORIGIN")
97 }
98 tz := get("TIMEZONE")
99 if tz == "" {
100 tz = "Europe/Dublin"
101 }
102 if cfg.Timezone, err = time.LoadLocation(tz); err != nil {
103 return Config{}, fmt.Errorf("BASE_TIMEZONE: %w", err)
104 }
105 if raw := get("ASSERTION_KEY"); raw != "" {
106 b, err := base64.StdEncoding.DecodeString(raw)
107 if err != nil {
108 return Config{}, fmt.Errorf("BASE_ASSERTION_KEY is not base64: %w", err)
109 }
110 if cfg.AssertionKey, err = crypto.UnmarshalKeypair(b); err != nil {
111 return Config{}, fmt.Errorf("BASE_ASSERTION_KEY: %w", err)
112 }
113 }
114 if cfg.EquipoOrigin, err = equipoOrigin(get("EQUIPO_ORIGIN")); err != nil {
115 return Config{}, err
116 }
117 if cfg.OficinaApps, err = parseOficinaApps(get("OFICINA_APPS")); err != nil {
118 return Config{}, err
119 }
120 if cfg.AppsDomain != "" {
121 if err := checkAssertionOrigins(cfg, local); err != nil {
122 return Config{}, err
123 }
124 }
125 return cfg, nil
126}
127
128// checkAssertionOrigins holds, with installs configured, Base's origin and
129// each catalogue app's origin to the rules rastrillo/assertion applies to an
130// assertion's issuer and audience (https, a DNS hostname, no :443), by asking
131// it to build a verifier for each pair. A loopback http Base origin is the
132// local-run mode and is not checked; handoffs cannot work there.
133func checkAssertionOrigins(cfg Config, local bool) error {
134 issuer := cfg.Origin
135 if local && strings.HasPrefix(issuer, "http://") {
136 issuer = "https://base.invalid" // stands in, so the app origins are still checked
137 } else if _, err := assertion.NewVerifier(issuer, "https://app.invalid", probeKeys); err != nil {
138 return fmt.Errorf("BASE_ORIGIN %q cannot issue assertions: it must be https with a DNS hostname and no :443", cfg.Origin)
139 }
140 for _, e := range catalog.All() {
141 app := "https://" + cfg.Slug + "-" + e.ID + "." + cfg.AppsDomain
142 if _, err := assertion.NewVerifier(issuer, app, probeKeys); err != nil {
143 return fmt.Errorf("BASE_APPS_DOMAIN %q gives %s the origin %q, which cannot receive assertions: it must be a DNS hostname with no :443", cfg.AppsDomain, e.ID, app)
144 }
145 }
146 return nil
147}
148
149// probeKeys is a key set the verifier accepts (P-256's base point), for
150// checking origins only; nothing is ever verified with it.
151var probeKeys = func() map[string][]byte {
152 p := elliptic.P256().Params()
153 pub := make([]byte, 65)
154 pub[0] = 4
155 p.Gx.FillBytes(pub[1:33])
156 p.Gy.FillBytes(pub[33:])
157 return map[string][]byte{"probe": pub}
158}()
159
160// originIsLocal checks BASE_ORIGIN is https, or http on a loopback host,
161// and reports whether it is loopback.
162func originIsLocal(origin string) (bool, error) {
163 u, err := url.Parse(origin)
164 if err != nil || u.Host == "" || u.Path != "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
165 return false, fmt.Errorf("BASE_ORIGIN %q must be a scheme and host only", origin)
166 }
167 host := strings.ToLower(u.Hostname())
168 ip := net.ParseIP(host)
169 local := host == "localhost" || (ip != nil && ip.IsLoopback())
170 if ip != nil && u.Scheme == "https" {
171 return false, fmt.Errorf("BASE_ORIGIN %q must use a hostname, not an IP address", origin)
172 }
173 if u.Scheme != "https" && !(u.Scheme == "http" && local) {
174 return false, fmt.Errorf("BASE_ORIGIN %q must be https (http only on loopback)", origin)
175 }
176 return local, nil
177}
178
179// equipoOrigin checks BASE_EQUIPO_ORIGIN: empty, or a scheme and host only,
180// https (http only on a loopback host, for a local Equipo).
181func equipoOrigin(raw string) (string, error) {
182 raw = strings.TrimRight(raw, "/")
183 if raw == "" {
184 return "", nil
185 }
186 if _, err := originIsLocal(raw); err != nil {
187 return "", fmt.Errorf("BASE_EQUIPO_ORIGIN %q must be an https origin: a scheme and host only (http only on loopback)", raw)
188 }
189 return raw, nil
190}
191