package main import ( "crypto/ed25519" "encoding/base64" "errors" "fmt" "net" "net/netip" "os" "strconv" "strings" "amadan.net/oficina/equipo/internal/hostedctl" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" "amadan.net/oficina/equipo/internal/isolatedjob/awsjob" ) // fileConfig is the -config file: one JSON object read with // hostedwire.DecodeStrict, so an unknown or repeated key is refused. Every // field is required. // // Keys. Each controller has verify keys of its own, and each key stays under // one key ID for good: the key ID is not signed, so a key reused by another // controller, or an ID moved to another key, cannot be told apart from the // right one. Load refuses an ID listed twice and one public key under two // IDs, but cannot see keys shared with another controller. // // Launches are switched on only by EQUIPO_HOSTED_ENABLED=1 in the // environment, never by this file. type fileConfig struct { // Listen is the HTTPS API's address and MetricsListen the plain HTTP // metrics listener's: an IP address and port each, never a wildcard. Listen string `json:"listen"` MetricsListen string `json:"metrics_listen"` TLSCertFile string `json:"tls_cert_file"` TLSKeyFile string `json:"tls_key_file"` Database string `json:"database"` // SigningKeyFile holds the controller's ed25519 seed (32 bytes) in // standard base64. It must not be readable by group or others. SigningKeyFile string `json:"signing_key_file"` VerifyKeys []keyEntry `json:"verify_keys"` Images []imageEntry `json:"images"` Region string `json:"region"` VPCID string `json:"vpc_id"` VMSubnetID string `json:"vm_subnet_id"` // VMSecurityGroupID is the connector's only security group. VMSecurityGroupID string `json:"vm_security_group_id"` // ConnectorARN is the version-qualified ARN of the VPC_EGRESS connector. ConnectorARN string `json:"connector_arn"` // Egress is every "address:port" VMs may reach, as the network audit // expects it. Slice 1a has no egress stack, so it must be empty ([]): // the VM security group has no outbound rules (ruling R30). Egress []string `json:"egress"` SNSTopicARN string `json:"sns_topic_arn"` } // keyEntry is one verify key: its ID, role (instance or operator) and // ed25519 public key in standard base64. type keyEntry struct { ID string `json:"id"` Role string `json:"role"` PublicKey string `json:"public_key"` } // imageEntry is one certified image: its digest, MicroVM image ARN and the // image version for each size ("small", "large"). type imageEntry struct { Digest string `json:"digest"` ARN string `json:"arn"` Versions map[string]string `json:"versions"` } // config is a checked fileConfig, ready to wire. type config struct { listen, metricsListen, tlsCert, tlsKey, database, topicARN string signing ed25519.PrivateKey keys map[hostedwire.KeyID]hostedwire.VerifyKey ctl hostedctl.Config aws awsjob.Config } // enabledEnv is the one switch for launches. const enabledEnv = "EQUIPO_HOSTED_ENABLED" // loadConfig reads and checks the config file at path. getenv reads the // environment (os.Getenv in main). func loadConfig(path string, getenv func(string) string) (config, error) { if path == "" { return config{}, errors.New("no -config file given") } f, err := os.Open(path) if err != nil { return config{}, err } defer f.Close() var fc fileConfig if err := hostedwire.DecodeStrict(f, &fc); err != nil { return config{}, fmt.Errorf("config %s: %w", path, err) } c, err := fc.check() if err != nil { return config{}, fmt.Errorf("config %s: %w", path, err) } c.ctl.Enabled = getenv(enabledEnv) == "1" return c, nil } func (fc fileConfig) check() (config, error) { c := config{tlsCert: fc.TLSCertFile, tlsKey: fc.TLSKeyFile, database: fc.Database, topicARN: fc.SNSTopicARN} var err error if c.listen, err = checkListen("listen", fc.Listen); err != nil { return config{}, err } if c.metricsListen, err = checkListen("metrics_listen", fc.MetricsListen); err != nil { return config{}, err } if c.listen == c.metricsListen { return config{}, errors.New("listen and metrics_listen must differ") } for name, v := range map[string]string{"tls_cert_file": fc.TLSCertFile, "tls_key_file": fc.TLSKeyFile, "database": fc.Database, "signing_key_file": fc.SigningKeyFile, "sns_topic_arn": fc.SNSTopicARN} { if v == "" { return config{}, fmt.Errorf("%s is required", name) } } if c.signing, err = readSigningKey(fc.SigningKeyFile); err != nil { return config{}, err } if c.keys, err = verifyKeys(fc.VerifyKeys); err != nil { return config{}, err } if c.aws, err = fc.awsConfig(); err != nil { return config{}, err } c.ctl.Images = map[isolatedjob.ImageDigest]bool{} for d := range c.aws.Images { c.ctl.Images[d] = true } c.ctl.Egress = c.aws.Egress c.ctl.ProviderFingerprint = c.aws.Fingerprint return c, nil } // checkListen accepts only "IP:port" with a specific IP: a wildcard // (0.0.0.0, ::) or an empty host (":port") would listen on every interface, // and a host name could resolve to anything. func checkListen(name, addr string) (string, error) { if addr == "" { return "", fmt.Errorf("%s is required", name) } host, port, err := net.SplitHostPort(addr) if err != nil { return "", fmt.Errorf("%s %q is not host:port", name, addr) } ip, err := netip.ParseAddr(host) if err != nil || ip.Zone() != "" { return "", fmt.Errorf("%s %q must name one IP address, not %q", name, addr, host) } if ip.Unmap().IsUnspecified() { return "", fmt.Errorf("%s %q listens on every interface; name one address", name, addr) } n, err := strconv.ParseUint(port, 10, 16) if err != nil || n == 0 || strconv.FormatUint(n, 10) != port { return "", fmt.Errorf("%s %q has no valid port", name, addr) } return netip.AddrPortFrom(ip, uint16(n)).String(), nil } // readSigningKey reads the base64 seed in path. A file that group or others // may read is refused. func readSigningKey(path string) (ed25519.PrivateKey, error) { info, err := os.Stat(path) if err != nil { return nil, fmt.Errorf("signing key: %w", err) } if info.Mode().Perm()&0o077 != 0 { return nil, fmt.Errorf("signing key %s is readable by group or others (mode %v)", path, info.Mode().Perm()) } raw, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("signing key: %w", err) } seed, err := base64.StdEncoding.Strict().DecodeString(strings.TrimSpace(string(raw))) if err != nil || len(seed) != ed25519.SeedSize { return nil, fmt.Errorf("signing key %s must hold a %d-byte ed25519 seed in base64", path, ed25519.SeedSize) } return ed25519.NewKeyFromSeed(seed), nil } // verifyKeys builds the key table, refusing an ID listed twice, then checks // it as the API will (hostedctl.CheckVerifyKeys). func verifyKeys(entries []keyEntry) (map[hostedwire.KeyID]hostedwire.VerifyKey, error) { keys := map[hostedwire.KeyID]hostedwire.VerifyKey{} for _, k := range entries { id := hostedwire.KeyID(k.ID) if _, dup := keys[id]; dup { return nil, fmt.Errorf("verify key ID %q is listed twice", k.ID) } pub, err := base64.StdEncoding.Strict().DecodeString(k.PublicKey) if err != nil { return nil, fmt.Errorf("verify key %q: public key is not base64", k.ID) } keys[id] = hostedwire.VerifyKey{Public: pub, Role: hostedwire.Role(k.Role)} } if err := hostedctl.CheckVerifyKeys(keys); err != nil { return nil, err } return keys, nil } // awsConfig builds the adapter's config and checks it with awsjob.New, // which makes no provider call; main builds the real Runner later. func (fc fileConfig) awsConfig() (awsjob.Config, error) { ac := awsjob.Config{Region: fc.Region, ConnectorID: fc.ConnectorARN, VPCID: fc.VPCID, VMSubnetID: fc.VMSubnetID, VMSecurityGroupID: fc.VMSecurityGroupID, Images: map[isolatedjob.ImageDigest]awsjob.Image{}} for _, img := range fc.Images { d := isolatedjob.ImageDigest(img.Digest) if !validDigest(img.Digest) { return awsjob.Config{}, fmt.Errorf("image digest %q is not sha256: and 64 lower-case hex digits", img.Digest) } if _, dup := ac.Images[d]; dup { return awsjob.Config{}, fmt.Errorf("image %s is listed twice", d) } versions := map[isolatedjob.Size]string{} for size, v := range img.Versions { versions[isolatedjob.Size(size)] = v } ac.Images[d] = awsjob.Image{ARN: img.ARN, Versions: versions} } if len(fc.Egress) > 0 { return awsjob.Config{}, fmt.Errorf("egress lists %d destinations; slice 1a has no egress stack, so it must be empty", len(fc.Egress)) } if _, err := awsjob.New(ac, awsjob.NewAPI(nil, nil, nil)); err != nil { return awsjob.Config{}, err } return ac, nil } func validDigest(s string) bool { hex, ok := strings.CutPrefix(s, "sha256:") if !ok || len(hex) != 64 { return false } for i := 0; i < len(hex); i++ { if !(hex[i] >= '0' && hex[i] <= '9' || hex[i] >= 'a' && hex[i] <= 'f') { return false } } return true }