SPB Git

Repository Public

agents.go 4.8 KB 133 lines go

1package main23import (4	"context"5	"encoding/json"6	"flag"7	"fmt"8	"regexp"9	"strings"10	"time"1112	"github.com/google/uuid"13	"github.com/jackc/pgx/v5/pgxpool"1415	"clustr.spboucher.ai/mcc/internal/audit"16	"clustr.spboucher.ai/mcc/internal/config"17	"clustr.spboucher.ai/mcc/internal/ids"18	"clustr.spboucher.ai/mcc/internal/secret"19)2021func init() {22	extraCommands["enroll-token"] = cmdEnrollToken23	extraCommands["register-node"] = cmdRegisterNode24}2526var aliasRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,62}$`)2728// cmdEnrollToken issues a single-use agent enrollment token from the host29// (same rules as the API: hash stored, short lifetime). Used for the first30// agents, before any administrator account exists, and for scripted rollouts.31func cmdEnrollToken(ctx context.Context, cfg *config.Config, pool *pgxpool.Pool, args []string) error {32	fs := flag.NewFlagSet("enroll-token", flag.ExitOnError)33	alias := fs.String("alias", "", "node alias the token enrolls")34	kind := fs.String("kind", "mac", "mac | linux")35	ttl := fs.Duration("ttl", 15*time.Minute, "lifetime (max 1h)")36	quiet := fs.Bool("quiet", false, "print only: <token> <ca-fingerprint>")37	fs.Parse(args)38	if !aliasRE.MatchString(*alias) {39		return fmt.Errorf("--alias is required (letters, digits, . _ -)")40	}41	if *kind != "mac" && *kind != "linux" {42		return fmt.Errorf("--kind must be mac or linux")43	}44	if *ttl < time.Minute || *ttl > time.Hour {45		return fmt.Errorf("--ttl must be between 1m and 1h")46	}47	var raw []byte48	if err := pool.QueryRow(ctx, `select value from settings where key='pki.ca'`).Scan(&raw); err != nil {49		return fmt.Errorf("the agent CA is not published yet (is telemetry-ingest running?): %w", err)50	}51	var ca struct {52		Fingerprint string `json:"fingerprint"`53	}54	if json.Unmarshal(raw, &ca) != nil || ca.Fingerprint == "" {55		return fmt.Errorf("the agent CA record is unreadable")56	}57	fp := ca.Fingerprint58	if !strings.HasPrefix(fp, "sha256:") {59		fp = "sha256:" + fp60	}61	token, hash := secret.NewToken()62	id := ids.New()63	tx, err := pool.Begin(ctx)64	if err != nil {65		return err66	}67	defer tx.Rollback(ctx)68	if _, err := tx.Exec(ctx, `insert into agent_enrollment_tokens(id, token_hash, node_alias, node_kind, expires_at) values ($1,$2,$3,$4::node_kind, now() + $5::interval)`,69		id, hash, *alias, *kind, ttl.String()); err != nil {70		return err71	}72	if _, err := audit.Append(ctx, tx, audit.Entry{ActorKind: "cli", ActorLabel: "mccctl", Action: "agent.enrollment_token.create", TargetKind: "enrollment_token",73		TargetID: id.String(), Outcome: audit.Success, CorrelationID: uuid.New(), Params: map[string]any{"node_alias": *alias, "node_kind": *kind, "ttl_s": int(ttl.Seconds())}}); err != nil {74		return err75	}76	if err := tx.Commit(ctx); err != nil {77		return err78	}79	endpoints := strings.Join(cfg.IngestAdvertise, ",")80	if *quiet {81		fmt.Println(token, fp)82		return nil83	}84	fmt.Printf("Enrollment token for %q (%s), single use, valid %s:\n\n  mcc-agent enroll --endpoints %s --token %s --ca-fingerprint %s\n\n", *alias, *kind, *ttl, endpoints, token, fp)85	return nil86}8788// cmdRegisterNode records a machine that exists but has no agent yet (for89// example a laptop that is currently off). It appears as offline / never seen90// with no hardware facts until its agent enrolls under the same alias.91func cmdRegisterNode(ctx context.Context, _ *config.Config, pool *pgxpool.Pool, args []string) error {92	fs := flag.NewFlagSet("register-node", flag.ExitOnError)93	alias := fs.String("alias", "", "node alias")94	kind := fs.String("kind", "mac", "mac | linux | nas")95	site := fs.String("site", "default", "site")96	role := fs.String("role", "worker", "role")97	tags := fs.String("tags", "", "comma-separated tags")98	fs.Parse(args)99	if !aliasRE.MatchString(*alias) {100		return fmt.Errorf("--alias is required")101	}102	var tagList []string103	for _, t := range strings.Split(*tags, ",") {104		if t = strings.TrimSpace(t); t != "" {105			tagList = append(tagList, t)106		}107	}108	id := ids.New()109	tx, err := pool.Begin(ctx)110	if err != nil {111		return err112	}113	defer tx.Rollback(ctx)114	tag, err := tx.Exec(ctx, `insert into nodes(id, alias, kind, site, role, tags, registered_via) values ($1,$2,$3::node_kind,$4,$5,$6,'manual') on conflict (alias) do nothing`,115		id, *alias, *kind, *site, *role, tagList)116	if err != nil {117		return err118	}119	if tag.RowsAffected() == 0 {120		fmt.Printf("node %q already exists — unchanged\n", *alias)121		return nil122	}123	if _, err := audit.Append(ctx, tx, audit.Entry{ActorKind: "cli", ActorLabel: "mccctl", Action: "node.register", TargetKind: "node", TargetID: id.String(),124		Outcome: audit.Success, CorrelationID: uuid.New(), Params: map[string]any{"alias": *alias, "kind": *kind, "site": *site, "role": *role}}); err != nil {125		return err126	}127	if err := tx.Commit(ctx); err != nil {128		return err129	}130	fmt.Printf("registered %q (%s) — offline until its agent enrolls\n", *alias, *kind)131	return nil132}133
Files main
Menu

Theme