Monorepo for Tangled
tangled.org
1package keys
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "os"
8 "strings"
9
10 "github.com/urfave/cli/v3"
11 "tangled.org/core/knot2/config"
12 "tangled.org/core/knot2/db"
13 "tangled.org/core/log"
14)
15
16func Command() *cli.Command {
17 return &cli.Command{
18 Name: "keys",
19 Usage: "fetch public keys from the knot server",
20 Action: Run,
21 Flags: []cli.Flag{
22 &cli.StringFlag{
23 Name: "config",
24 Aliases: []string{"c"},
25 Usage: "config path",
26 Required: true,
27 },
28 &cli.StringFlag{
29 Name: "output",
30 Aliases: []string{"o"},
31 Usage: "output format (table, json, authorized-keys)",
32 Value: "table",
33 },
34 },
35 }
36}
37
38func Run(ctx context.Context, cmd *cli.Command) error {
39 l := log.FromContext(ctx)
40 l = log.SubLogger(l, cmd.Name)
41 ctx = log.IntoContext(ctx, l)
42
43 var (
44 output = cmd.String("output")
45 configPath = cmd.String("config")
46 )
47
48 cfg, err := config.Load(ctx, configPath)
49 if err != nil {
50 return fmt.Errorf("failed to load config: %w", err)
51 }
52
53 d, err := db.New(cfg.DbPath())
54 if err != nil {
55 return fmt.Errorf("failed to load db: %w", err)
56 }
57
58 pubkeyDidListMap, err := db.GetPubkeyDidListMap(d)
59 if err != nil {
60 return err
61 }
62
63 switch output {
64 case "json":
65 prettyJSON, err := json.MarshalIndent(pubkeyDidListMap, "", " ")
66 if err != nil {
67 return err
68 }
69 if _, err := os.Stdout.Write(prettyJSON); err != nil {
70 return err
71 }
72 case "table":
73 fmt.Printf("%-40s %-40s\n", "KEY", "DID")
74 fmt.Println(strings.Repeat("-", 80))
75
76 for key, didList := range pubkeyDidListMap {
77 fmt.Printf("%-40s %-40s\n", key, strings.Join(didList, ","))
78 }
79 case "authorized-keys":
80 for key, didList := range pubkeyDidListMap {
81 executablePath, err := os.Executable()
82 if err != nil {
83 l.Error("error getting path of executable", "error", err)
84 return err
85 }
86 command := fmt.Sprintf("%s guard", executablePath)
87 for _, did := range didList {
88 command += fmt.Sprintf(" -user %s", did)
89 }
90 fmt.Printf(
91 `command="%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s`+"\n",
92 command,
93 key,
94 )
95 }
96 if err != nil {
97 l.Error("error writing to stdout", "error", err)
98 return err
99 }
100 }
101
102 return nil
103}