oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package main
2
3import (
4 "crypto/ed25519"
5 "encoding/base64"
6 "errors"
7 "fmt"
8 "net"
9 "net/netip"
10 "os"
11 "strconv"
12 "strings"
13
14 "amadan.net/oficina/equipo/internal/hostedctl"
15 "amadan.net/oficina/equipo/internal/hostedwire"
16 "amadan.net/oficina/equipo/internal/isolatedjob"
17 "amadan.net/oficina/equipo/internal/isolatedjob/awsjob"
18)
19
20// fileConfig is the -config file: one JSON object read with
21// hostedwire.DecodeStrict, so an unknown or repeated key is refused. Every
22// field is required.
23//
24// Keys. Each controller has verify keys of its own, and each key stays under
25// one key ID for good: the key ID is not signed, so a key reused by another
26// controller, or an ID moved to another key, cannot be told apart from the
27// right one. Load refuses an ID listed twice and one public key under two
28// IDs, but cannot see keys shared with another controller.
29//
30// Launches are switched on only by EQUIPO_HOSTED_ENABLED=1 in the
31// environment, never by this file.
32type fileConfig struct {
33 // Listen is the HTTPS API's address and MetricsListen the plain HTTP
34 // metrics listener's: an IP address and port each, never a wildcard.
35 Listen string `json:"listen"`
36 MetricsListen string `json:"metrics_listen"`
37 TLSCertFile string `json:"tls_cert_file"`
38 TLSKeyFile string `json:"tls_key_file"`
39 Database string `json:"database"`
40 // SigningKeyFile holds the controller's ed25519 seed (32 bytes) in
41 // standard base64. It must not be readable by group or others.
42 SigningKeyFile string `json:"signing_key_file"`
43 VerifyKeys []keyEntry `json:"verify_keys"`
44 Images []imageEntry `json:"images"`
45 Region string `json:"region"`
46 VPCID string `json:"vpc_id"`
47 VMSubnetID string `json:"vm_subnet_id"`
48 // VMSecurityGroupID is the connector's only security group.
49 VMSecurityGroupID string `json:"vm_security_group_id"`
50 // ConnectorARN is the version-qualified ARN of the VPC_EGRESS connector.
51 ConnectorARN string `json:"connector_arn"`
52 // Egress is every "address:port" VMs may reach, as the network audit
53 // expects it. Slice 1a has no egress stack, so it must be empty ([]):
54 // the VM security group has no outbound rules (ruling R30).
55 Egress []string `json:"egress"`
56 SNSTopicARN string `json:"sns_topic_arn"`
57}
58
59// keyEntry is one verify key: its ID, role (instance or operator) and
60// ed25519 public key in standard base64.
61type keyEntry struct {
62 ID string `json:"id"`
63 Role string `json:"role"`
64 PublicKey string `json:"public_key"`
65}
66
67// imageEntry is one certified image: its digest, MicroVM image ARN and the
68// image version for each size ("small", "large").
69type imageEntry struct {
70 Digest string `json:"digest"`
71 ARN string `json:"arn"`
72 Versions map[string]string `json:"versions"`
73}
74
75// config is a checked fileConfig, ready to wire.
76type config struct {
77 listen, metricsListen, tlsCert, tlsKey, database, topicARN string
78 signing ed25519.PrivateKey
79 keys map[hostedwire.KeyID]hostedwire.VerifyKey
80 ctl hostedctl.Config
81 aws awsjob.Config
82}
83
84// enabledEnv is the one switch for launches.
85const enabledEnv = "EQUIPO_HOSTED_ENABLED"
86
87// loadConfig reads and checks the config file at path. getenv reads the
88// environment (os.Getenv in main).
89func loadConfig(path string, getenv func(string) string) (config, error) {
90 if path == "" {
91 return config{}, errors.New("no -config file given")
92 }
93 f, err := os.Open(path)
94 if err != nil {
95 return config{}, err
96 }
97 defer f.Close()
98 var fc fileConfig
99 if err := hostedwire.DecodeStrict(f, &fc); err != nil {
100 return config{}, fmt.Errorf("config %s: %w", path, err)
101 }
102 c, err := fc.check()
103 if err != nil {
104 return config{}, fmt.Errorf("config %s: %w", path, err)
105 }
106 c.ctl.Enabled = getenv(enabledEnv) == "1"
107 return c, nil
108}
109
110func (fc fileConfig) check() (config, error) {
111 c := config{tlsCert: fc.TLSCertFile, tlsKey: fc.TLSKeyFile, database: fc.Database, topicARN: fc.SNSTopicARN}
112 var err error
113 if c.listen, err = checkListen("listen", fc.Listen); err != nil {
114 return config{}, err
115 }
116 if c.metricsListen, err = checkListen("metrics_listen", fc.MetricsListen); err != nil {
117 return config{}, err
118 }
119 if c.listen == c.metricsListen {
120 return config{}, errors.New("listen and metrics_listen must differ")
121 }
122 for name, v := range map[string]string{"tls_cert_file": fc.TLSCertFile, "tls_key_file": fc.TLSKeyFile,
123 "database": fc.Database, "signing_key_file": fc.SigningKeyFile, "sns_topic_arn": fc.SNSTopicARN} {
124 if v == "" {
125 return config{}, fmt.Errorf("%s is required", name)
126 }
127 }
128 if c.signing, err = readSigningKey(fc.SigningKeyFile); err != nil {
129 return config{}, err
130 }
131 if c.keys, err = verifyKeys(fc.VerifyKeys); err != nil {
132 return config{}, err
133 }
134 if c.aws, err = fc.awsConfig(); err != nil {
135 return config{}, err
136 }
137 c.ctl.Images = map[isolatedjob.ImageDigest]bool{}
138 for d := range c.aws.Images {
139 c.ctl.Images[d] = true
140 }
141 c.ctl.Egress = c.aws.Egress
142 c.ctl.ProviderFingerprint = c.aws.Fingerprint
143 return c, nil
144}
145
146// checkListen accepts only "IP:port" with a specific IP: a wildcard
147// (0.0.0.0, ::) or an empty host (":port") would listen on every interface,
148// and a host name could resolve to anything.
149func checkListen(name, addr string) (string, error) {
150 if addr == "" {
151 return "", fmt.Errorf("%s is required", name)
152 }
153 host, port, err := net.SplitHostPort(addr)
154 if err != nil {
155 return "", fmt.Errorf("%s %q is not host:port", name, addr)
156 }
157 ip, err := netip.ParseAddr(host)
158 if err != nil || ip.Zone() != "" {
159 return "", fmt.Errorf("%s %q must name one IP address, not %q", name, addr, host)
160 }
161 if ip.Unmap().IsUnspecified() {
162 return "", fmt.Errorf("%s %q listens on every interface; name one address", name, addr)
163 }
164 n, err := strconv.ParseUint(port, 10, 16)
165 if err != nil || n == 0 || strconv.FormatUint(n, 10) != port {
166 return "", fmt.Errorf("%s %q has no valid port", name, addr)
167 }
168 return netip.AddrPortFrom(ip, uint16(n)).String(), nil
169}
170
171// readSigningKey reads the base64 seed in path. A file that group or others
172// may read is refused.
173func readSigningKey(path string) (ed25519.PrivateKey, error) {
174 info, err := os.Stat(path)
175 if err != nil {
176 return nil, fmt.Errorf("signing key: %w", err)
177 }
178 if info.Mode().Perm()&0o077 != 0 {
179 return nil, fmt.Errorf("signing key %s is readable by group or others (mode %v)", path, info.Mode().Perm())
180 }
181 raw, err := os.ReadFile(path)
182 if err != nil {
183 return nil, fmt.Errorf("signing key: %w", err)
184 }
185 seed, err := base64.StdEncoding.Strict().DecodeString(strings.TrimSpace(string(raw)))
186 if err != nil || len(seed) != ed25519.SeedSize {
187 return nil, fmt.Errorf("signing key %s must hold a %d-byte ed25519 seed in base64", path, ed25519.SeedSize)
188 }
189 return ed25519.NewKeyFromSeed(seed), nil
190}
191
192// verifyKeys builds the key table, refusing an ID listed twice, then checks
193// it as the API will (hostedctl.CheckVerifyKeys).
194func verifyKeys(entries []keyEntry) (map[hostedwire.KeyID]hostedwire.VerifyKey, error) {
195 keys := map[hostedwire.KeyID]hostedwire.VerifyKey{}
196 for _, k := range entries {
197 id := hostedwire.KeyID(k.ID)
198 if _, dup := keys[id]; dup {
199 return nil, fmt.Errorf("verify key ID %q is listed twice", k.ID)
200 }
201 pub, err := base64.StdEncoding.Strict().DecodeString(k.PublicKey)
202 if err != nil {
203 return nil, fmt.Errorf("verify key %q: public key is not base64", k.ID)
204 }
205 keys[id] = hostedwire.VerifyKey{Public: pub, Role: hostedwire.Role(k.Role)}
206 }
207 if err := hostedctl.CheckVerifyKeys(keys); err != nil {
208 return nil, err
209 }
210 return keys, nil
211}
212
213// awsConfig builds the adapter's config and checks it with awsjob.New,
214// which makes no provider call; main builds the real Runner later.
215func (fc fileConfig) awsConfig() (awsjob.Config, error) {
216 ac := awsjob.Config{Region: fc.Region, ConnectorID: fc.ConnectorARN, VPCID: fc.VPCID, VMSubnetID: fc.VMSubnetID,
217 VMSecurityGroupID: fc.VMSecurityGroupID, Images: map[isolatedjob.ImageDigest]awsjob.Image{}}
218 for _, img := range fc.Images {
219 d := isolatedjob.ImageDigest(img.Digest)
220 if !validDigest(img.Digest) {
221 return awsjob.Config{}, fmt.Errorf("image digest %q is not sha256: and 64 lower-case hex digits", img.Digest)
222 }
223 if _, dup := ac.Images[d]; dup {
224 return awsjob.Config{}, fmt.Errorf("image %s is listed twice", d)
225 }
226 versions := map[isolatedjob.Size]string{}
227 for size, v := range img.Versions {
228 versions[isolatedjob.Size(size)] = v
229 }
230 ac.Images[d] = awsjob.Image{ARN: img.ARN, Versions: versions}
231 }
232 if len(fc.Egress) > 0 {
233 return awsjob.Config{}, fmt.Errorf("egress lists %d destinations; slice 1a has no egress stack, so it must be empty", len(fc.Egress))
234 }
235 if _, err := awsjob.New(ac, awsjob.NewAPI(nil, nil, nil)); err != nil {
236 return awsjob.Config{}, err
237 }
238 return ac, nil
239}
240
241func validDigest(s string) bool {
242 hex, ok := strings.CutPrefix(s, "sha256:")
243 if !ok || len(hex) != 64 {
244 return false
245 }
246 for i := 0; i < len(hex); i++ {
247 if !(hex[i] >= '0' && hex[i] <= '9' || hex[i] >= 'a' && hex[i] <= 'f') {
248 return false
249 }
250 }
251 return true
252}
253