diff --git a/README.md b/README.md index 8c36f11..98cc416 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,11 @@ It prints the DNS TXT records to publish at `_dnsaddr.allmende.stinnesbeck.com` (`dnsaddr=/ip4//tcp/4001/p2p/`, one per address). With a few such nodes on different networks, the network no longer depends on any one of them. In Docker replace the command (see the end of the `Dockerfile`) and add `--public`; -the NixOS module has `services.allmende.public = true`. +the NixOS module has `services.allmende.public = true`. On Kubernetes, `k8s/` +has ready manifests (kustomize), including how to run it behind a home router +with a port forward: see [k8s/README.md](k8s/README.md). A node that does not +know its own public address (router, container) is told one with +`--announce /dns4//tcp/4001`. ## Running a node for real diff --git a/cmd/allmende/bootstrap_test.go b/cmd/allmende/bootstrap_test.go index 9844ed3..298871a 100644 --- a/cmd/allmende/bootstrap_test.go +++ b/cmd/allmende/bootstrap_test.go @@ -27,3 +27,15 @@ func TestBootstrapRecordsKeepOnlyPublicAddresses(t *testing.T) { t.Fatalf("got %v\nwant %v", got, want) } } + +func TestAHostnameAddressIsPublishedAsItIs(t *testing.T) { + const id = "12D3KooWQYhTNQdmr3ArTeUHRYzFg94BKyTkoWBDWez9kSCVe2Xo" + got := bootstrapRecords([]string{ + "/dns4/node.example.org/tcp/4001/p2p/" + id, + "/dns4/localhost/tcp/4001/p2p/" + id, + }) + want := []string{"dnsaddr=/dns4/node.example.org/tcp/4001/p2p/" + id} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %v\nwant %v", got, want) + } +} diff --git a/cmd/allmende/run.go b/cmd/allmende/run.go index f98d174..59c2dee 100644 --- a/cmd/allmende/run.go +++ b/cmd/allmende/run.go @@ -44,6 +44,9 @@ func cmdRun(args []string) error { noDHT := fs.Bool("no-dht", false, "do not look for peers through the DHT") public := fs.Bool("public", false, "this node is reachable from the internet: serve the DHT and relay for nodes behind a NAT (for bootstrap nodes)") + var announceAddrs listFlag + fs.Var(&announceAddrs, "announce", + "address others should dial, when this node sits behind a router or in a container, e.g. /dns4/node.example.org/tcp/4001; repeatable") fs.Var(&listen, "listen", "libp2p listen multiaddr; repeatable (default: all interfaces, random ports)") httpAddr := fs.String("http", "127.0.0.1:8080", "address for the HTTP API") noMDNS := fs.Bool("no-mdns", false, "do not look for peers on the local network") @@ -121,6 +124,7 @@ func cmdRun(args []string) error { MDNS: !*noMDNS, DHT: !*noDHT, Public: *public, + Announce: announceAddrs, PeerCache: filepath.Join(*data, peersFile), Difficulty: *difficulty, Logger: log, diff --git a/internal/p2p/node.go b/internal/p2p/node.go index 9f1750c..e0d0a9d 100644 --- a/internal/p2p/node.go +++ b/internal/p2p/node.go @@ -31,6 +31,7 @@ import ( "github.com/libp2p/go-libp2p/p2p/discovery/mdns" drouting "github.com/libp2p/go-libp2p/p2p/discovery/routing" "github.com/libp2p/go-libp2p/p2p/host/autorelay" + ma "github.com/multiformats/go-multiaddr" madns "github.com/multiformats/go-multiaddr-dns" "git.stinnesbeck.com/nils/allmende/internal/identity" @@ -69,6 +70,11 @@ type Config struct { // address or a forwarded port). It then serves the DHT and acts as a relay // for nodes behind a NAT, which is what a bootstrap node does. Public bool + // Announce lists the addresses other nodes should dial, without /p2p/, + // e.g. /dns4/node.example.org/tcp/4001. A node behind a router or in a + // container does not know its public address; when this is set, only these + // addresses are announced. + Announce []string // PeerCache is a file in which the node remembers its peers between runs; // empty turns that off. PeerCache string @@ -167,6 +173,17 @@ func New(ctx context.Context, cfg Config) (*Node, error) { autorelay.WithMinCandidates(1), autorelay.WithNumRelays(2)), } + if len(cfg.Announce) > 0 { + announce := make([]ma.Multiaddr, 0, len(cfg.Announce)) + for _, a := range cfg.Announce { + m, err := ma.NewMultiaddr(a) + if err != nil { + return nil, fmt.Errorf("announce address %q: %w", a, err) + } + announce = append(announce, m) + } + opts = append(opts, libp2p.AddrsFactory(func([]ma.Multiaddr) []ma.Multiaddr { return announce })) + } if cfg.Public { opts = append(opts, libp2p.ForceReachabilityPublic(), libp2p.EnableRelayService(), libp2p.EnableNATService()) } diff --git a/internal/p2p/p2p_test.go b/internal/p2p/p2p_test.go index 1edf1a1..6fd8dab 100644 --- a/internal/p2p/p2p_test.go +++ b/internal/p2p/p2p_test.go @@ -7,6 +7,7 @@ import ( "io" "log/slog" "os" + "strings" "testing" "time" @@ -406,3 +407,34 @@ func TestANodeWithoutRegionsFollowsTheFirstOneWhenChosen(t *testing.T) { } eventually(t, "the first region is followed and caught up", func() bool { return count(b) == 1 }) } + +func TestAnnouncedAddressesReplaceTheLocalOnes(t *testing.T) { + const want = "/dns4/node.example.org/tcp/4001" + n := startNodeWith(t, nil, func(c *Config) { c.Announce = []string{want} }, "u1x") + addrs := n.Addrs() + if len(addrs) != 1 || !strings.HasPrefix(addrs[0], want+"/p2p/") { + t.Fatalf("a node behind a router announces only what it was told: %v", addrs) + } +} + +func TestABadAnnounceAddressIsRefused(t *testing.T) { + dev, _ := identity.Enroll(mustRoot(t), time.Now().Add(-time.Hour), 90*24*time.Hour) + s, err := store.Open(":memory:", store.Options{}) + if err != nil { + t.Fatal(err) + } + defer s.Close() + _, err = New(context.Background(), Config{Device: dev, Store: s, ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"}, Announce: []string{"not an address"}}) + if err == nil || !strings.Contains(err.Error(), "announce address") { + t.Fatalf("err = %v", err) + } +} + +func mustRoot(t *testing.T) *identity.Identity { + t.Helper() + root, _, err := identity.NewRoot() + if err != nil { + t.Fatal(err) + } + return root +} diff --git a/k8s/README.md b/k8s/README.md new file mode 100644 index 0000000..f5873bc --- /dev/null +++ b/k8s/README.md @@ -0,0 +1,90 @@ +# Running a public node on Kubernetes + +This runs one Allmende node as a **bootstrap node**: the address new nodes +use to find the network (`_dnsaddr.allmende.stinnesbeck.com`). It serves the +DHT and relays for nodes behind a NAT. It also works behind your home router. + +``` +k8s/base/ namespace, StatefulSet (+1 Gi volume), Services, config +k8s/base/ingress.yaml optional: the web UI on a public name (off by default) +k8s/overlays/nodeport/ variant for a cluster without a load balancer +``` + +## Does it work behind a router? + +Yes, with a port forward. A bootstrap node must be dialable from the internet, +so: + +1. **Forward port 4001, TCP and UDP**, on the router to the cluster (the + LoadBalancer address, or with the `nodeport` overlay a node's address on + port 30401). UDP matters: it carries QUIC, which most nodes prefer. +2. **Give the router's public IP a DNS name** (an A record, or dynamic DNS if + your IP changes) and put it in `base/config.env` as `PUBLIC_HOST`. + A node in a pod or behind a router cannot know its own public address, so + it announces that name (`--announce`) instead. Because the name, not an IP, + goes into the DNS records below, a changing IP only needs the A record + updated, not the `_dnsaddr` records. +3. If your provider puts you behind carrier-grade NAT (no real public IPv4), + forwarding cannot work. Use a small VPS instead, or IPv6 if your network + gives you a routable address. + +## Setup + +1. **Image.** Build it from the `Dockerfile` in the repository root, push it + to a registry the cluster can pull from, and set `images:` in + `base/kustomization.yaml`. + ``` + docker build -t registry.example.com/allmende:latest . && docker push registry.example.com/allmende:latest + ``` +2. **Name.** Edit `base/config.env` (`PUBLIC_HOST`, and `PUBLIC_PORT` if the + router cannot forward 4001 to 4001). +3. **Apply.** + ``` + kubectl apply -k k8s/base # with a LoadBalancer (MetalLB, kube-vip, ...) + kubectl apply -k k8s/overlays/nodeport # or: NodePort 30401, no load balancer + ``` + The pod starts and waits: it has no identity yet. +4. **Create the identity, once.** This shows the 12-word recovery phrase; it is + done by hand so the phrase never lands in a log. + ``` + kubectl -n allmende exec -it allmende-0 -- allmende init + ``` + Write the words down. The node starts by itself a few seconds later. Keys + and the database are on the volume (`data-allmende-0`): keep it, and back + it up if you can; the phrase can recover the identity (`allmende recover`) + but not the listings of other people. +5. **Publish the DNS records.** The node prints them at start: + ``` + kubectl -n allmende logs allmende-0 | grep dnsaddr= + ``` + Add each line as a TXT record at `_dnsaddr.allmende.stinnesbeck.com` (the + value is the whole `dnsaddr=...` text). Check: + ``` + dig +short TXT _dnsaddr.allmende.stinnesbeck.com + ``` +6. **Try it from outside your network** (a phone on mobile data, or a VPS): + ``` + allmende init && allmende run # no --bootstrap needed + ``` + Within a minute its status (`/api/v1/status`) should show a peer. + +## Good to know + +- **One replica only.** A second pod would be a second node with its own + identity, not a copy. +- **The sign-in link is in the log.** `allmende run` prints the owner sign-in + link, token included, to the terminal, which in Kubernetes is the pod log. + A bootstrap node does not need it; if your logs are shared, read the token + from `/data/admin.token` yourself and rotate it by recovering the identity + (`allmende recover`) if it was exposed. +- **The web UI** is not published by default. For a look at it: + `kubectl -n allmende port-forward svc/allmende-http 8080:8080`. To publish + it, enable `ingress.yaml` in `base/kustomization.yaml` (read its note first: + the same port serves the owner API). +- **Regions.** A bootstrap node follows none. To make it also keep listings, + open the UI through the port-forward, sign in and choose regions. +- **More than one bootstrap node** on different networks makes the network + independent of any single one. Run this on a second cluster or a VPS and add + its records next to the first. +- **Upgrades.** Build and push a new image tag, change `newTag`, apply again. + The pod restarts; peers reconnect on their own. diff --git a/k8s/base/config.env b/k8s/base/config.env new file mode 100644 index 0000000..28a3c52 --- /dev/null +++ b/k8s/base/config.env @@ -0,0 +1,8 @@ +# The public name of this node: a DNS name (A record, or a dynamic-DNS name) +# that points at your router's public IP. Nodes behind a router do not know +# their own public address, so the node announces this name instead. +PUBLIC_HOST=bootstrap.allmende.stinnesbeck.com + +# The port your router forwards to the cluster, as seen from the internet +# (TCP and UDP). Keep it 4001 unless the router cannot forward it. +PUBLIC_PORT=4001 diff --git a/k8s/base/ingress.yaml b/k8s/base/ingress.yaml new file mode 100644 index 0000000..f4626c8 --- /dev/null +++ b/k8s/base/ingress.yaml @@ -0,0 +1,30 @@ +# Optional: the web UI on a public name, so people can search without running +# their own node. Not part of the kustomization until you enable it there. +# +# The same port serves the owner API. It is protected by the admin token +# (which stays on the volume, /data/admin.token), but put TLS in front of it +# and consider limiting /api/v1/ to your own address ranges if you do not need +# the owner screens from outside. +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: allmende + annotations: + # cert-manager.io/cluster-issuer: letsencrypt + nginx.ingress.kubernetes.io/proxy-read-timeout: "60" +spec: + # ingressClassName: nginx + tls: + - hosts: [allmende.example.org] + secretName: allmende-tls + rules: + - host: allmende.example.org + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: allmende-http + port: + name: http diff --git a/k8s/base/kustomization.yaml b/k8s/base/kustomization.yaml new file mode 100644 index 0000000..fb62006 --- /dev/null +++ b/k8s/base/kustomization.yaml @@ -0,0 +1,36 @@ +# A public Allmende node (a bootstrap node) for your own cluster. +# +# kubectl apply -k k8s/base (or: kustomize build k8s/base | kubectl apply -f -) +# +# Before you apply: set the image below and the public name in config.env. +# See k8s/README.md for the whole setup (router, DNS, first start). +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization + +namespace: allmende + +resources: + - namespace.yaml + - statefulset.yaml + - service-p2p.yaml + - service-http.yaml + # Optional: the web UI on a public name. Read the note in ingress.yaml first. + # - ingress.yaml + +configMapGenerator: + - name: allmende-config + envs: + - config.env + +# Build the image from the Dockerfile in the repository root, push it to a +# registry your cluster can pull from, and name it here. +images: + - name: allmende + newName: registry.example.com/allmende + newTag: latest + +labels: + - pairs: + app.kubernetes.io/name: allmende + app.kubernetes.io/part-of: allmende + includeSelectors: false diff --git a/k8s/base/namespace.yaml b/k8s/base/namespace.yaml new file mode 100644 index 0000000..d15c53a --- /dev/null +++ b/k8s/base/namespace.yaml @@ -0,0 +1,4 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: allmende diff --git a/k8s/base/service-http.yaml b/k8s/base/service-http.yaml new file mode 100644 index 0000000..a656e81 --- /dev/null +++ b/k8s/base/service-http.yaml @@ -0,0 +1,15 @@ +# The web UI and API, inside the cluster only. Reach it with +# kubectl -n allmende port-forward svc/allmende-http 8080:8080 +# or publish it through ingress.yaml. +apiVersion: v1 +kind: Service +metadata: + name: allmende-http +spec: + type: ClusterIP + selector: + app: allmende + ports: + - name: http + port: 8080 + targetPort: http diff --git a/k8s/base/service-p2p.yaml b/k8s/base/service-p2p.yaml new file mode 100644 index 0000000..2f018eb --- /dev/null +++ b/k8s/base/service-p2p.yaml @@ -0,0 +1,28 @@ +# The libp2p port other nodes connect to, TCP and UDP (QUIC), on one address. +# +# Your router forwards 4001 (TCP and UDP) to this Service's address. This file +# uses a LoadBalancer, which at home usually means MetalLB or kube-vip handing +# out a LAN address; forward the router's port to that address. Without a load +# balancer in the cluster use overlays/nodeport instead. +# +# Mixed TCP and UDP on one LoadBalancer needs Kubernetes 1.26 or later and a +# load balancer implementation that supports it (MetalLB does). +apiVersion: v1 +kind: Service +metadata: + name: allmende-p2p +spec: + type: LoadBalancer + # Keep the real client address (and skip a second hop through the cluster). + externalTrafficPolicy: Local + selector: + app: allmende + ports: + - name: p2p-tcp + port: 4001 + targetPort: p2p-tcp + protocol: TCP + - name: p2p-quic + port: 4001 + targetPort: p2p-quic + protocol: UDP diff --git a/k8s/base/statefulset.yaml b/k8s/base/statefulset.yaml new file mode 100644 index 0000000..4331950 --- /dev/null +++ b/k8s/base/statefulset.yaml @@ -0,0 +1,117 @@ +# One node, with its keys and database on a volume. Keep it at one replica: a +# second pod would be a second node with its own identity, not a copy. +# +# The identity is created by hand, once, because it shows a recovery phrase +# that must never end up in a log. Until you do, the pod waits: +# kubectl -n allmende exec -it allmende-0 -- allmende init +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: allmende +spec: + serviceName: allmende-p2p + replicas: 1 + selector: + matchLabels: + app: allmende + template: + metadata: + labels: + app: allmende + spec: + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + fsGroup: 10001 + seccompProfile: + type: RuntimeDefault + terminationGracePeriodSeconds: 30 + containers: + - name: allmende + image: allmende + imagePullPolicy: IfNotPresent + # Wait for 'allmende init' (it writes admin.token last), then run as a + # bootstrap node: --public serves the DHT and relays for nodes behind + # a NAT, --announce names the address the router forwards. + command: ["/bin/sh", "-c"] + args: + - | + until [ -f /data/admin.token ]; do + echo "not set up yet: run kubectl -n allmende exec -it allmende-0 -- allmende init" + sleep 10 + done + exec allmende run \ + --public \ + --no-default-bootstrap \ + --no-mdns \ + --http 0.0.0.0:8080 \ + --listen /ip4/0.0.0.0/tcp/4001 \ + --listen /ip4/0.0.0.0/udp/4001/quic-v1 \ + --announce "/dns4/${PUBLIC_HOST}/tcp/${PUBLIC_PORT}" \ + --announce "/dns4/${PUBLIC_HOST}/udp/${PUBLIC_PORT}/quic-v1" + envFrom: + - configMapRef: + name: allmende-config + env: + - name: ALLMENDE_DATA + value: /data + ports: + - name: p2p-tcp + containerPort: 4001 + protocol: TCP + - name: p2p-quic + containerPort: 4001 + protocol: UDP + - name: http + containerPort: 8080 + protocol: TCP + # Ready once the node answers; before 'init' it never does, which keeps + # a half-set-up node out of the Services without restarting it. + readinessProbe: + httpGet: + path: /api/v1/status + port: http + periodSeconds: 10 + # Only judge it dead after the first start succeeded (the wait for + # 'init' may take as long as you need). + startupProbe: + httpGet: + path: /api/v1/status + port: http + periodSeconds: 10 + failureThreshold: 360 + livenessProbe: + httpGet: + path: /api/v1/status + port: http + periodSeconds: 30 + failureThreshold: 3 + resources: + requests: + cpu: 50m + memory: 128Mi + limits: + memory: 512Mi + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + volumeMounts: + - name: data + mountPath: /data + - name: tmp # the root file system is read-only; SQLite wants a scratch place + mountPath: /tmp + volumes: + - name: tmp + emptyDir: {} + volumeClaimTemplates: + - metadata: + name: data + spec: + accessModes: ["ReadWriteOnce"] + # storageClassName: your-class # the cluster default is used otherwise + resources: + requests: + storage: 1Gi diff --git a/k8s/overlays/nodeport/kustomization.yaml b/k8s/overlays/nodeport/kustomization.yaml new file mode 100644 index 0000000..96baf9c --- /dev/null +++ b/k8s/overlays/nodeport/kustomization.yaml @@ -0,0 +1,13 @@ +# For a cluster without a load balancer: publish the libp2p port on every node +# as NodePort 30401 (TCP and UDP) and forward the router's port 4001 to the LAN +# address of a node, port 30401. +# +# kubectl apply -k k8s/overlays/nodeport (instead of k8s/base) +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization + +resources: + - ../../base + +patches: + - path: service-p2p.yaml diff --git a/k8s/overlays/nodeport/service-p2p.yaml b/k8s/overlays/nodeport/service-p2p.yaml new file mode 100644 index 0000000..933bdc3 --- /dev/null +++ b/k8s/overlays/nodeport/service-p2p.yaml @@ -0,0 +1,20 @@ +apiVersion: v1 +kind: Service +metadata: + name: allmende-p2p +spec: + type: NodePort + # NodePort traffic that lands on another node is forwarded, so the port also + # works when the router points at a node that is not running the pod. + externalTrafficPolicy: Cluster + ports: + - name: p2p-tcp + port: 4001 + targetPort: p2p-tcp + protocol: TCP + nodePort: 30401 + - name: p2p-quic + port: 4001 + targetPort: p2p-quic + protocol: UDP + nodePort: 30401