~whereswaldon/forest-go

ref: 972f2afc043771da05b4e13bd7386f39f7f5e125 forest-go/cmd/forest/main.go -rw-r--r-- 11.8 KiB
972f2afcChris Waldon fix: ensure archive DescendantsOf does not return the root 3 months ago
                                                                                
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
package main

import (
	"encoding"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"

	forest "git.sr.ht/~whereswaldon/forest-go"
	"git.sr.ht/~whereswaldon/forest-go/fields"
	"git.sr.ht/~whereswaldon/forest-go/twig"
	"golang.org/x/crypto/openpgp"
	"golang.org/x/crypto/openpgp/packet"
)

const (
	usageError = 1

	commandIdentity  = "identity"
	commandCommunity = "community"
	commandReply     = "reply"

	commandShow   = "show"
	commandCreate = "create"
)

func main() {
	flag.Usage = func() {
		fmt.Fprintln(os.Stderr, `forest

A CLI for manipulating nodes in the arbor forest.

Subcommands:

`+commandCreate+" ("+commandIdentity+"|"+commandCommunity+"|"+commandReply+`)
show <node-id>
`)
		flag.PrintDefaults()
		os.Exit(usageError)
	}
	if len(os.Args) < 2 {
		flag.Usage()
	}

	var cmdHandler handler
	switch os.Args[1] {
	case commandCreate:
		cmdHandler = create
	case commandShow:
		cmdHandler = show
	default:
		flag.Usage()
	}
	if err := cmdHandler(os.Args[2:]); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
}

type handler func(args []string) error

func show(args []string) error {
	flags := flag.NewFlagSet(commandShow, flag.ExitOnError)
	usage := func() {
		flags.PrintDefaults()
		os.Exit(usageError)
	}
	err := flags.Parse(args)
	if err != nil {
		return err
	}
	if len(flags.Args()) < 1 {
		usage()
	}
	return showNode(args, commandShow, forest.UnmarshalBinaryNode)
}

func create(args []string) error {
	flags := flag.NewFlagSet(commandCreate, flag.ExitOnError)
	usage := func() {
		flags.PrintDefaults()
		os.Exit(usageError)
	}
	err := flags.Parse(args)
	if err != nil {
		return err
	}
	if len(flags.Args()) < 1 {
		usage()
	}
	var cmdHandler handler
	switch flags.Arg(0) {
	case commandIdentity:
		cmdHandler = createIdentity
	case commandCommunity:
		cmdHandler = createCommunity
	case commandReply:
		cmdHandler = createReply
	default:
		usage()
	}
	if err := cmdHandler(flags.Args()[1:]); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
	return nil
}

type Metadata struct {
	Version uint   `json:"version" `
	Data    string `json:"data" `
}

func decodeMetadata(input string) ([]byte, error) {

	var metadata map[string]string
	err := json.Unmarshal([]byte(input), &metadata)
	if err != nil {
		return nil, fmt.Errorf("Error unmarshalling metadata: %v", err)
	}

	var twigData = twig.New()

	for k, d := range metadata {
		key, err := twig.FromString(k)
		if err != nil {
			return nil, fmt.Errorf("Error parsing twig key: %w", err)
		}

		twigData.Values[key] = []byte(d)
	}

	mdBlob, err := twigData.MarshalBinary()
	if err != nil {
		return nil, fmt.Errorf("Error marshalling data to binary: %v", err)
	}

	return mdBlob, nil
}

func createIdentity(args []string) error {
	var (
		name, keyfile, gpguser, metadata string
	)
	flags := flag.NewFlagSet(commandCreate+" "+commandIdentity, flag.ExitOnError)
	flags.StringVar(&name, "name", "forest", "username for the identity node")
	flags.StringVar(&keyfile, "key", "arbor.privkey", "the openpgp private key for the identity node")
	flags.StringVar(&gpguser, "gpguser", "", "gpg2 user whose private key should be used to create this node. Supercedes -key.")
	flags.StringVar(&metadata, "metadata", "{}", "Twig metadata fields for the node: {\"<key>/<version>\": \"data\",...}")

	usage := func() {
		flags.PrintDefaults()
	}
	if err := flags.Parse(args); err != nil {
		usage()
		return fmt.Errorf("Error parsing arguments: %v", err)
	}
	signer, err := getSigner(gpguser, keyfile)
	if err != nil {
		return fmt.Errorf("Error getting signer: %v", err)
	}

	metadataRaw, err := decodeMetadata(metadata)
	if err != nil {
		return fmt.Errorf("Error decoding metadata: %v", err)
	}

	identity, err := forest.NewIdentity(signer, name, metadataRaw)
	if err != nil {
		return fmt.Errorf("Error creating identity: %v", err)
	}

	fname, err := identity.ID().MarshalString()
	if err != nil {
		return fmt.Errorf("Error marshalling identity: %v", err)
	}

	if err := saveAs(fname, identity); err != nil {
		return fmt.Errorf("Error saving identity: %v", err)
	}

	fmt.Println(fname)

	return nil
}

