1//
2// Copyright (c) 2018, Joyent, Inc. All rights reserved.
3//
4// This Source Code Form is subject to the terms of the Mozilla Public
5// License, v. 2.0. If a copy of the MPL was not distributed with this
6// file, You can obtain one at http://mozilla.org/MPL/2.0/.
7//
8
9package main
10
11import (
12	"context"
13	"fmt"
14	"io/ioutil"
15	"log"
16	"os"
17
18	"encoding/pem"
19
20	triton "github.com/joyent/triton-go"
21	"github.com/joyent/triton-go/authentication"
22	"github.com/joyent/triton-go/storage"
23)
24
25func main() {
26	keyID := os.Getenv("TRITON_KEY_ID")
27	accountName := os.Getenv("TRITON_ACCOUNT")
28	keyMaterial := os.Getenv("TRITON_KEY_MATERIAL")
29	userName := os.Getenv("TRITON_USER")
30
31	var signer authentication.Signer
32	var err error
33
34	if keyMaterial == "" {
35		input := authentication.SSHAgentSignerInput{
36			KeyID:       keyID,
37			AccountName: accountName,
38			Username:    userName,
39		}
40		signer, err = authentication.NewSSHAgentSigner(input)
41		if err != nil {
42			log.Fatalf("Error Creating SSH Agent Signer: %v", err)
43		}
44	} else {
45		var keyBytes []byte
46		if _, err = os.Stat(keyMaterial); err == nil {
47			keyBytes, err = ioutil.ReadFile(keyMaterial)
48			if err != nil {
49				log.Fatalf("Error reading key material from %s: %s",
50					keyMaterial, err)
51			}
52			block, _ := pem.Decode(keyBytes)
53			if block == nil {
54				log.Fatalf(
55					"Failed to read key material '%s': no key found", keyMaterial)
56			}
57
58			if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
59				log.Fatalf(
60					"Failed to read key '%s': password protected keys are\n"+
61						"not currently supported. Please decrypt the key prior to use.", keyMaterial)
62			}
63
64		} else {
65			keyBytes = []byte(keyMaterial)
66		}
67
68		input := authentication.PrivateKeySignerInput{
69			KeyID:              keyID,
70			PrivateKeyMaterial: keyBytes,
71			AccountName:        accountName,
72			Username:           userName,
73		}
74		signer, err = authentication.NewPrivateKeySigner(input)
75		if err != nil {
76			log.Fatalf("Error Creating SSH Private Key Signer: %v", err)
77		}
78	}
79
80	config := &triton.ClientConfig{
81		MantaURL:    os.Getenv("TRITON_URL"),
82		AccountName: accountName,
83		Username:    userName,
84		Signers:     []authentication.Signer{signer},
85	}
86
87	client, err := storage.NewClient(config)
88	if err != nil {
89		log.Fatalf("NewClient: %v", err)
90	}
91
92	ctx := context.Background()
93	input := &storage.ListDirectoryInput{}
94	output, err := client.Dir().List(ctx, input)
95	if err != nil {
96		log.Fatalf("storage.Dir.List: %v", err)
97	}
98
99	for _, dir := range output.Entries {
100		fmt.Println(dir.Name)
101	}
102}
103