-
Notifications
You must be signed in to change notification settings - Fork 491
/
utils.go
68 lines (60 loc) · 2.05 KB
/
utils.go
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
// Copyright 2017 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package user
import (
"encoding/asn1"
"encoding/base64"
"github.com/juju/errors"
"gopkg.in/yaml.v2"
"github.com/juju/juju/jujuclient"
)
// ControllerCommand defines a subset methods of the modelcmd.ControllerCommandBase that the generateUserControllerAccessToken function uses.
type ControllerCommand interface {
ControllerName() (string, error)
ClientStore() jujuclient.ClientStore
}
func generateUserControllerAccessToken(command ControllerCommand, username string, secretKey []byte) (string, error) {
controllerName, err := command.ControllerName()
if err != nil {
return "", errors.Trace(err)
}
// Generate the base64-encoded string for the user to pass to
// "juju register". We marshal the information using ASN.1
// to keep the size down, since we need to encode binary data.
controllerDetails, err := command.ClientStore().ControllerByName(controllerName)
if err != nil {
return "", errors.Trace(err)
}
registrationInfo := jujuclient.RegistrationInfo{
User: username,
Addrs: controllerDetails.APIEndpoints,
SecretKey: secretKey,
ControllerName: controllerName,
}
if controllerDetails.Proxy != nil {
controllerDetails.Proxy.Proxier.Insecure()
proxyConfig, err := yaml.Marshal(controllerDetails.Proxy)
if err != nil {
return "", errors.Trace(err)
}
if len(proxyConfig) > 0 {
registrationInfo.ProxyConfig = string(proxyConfig)
}
}
registrationData, err := asn1.Marshal(registrationInfo)
if err != nil {
return "", errors.Trace(err)
}
// Use URLEncoding so we don't get + or / in the string,
// and pad with zero bytes so we don't get =; this all
// makes it easier to copy & paste in a terminal.
//
// The embedded ASN.1 data is length-encoded, so the
// padding will not complicate decoding.
remainder := len(registrationData) % 3
if remainder != 0 {
var pad [3]byte
registrationData = append(registrationData, pad[:3-remainder]...)
}
return base64.URLEncoding.EncodeToString(registrationData), nil
}