func createCommunity(args []string) error {
	var (
		name, keyfile, identity, gpguser, metadata string
	)
	flags := flag.NewFlagSet(commandCreate+" "+commandCommunity, flag.ExitOnError)
	flags.StringVar(&name, "name", "forest", "username for the community node")
	flags.StringVar(&keyfile, "key", "arbor.privkey", "the openpgp private key for the signing identity node")
	flags.StringVar(&identity, "as", "", "[required] the id of the signing identity node")
	flags.StringVar(&gpguser, "gpguser", "", "gpg2 user whose private key should be used to create this node. Supercedes -key.")
	flags.StringVar(&metadata, "metadata", "{}", "Twig metadata fields for the node: {\"<key>/<version>\": \"data\",...}")
	usage := func() {
		flags.PrintDefaults()
	}
	if err := flags.Parse(args); err != nil {
		usage()
		return fmt.Errorf("Error parsing arguments: %v", err)
	}
	signer, err := getSigner(gpguser, keyfile)
	if err != nil {
		return fmt.Errorf("Error getting signer: %v", err)
	}
	idNode, err := getIdentity(identity)
	if err != nil {
		return fmt.Errorf("Error gettig identity: %v", err)
	}
	metadataRaw, err := decodeMetadata(metadata)
	if err != nil {
		return fmt.Errorf("Error decoding metadata: %v", err)
	}

	community, err := forest.As(idNode, signer).NewCommunity(name, metadataRaw)
	if err != nil {
		return fmt.Errorf("Error creating community: %v", err)
	}

	fname, err := community.ID().MarshalString()
	if err != nil {
		return fmt.Errorf("Error marshalling community: %v", err)
	}

	if err := saveAs(fname, community); err != nil {
		return fmt.Errorf("Error saving community: %v", err)
	}

	fmt.Println(fname)

	return nil
}

func createReply(args []string) error {
	var (
		content, parent, keyfile, identity, gpguser, metadata string
	)
	flags := flag.NewFlagSet(commandCreate+" "+commandReply, flag.ExitOnError)
	flags.StringVar(&keyfile, "key", "arbor.privkey", "the openpgp private key for the signing identity node")
	flags.StringVar(&gpguser, "gpguser", "", "gpg2 user whose private key should be used to create this node. Supercedes -key.")
	flags.StringVar(&identity, "as", "", "[required] the id of the signing identity node")
	flags.StringVar(&parent, "to", "", "[required] the id of the parent reply or community node")
	flags.StringVar(&content, "content", "", "[required] content of the reply node")
	flags.StringVar(&metadata, "metadata", "{}", "Twig metadata fields for the node: {\"<key>/<version>\": \"data\",...}")

	usage := func() {
		flags.PrintDefaults()
	}
	if err := flags.Parse(args); err != nil {
		usage()
		return err
	}

	signer, err := getSigner(gpguser, keyfile)
	if err != nil {
		return fmt.Errorf("Error getting signer: %v", err)
	}
	idNode, err := getIdentity(identity)
	if err != nil {
		return fmt.Errorf("Error getting Identity: %v", err)
	}

	parentNode, err := getReplyOrCommunity(parent)
	if err != nil {
		return fmt.Errorf("Error getting Reply/Community: %v", err)
	}

	metadataRaw, err := decodeMetadata(metadata)
	if err != nil {
		return fmt.Errorf("Error decoding metadata: %v", err)
	}

	reply, err := forest.As(idNode, signer).NewReply(parentNode, content, metadataRaw)
	if err != nil {
		return fmt.Errorf("Error during creating new reply: %v", err)
	}

	fname, err := reply.ID().MarshalString()
	if err != nil {
		return fmt.Errorf("Error marshalling reply.ID: %v", err)
	}

	if err := saveAs(fname, reply); err != nil {
		return fmt.Errorf("Error saving reply: %v", err)
	}

	fmt.Println(fname)

	return nil
}

