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	"encoding/pem"
13	"io/ioutil"
14	"log"
15	"os"
16
17	"net/http"
18	"time"
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	input := &storage.SignURLInput{
93		ObjectPath:     "/stor/books/treasure_island.txt",
94		Method:         http.MethodGet,
95		ValidityPeriod: 5 * time.Minute,
96	}
97	signed, err := client.SignURL(input)
98	if err != nil {
99		log.Fatalf("SignURL: %v", err)
100	}
101
102	log.Printf("Signed URL: %s", signed.SignedURL("http"))
103}
104