1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
package nodeagent
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/childproc"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/clock"
"github.com/johnandersen777/socialweb-computer-kcp/internal/nodemarket"
"github.com/johnandersen777/socialweb-computer-kcp/internal/systemdunit"
"github.com/johnandersen777/socialweb-computer-kcp/internal/systemdunit/notify"
"github.com/johnandersen777/socialweb-computer-kcp/internal/vault/openbao"
)
const openBaoLinkName = "openbao"
const apiserverLinkName = "apiserver"
type claimDocument struct {
Node string `json:"node"`
JWTMount string `json:"jwtMount"`
Role string `json:"role"`
Audience string `json:"audience"`
KVMount string `json:"kvMount"`
KVPath string `json:"kvPath"`
}
func LoadConfig(path string) (Config, error) {
if path == "" {
return Config{}, errors.New("nodeagent: no config path was given")
}
raw, err := os.ReadFile(path)
if err != nil {
return Config{}, fmt.Errorf("nodeagent: reading %s: %w", path, err)
}
var cfg Config
if err := json.Unmarshal(raw, &cfg); err != nil {
return Config{}, fmt.Errorf("nodeagent: %s is not a join config: %w", path, err)
}
cfg = cfg.WithDefaults()
cfg.ConfigPath = path
if err := cfg.Validate(); err != nil {
return Config{}, err
}
return cfg, nil
}
func Join(ctx context.Context, cfg Config, log *slog.Logger) error {
if log == nil {
log = slog.Default()
}
cfg = cfg.WithDefaults()
if err := cfg.Validate(); err != nil {
return err
}
if !executable(cfg.DumbpipePath) {
return fmt.Errorf("nodeagent: %s is not installed", cfg.DumbpipePath)
}
if _, err := openBaoLinkArgs(cfg); err != nil {
return err
}
runCtx, cancel := context.WithCancel(ctx)
defer cancel()
var wg sync.WaitGroup
wg.Go(func() {
superviseLink(runCtx, cfg, openBaoLinkName, log)
})
if err := prepare(runCtx, cfg, log); err != nil {
cancel()
wg.Wait()
return err
}
if _, err := apiserverLinkArgs(ctx, cfg); err != nil {
cancel()
wg.Wait()
return err
}
wg.Go(func() {
superviseLink(runCtx, cfg, apiserverLinkName, log)
})
if err := notify.Ready("joined the cluster; supervising the OpenBao and apiserver links"); err != nil {
log.Warn("sd_notify READY failed", "err", err.Error())
}
log.Info("the join is complete; the links run under this service", "config", cfg.ConfigPath)
<-ctx.Done()
cancel()
wg.Wait()
return nil
}
func prepare(ctx context.Context, cfg Config, log *slog.Logger) error {
if fileNonEmpty(cfg.DoneStamp) && fileNonEmpty(cfg.APIServerEnvPath) && fileNonEmpty(cfg.MeshdEnvPath) {
log.Info("the join secrets were already fetched; keeping them and starting the links",
"stamp", cfg.DoneStamp)
return nil
}
for _, path := range []string{cfg.ClaimDocPath, cfg.ClaimCAPath} {
if !fileNonEmpty(path) {
return fmt.Errorf("nodeagent: %s is missing", path)
}
}
raw, err := os.ReadFile(cfg.ClaimDocPath)
if err != nil {
return fmt.Errorf("nodeagent: reading %s: %w", cfg.ClaimDocPath, err)
}
var doc claimDocument
if err := json.Unmarshal(raw, &doc); err != nil {
return fmt.Errorf("nodeagent: %s is not a claim document: %w", cfg.ClaimDocPath, err)
}
for name, value := range map[string]string{
"node": doc.Node, "jwtMount": doc.JWTMount, "role": doc.Role,
"kvMount": doc.KVMount, "kvPath": doc.KVPath,
} {
if value == "" {
return fmt.Errorf("nodeagent: %s carries no %s", cfg.ClaimDocPath, name)
}
if !validName(value) {
return fmt.Errorf("nodeagent: %s carries an unsafe name for %s: %q", cfg.ClaimDocPath, name, value)
}
}
if doc.Audience == "" {
return fmt.Errorf("nodeagent: %s carries no audience", cfg.ClaimDocPath)
}
exchanged, err := exchangeWorkloadToken(ctx, cfg, doc.Audience, log)
if err != nil {
return err
}
caPEM, err := os.ReadFile(cfg.ClaimCAPath)
if err != nil {
return fmt.Errorf("nodeagent: reading %s: %w", cfg.ClaimCAPath, err)
}
pool, err := openbao.CertPoolFromPEM(caPEM)
if err != nil {
return fmt.Errorf("nodeagent: %s: %w", cfg.ClaimCAPath, err)
}
client := openbao.New("https://"+cfg.OpenBaoLinkAddress, "", openbao.WithCACertPool(pool))
logged, err := loginOpenBao(ctx, cfg, client, doc, exchanged, log)
if err != nil {
return err
}
data, err := readNodeKV(ctx, cfg, logged, doc, log)
if err != nil {
return err
}
token, ok := firstValue(data, "token")
if !ok {
return fmt.Errorf("nodeagent: %s/%s has no token", doc.KVMount, doc.KVPath)
}
nodePassword, ok := firstValue(data, "nodePassword")
if !ok {
return fmt.Errorf("nodeagent: %s/%s has no nodePassword", doc.KVMount, doc.KVPath)
}
serverCA, ok := firstValue(data, "serverCA")
if !ok {
return fmt.Errorf("nodeagent: %s/%s has no serverCA", doc.KVMount, doc.KVPath)
}
address, port, ticket := "", "", ""
fromBundle := fileNonEmpty(cfg.APIServerEnvPath)
if fromBundle {
env, err := readEnvFile(cfg.APIServerEnvPath)
if err != nil {
return fmt.Errorf("nodeagent: reading %s: %w", cfg.APIServerEnvPath, err)
}
if env["NODE_NAME"] != doc.Node {
return fmt.Errorf("nodeagent: the bundled apiserver link names %q, not %q", env["NODE_NAME"], doc.Node)
}
address, port, ticket = env["ADVERTISE_ADDRESS"], env["APISERVER_PORT"], env["APISERVER_TICKET"]
log.Info("the apiserver link came with the bundle", "path", cfg.APIServerEnvPath)
} else {
for _, key := range []string{"apiserverTicket", "advertiseAddress", "apiserverPort"} {
if _, ok := firstValue(data, key); !ok {
return fmt.Errorf("nodeagent: %s/%s has no %s", doc.KVMount, doc.KVPath, key)
}
}
address, _ = firstValue(data, "advertiseAddress")
port, _ = firstValue(data, "apiserverPort")
ticket, _ = firstValue(data, "apiserverTicket")
}
if err := guardLinkEnv(address, port, ticket); err != nil {
return err
}
joinToken := stripSpace(token)
if !strings.HasPrefix(joinToken, "K10") {
joinToken = nodemarket.PinnedJoinToken(serverCA, joinToken)
}
for _, dir := range []string{cfg.NodeDir, filepath.Dir(cfg.K3sNodePasswordPath)} {
if err := ensureDir(dir, 0o700); err != nil {
return fmt.Errorf("nodeagent: creating %s: %w", dir, err)
}
}
if err := writeAtomic(cfg.ServerCAPath, []byte(serverCA), 0o600); err != nil {
return err
}
if err := writeAtomic(cfg.TokenPath, []byte(joinToken), 0o600); err != nil {
return err
}
password := strings.ReplaceAll(nodePassword, "\n", "")
if err := writeAtomic(cfg.NodePasswordPath, []byte(password), 0o600); err != nil {
return err
}
if err := writeAtomic(cfg.K3sNodePasswordPath, []byte(password), 0o600); err != nil {
return err
}
if !fromBundle {
env := fmt.Sprintf("NODE_NAME=%s\nADVERTISE_ADDRESS=%s\nAPISERVER_PORT=%s\nAPISERVER_TICKET=%s\n",
doc.Node, address, port, ticket)
if err := writeAtomic(cfg.APIServerEnvPath, []byte(env), 0o600); err != nil {
return err
}
}
meshdEnv := fmt.Sprintf("SOCIALWEB_MESHD_NODE_NAME=%s\nSOCIALWEB_MESHD_KUBECONFIG=%s\n", doc.Node, cfg.KubeletKubeconfig)
if err := writeAtomic(cfg.MeshdEnvPath, []byte(meshdEnv), 0o600); err != nil {
return err
}
if err := writeAtomic(cfg.DoneStamp, nil, 0o600); err != nil {
return err
}
log.Info("fetched the join secrets", "node", doc.Node, "kv", doc.KVMount+"/"+doc.KVPath)
return nil
}
func exchangeWorkloadToken(ctx context.Context, cfg Config, audience string, log *slog.Logger) (string, error) {
waited := 0
for !executable(cfg.GuestLoginHelperPath) {
if waited >= cfg.GuestLoginWaitAttempts {
return "", fmt.Errorf("nodeagent: the guest login helper %s never appeared", cfg.GuestLoginHelperPath)
}
waited++
log.Info("waiting for the guest login helper", "path", cfg.GuestLoginHelperPath,
"attempt", waited, "of", cfg.GuestLoginWaitAttempts)
if err := clock.SleepErr(ctx, cfg.GuestLoginWaitInterval()); err != nil {
return "", err
}
}
out, err := run(ctx, cfg.GuestLoginHelperPath, "token", audience)
if err != nil {
return "", fmt.Errorf("nodeagent: exchanging the workload identity token for %s: %w", audience, err)
}
token := strings.TrimSpace(string(out))
if token == "" {
return "", fmt.Errorf("nodeagent: no workload identity token from the bidder's OpenBao for %s", audience)
}
return token, nil
}
func loginOpenBao(ctx context.Context, cfg Config, client *openbao.Client, doc claimDocument, exchanged string, log *slog.Logger) (*openbao.Client, error) {
for attempt := 1; attempt <= cfg.LinkWaitAttempts; attempt++ {
logged, err := client.LoginJWT(ctx, doc.JWTMount, doc.Role, exchanged)
if err == nil {
log.Info("logged in to the cluster OpenBao", "mount", doc.JWTMount, "role", doc.Role)
return logged, nil
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
log.Info("the OpenBao link has not answered yet", "address", cfg.OpenBaoLinkAddress,
"attempt", attempt, "of", cfg.LinkWaitAttempts, "err", errString(err))
if err := clock.SleepErr(ctx, cfg.LinkWaitInterval()); err != nil {
return nil, err
}
}
return nil, fmt.Errorf("nodeagent: OpenBao login at auth/%s as %s failed after %d attempts at the link on %s",
doc.JWTMount, doc.Role, cfg.LinkWaitAttempts, cfg.OpenBaoLinkAddress)
}
func readNodeKV(ctx context.Context, cfg Config, client *openbao.Client, doc claimDocument, log *slog.Logger) (map[string]any, error) {
path := strings.Trim(doc.KVMount, "/") + "/data/" + strings.Trim(doc.KVPath, "/")
for attempt := 1; attempt <= cfg.LinkWaitAttempts; attempt++ {
response, err := client.Read(ctx, path)
if err == nil {
data, dataErr := kvData(response)
if dataErr == nil {
return data, nil
}
err = dataErr
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
log.Info("the OpenBao link has not answered with the node secrets yet", "address", cfg.OpenBaoLinkAddress,
"attempt", attempt, "of", cfg.LinkWaitAttempts, "err", errString(err))
if err := clock.SleepErr(ctx, cfg.LinkWaitInterval()); err != nil {
return nil, err
}
}
return nil, fmt.Errorf("nodeagent: reading %s/%s failed after %d attempts at the link on %s",
doc.KVMount, doc.KVPath, cfg.LinkWaitAttempts, cfg.OpenBaoLinkAddress)
}
func kvData(response map[string]any) (map[string]any, error) {
envelope, ok := response["data"].(map[string]any)
if !ok {
return nil, errors.New("the response carries no data object")
}
if data, ok := envelope["data"].(map[string]any); ok {
return data, nil
}
return envelope, nil
}
func openBaoLinkArgs(cfg Config) ([]string, error) {
raw, err := os.ReadFile(cfg.OpenBaoTicketPath)
if err != nil {
return nil, fmt.Errorf("nodeagent: reading the OpenBao ticket %s: %w", cfg.OpenBaoTicketPath, err)
}
ticket := strings.TrimSpace(string(raw))
if ticket == "" {
return nil, fmt.Errorf("nodeagent: the OpenBao ticket %s is empty", cfg.OpenBaoTicketPath)
}
return []string{"connect-tcp", "--addr", cfg.OpenBaoLinkAddress, ticket}, nil
}
func apiserverLinkArgs(ctx context.Context, cfg Config) ([]string, error) {
env, err := readEnvFile(cfg.APIServerEnvPath)
if err != nil {
return nil, fmt.Errorf("nodeagent: reading %s: %w", cfg.APIServerEnvPath, err)
}
address, port, ticket := env["ADVERTISE_ADDRESS"], env["APISERVER_PORT"], env["APISERVER_TICKET"]
if err := guardLinkEnv(address, port, ticket); err != nil {
return nil, err
}
if err := ensureLoopbackAlias(ctx, address); err != nil {
return nil, err
}
return []string{"connect-tcp", "--addr", address + ":" + port, ticket}, nil
}
func guardLinkEnv(address, port, ticket string) error {
if !validIPv4(address) {
return errors.New("nodeagent: advertiseAddress is not an IPv4 address")
}
if !validPort(port) {
return errors.New("nodeagent: apiserverPort is not a port")
}
if !validTicket(ticket) {
return errors.New("nodeagent: apiserverTicket is not a ticket")
}
return nil
}
func ensureLoopbackAlias(ctx context.Context, address string) error {
iface, err := net.InterfaceByName("lo")
if err == nil {
addrs, err := iface.Addrs()
if err == nil {
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip != nil && ip.String() == address {
return nil
}
}
}
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
if _, err := run(ctx, "ip", "addr", "add", address+"/32", "dev", "lo"); err != nil {
return fmt.Errorf("nodeagent: adding %s/32 to lo: %w", address, err)
}
return nil
}
func superviseLink(ctx context.Context, cfg Config, name string, log *slog.Logger) {
backoff := systemdunit.Backoff{Min: time.Second, Max: 30 * time.Second}
for {
if ctx.Err() != nil {
return
}
var args []string
var err error
switch name {
case openBaoLinkName:
args, err = openBaoLinkArgs(cfg)
case apiserverLinkName:
args, err = apiserverLinkArgs(ctx, cfg)
default:
err = fmt.Errorf("nodeagent: unknown link %s", name)
}
if err != nil {
log.Error("the link cannot start", "link", name, "err", err.Error())
if clock.SleepErr(ctx, backoff.Next()) != nil {
return
}
continue
}
cmd := exec.CommandContext(ctx, cfg.DumbpipePath, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = childproc.FilterSecrets(os.Stderr)
started := time.Now()
err = cmd.Run()
if ctx.Err() != nil {
return
}
if time.Since(started) > time.Minute {
backoff.Reset()
}
delay := backoff.Next()
log.Warn("the link child exited; restarting it", "link", name, "err", errString(err), "after", delay.String())
if clock.SleepErr(ctx, delay) != nil {
return
}
}
}
func errString(err error) string {
if err == nil {
return ""
}
return err.Error()
}