func showNode(args []string, commandName string, fromBytes func([]byte) (forest.Node, error)) error {
	flags := flag.NewFlagSet(commandName+" "+commandShow, flag.ExitOnError)
	usage := func() {
		flags.PrintDefaults()
	}
	if err := flags.Parse(args); err != nil {
		usage()
		return err
	}
	if len(flags.Args()) < 1 {
		return fmt.Errorf("missing required argument [node id]")
	}
	b, err := ioutil.ReadFile(args[0])
	if err != nil && err != io.EOF {
		return err
	}
	c, err := fromBytes(b)
	if err != nil {
		return err
	}
	if err := c.ValidateShallow(); err != nil {
		return err
	}
	text, err := json.Marshal(c)
	if err != nil {
		return err
	}
	if _, err := os.Stdout.Write(text); err != nil {
		return err
	}
	return nil
}

func save(w io.Writer, node encoding.BinaryMarshaler) error {
	b, err := node.MarshalBinary()
	if err != nil {
		return err
	}
	_, err = w.Write(b)
	return err
}

func saveAs(name string, node encoding.BinaryMarshaler) error {
	outfile, err := os.Create(name)
	if err != nil {
		return err
	}
	defer outfile.Close()

	return save(outfile, node)
}

func loadIdentity(r io.Reader) (*forest.Identity, error) {
	b, err := ioutil.ReadAll(r)
	if err != nil && err != io.EOF {
		return nil, err
	}
	return forest.UnmarshalIdentity(b)
}

func getIdentity(filename string) (*forest.Identity, error) {
	idFile, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer idFile.Close()

	return loadIdentity(idFile)
}

func loadCommunity(r io.Reader) (*forest.Community, error) {
	b, err := ioutil.ReadAll(r)
	if err != nil && err != io.EOF {
		return nil, err
	}
	return forest.UnmarshalCommunity(b)
}

func getCommunity(filename string) (*forest.Community, error) {
	idFile, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer idFile.Close()

	return loadCommunity(idFile)
}

func loadReplyOrCommunity(r io.Reader) (interface{}, error) {
	b, err := ioutil.ReadAll(r)
	if err != nil && err != io.EOF {
		return nil, err
	}
	nodeType, err := forest.NodeTypeOf(b)
	switch nodeType {
	case fields.NodeTypeReply:
		return forest.UnmarshalReply(b)
	case fields.NodeTypeCommunity:
		return forest.UnmarshalCommunity(b)
	default:
		return nil, fmt.Errorf("Expected node type of reply, got %v", nodeType)
	}
}

func getReplyOrCommunity(filename string) (interface{}, error) {
	idFile, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer idFile.Close()
	return loadReplyOrCommunity(idFile)
}

func readKey(in io.Reader) (*openpgp.Entity, error) {
	return openpgp.ReadEntity(packet.NewReader(in))
}

type PGPKeyConfig struct {
	Name    string
	Comment string
	Email   string
}

// getSigner returns a Signer. If the gpguser parameter is not the empty string, it
// uses a GPGSigner with that username. Otherwise, it uses a NativeSigner with the
// given privkeyFile as the source of the private key.
func getSigner(gpguser, privkeyFile string) (forest.Signer, error) {
	var (
		signer forest.Signer
		err    error
	)
	if gpguser != "" {
		signer, err = forest.NewGPGSigner(gpguser)
	} else {
		privkey, err := getPrivateKey(privkeyFile, &PGPKeyConfig{
			Name:    "Arbor identity key",
			Comment: "Automatically generated",
			Email:   "none@arbor.chat",
		})
		if err != nil {
			return nil, err
		}
		return forest.NewNativeSigner(privkey)
	}
	return signer, err
}

// getPrivateKey gets a private key for creating the identity based on the value
// of filename. If filename is:
// "-" => read a private key from stdin, do not write private key to a file
// existing file => read key from file, do not write private key to a file
// nonexistent file => create new private key, write to filename
//
// the value of config is only used when creating a new key
func getPrivateKey(filename string, config *PGPKeyConfig) (*openpgp.Entity, error) {
	var privkey *openpgp.Entity
	var err error
	if filename == "-" {
		// if stdin, try to read key
		return readKey(os.Stdin)

	}
	// check if privkeyfile exists
	keyOutFile, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0400)
	if err != nil {
		// keyfile may exist, use key from it
		keyOutFile, err := os.Open(filename)
		if err != nil {
			// keyfile doesn't exist or we can't open it
			return nil, err
		}
		return readKey(keyOutFile)
	}
	// keyfile did not exist, create new key and write it there
	privkey, err = openpgp.NewEntity(config.Name, config.Comment, config.Email, nil)
	if err != nil {
		return nil, err
	}

	if err := privkey.SerializePrivate(keyOutFile, nil); err != nil {
		return nil, err
	}
	return privkey, nil

}