Skip to content

Commit 6f9faa4

Browse files
error message decoding and code cleanup
1 parent 649f97a commit 6f9faa4

File tree

3 files changed

+90
-96
lines changed

3 files changed

+90
-96
lines changed

backend.go

Lines changed: 37 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import (
1212
"sync"
1313
"time"
1414

15-
//"github.com/Keyfactor/keyfactor-go-client/api"
1615
"github.com/hashicorp/errwrap"
1716
"github.com/hashicorp/vault/sdk/framework"
1817
"github.com/hashicorp/vault/sdk/logical"
@@ -35,7 +34,7 @@ type keyfactorBackend struct {
3534
*framework.Backend
3635
lock sync.RWMutex
3736
cachedConfig *keyfactorConfig
38-
//client *api.Client
37+
client *keyfactorClient
3938
}
4039

4140
// keyfactorBackend defines the target API keyfactorBackend
@@ -66,21 +65,39 @@ func backend() *keyfactorBackend {
6665
return &b
6766
}
6867

69-
// func (b *keyfactorBackend) initialize(ctx context.Context, req *logical.InitializationRequest) error {
70-
// err := req.Storage.Delete(ctx, "/ca")
71-
72-
// if err != nil {
73-
// b.Logger().Error("Error removing previous stored ca values on init")
74-
// return err
75-
// }
76-
// //confPath := os.Getenv("KF_CONF_PATH")
77-
// //file, _ := ioutil.ReadFile(confPath)
78-
// //config = make(map[string]string)
79-
// //jsonutil.DecodeJSON(file, &config)
80-
// //b.Logger().Debug("INITIALIZE: KF_CONF_PATH = " + confPath)
81-
// //b.Logger().Debug("config file contents = ", config)
82-
// return nil
83-
// }
68+
// reset clears any client configuration for a new
69+
// backend to be configured
70+
func (b *keyfactorBackend) reset() {
71+
b.lock.Lock()
72+
defer b.lock.Unlock()
73+
b.client = nil
74+
}
75+
76+
// invalidate clears an existing client configuration in
77+
// the backend
78+
func (b *keyfactorBackend) invalidate(ctx context.Context, key string) {
79+
if key == "config" {
80+
b.reset()
81+
}
82+
}
83+
84+
// getClient locks the backend as it configures and creates a
85+
// a new client for the target API
86+
func (b *keyfactorBackend) getClient(ctx context.Context, s logical.Storage) (*keyfactorClient, error) {
87+
b.lock.RLock()
88+
unlockFunc := b.lock.RUnlock
89+
defer func() { unlockFunc() }()
90+
91+
if b.client != nil {
92+
return b.client, nil
93+
}
94+
95+
b.lock.RUnlock()
96+
b.lock.Lock()
97+
unlockFunc = b.lock.Unlock
98+
99+
return nil, fmt.Errorf("need to return client")
100+
}
84101

85102
// Handle interface with Keyfactor API to enroll a certificate with given content
86103
func (b *keyfactorBackend) submitCSR(ctx context.Context, req *logical.Request, csr string, caName string, templateName string) ([]string, string, error) {
@@ -92,11 +109,6 @@ func (b *keyfactorBackend) submitCSR(ctx context.Context, req *logical.Request,
92109
return nil, "", errors.New("configuration is empty.")
93110
}
94111

95-
// host := config["host"]
96-
// template := config["template"]
97-
// ca := config["CA"]
98-
// creds := config["creds"]
99-
100112
ca := config.CertAuthority
101113
template := config.CertTemplate
102114

@@ -130,14 +142,14 @@ func (b *keyfactorBackend) submitCSR(ctx context.Context, req *logical.Request,
130142
b.Logger().Debug("About to connect to " + config.KeyfactorUrl + "for csr submission")
131143
res, err := http.DefaultClient.Do(httpReq)
132144
if err != nil {
133-
b.Logger().Info("CSR Enrollment failed: {{err}}", err)
145+
b.Logger().Info("CSR Enrollment failed: {{err}}", err.Error())
134146
return nil, "", err
135147
}
136148
if res.StatusCode != 200 {
137149
b.Logger().Error("CSR Enrollment failed: server returned" + fmt.Sprint(res.StatusCode))
138150
defer res.Body.Close()
139151
body, _ := ioutil.ReadAll(res.Body)
140-
b.Logger().Error("Error response: " + fmt.Sprint(body))
152+
b.Logger().Error("Error response: " + string(body[:]))
141153
return nil, "", fmt.Errorf("enrollment failed: server returned %d\n ", res.StatusCode)
142154
}
143155

@@ -166,7 +178,7 @@ func (b *keyfactorBackend) submitCSR(ctx context.Context, req *logical.Request,
166178
kfId := inner["KeyfactorID"].(float64)
167179

168180
if err != nil {
169-
b.Logger().Error("unable to parse ca_chain response", err)
181+
b.Logger().Error("unable to parse ca_chain response", fmt.Sprint(err))
170182
}
171183
caEntry, err := logical.StorageEntryJSON("ca_chain/", certs[1:])
172184
if err != nil {
@@ -199,40 +211,6 @@ func (b *keyfactorBackend) submitCSR(ctx context.Context, req *logical.Request,
199211
return certs, serial, nil
200212
}
201213

202-
// reset clears any client configuration for a new
203-
// backend to be configured
204-
func (b *keyfactorBackend) reset() {
205-
b.lock.Lock()
206-
defer b.lock.Unlock()
207-
//b.client = nil
208-
}
209-
210-
// invalidate clears an existing client configuration in
211-
// the backend
212-
func (b *keyfactorBackend) invalidate(ctx context.Context, key string) {
213-
if key == "config" {
214-
b.reset()
215-
}
216-
}
217-
218-
// getClient locks the backend as it configures and creates a
219-
// a new client for the target API
220-
// func (b *keyfactorBackend) getClient(ctx context.Context, s logical.Storage) (*hashiCupsClient, error) {
221-
// b.lock.RLock()
222-
// unlockFunc := b.lock.RUnlock
223-
// defer func() { unlockFunc() }()
224-
225-
// // if b.client != nil {
226-
// // return b.client, nil
227-
// // }
228-
229-
// b.lock.RUnlock()
230-
// b.lock.Lock()
231-
// unlockFunc = b.lock.Unlock
232-
233-
// return nil, fmt.Errorf("need to return client")
234-
// }
235-
236214
const keyfactorHelp = `
237215
The Keyfactor backend is a pki service that issues and manages certificates.
238216
`

cert_util.go

Lines changed: 0 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -25,43 +25,6 @@ import (
2525
"github.com/hashicorp/vault/sdk/logical"
2626
)
2727

28-
// type inputBundle struct {
29-
// role *roleEntry
30-
// req *logical.Request
31-
// apiData *framework.FieldData
32-
// }
33-
34-
// var (
35-
// // A note on hostnameRegex: although we set the StrictDomainName option
36-
// // when doing the idna conversion, this appears to only affect output, not
37-
// // input, so it will allow e.g. host^123.example.com straight through. So
38-
// // we still need to use this to check the output.
39-
// hostnameRegex = regexp.MustCompile(`^(\*\.)?(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])\.?$`)
40-
// oidExtensionBasicConstraints = []int{2, 5, 29, 19}
41-
// oidExtensionSubjectAltName = []int{2, 5, 29, 17}
42-
// )
43-
44-
// func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
45-
// for _, e := range extensions {
46-
// if e.Id.Equal(oid) {
47-
// return true
48-
// }
49-
// }
50-
// return false
51-
// }
52-
53-
// func getFormat(data *framework.FieldData) string {
54-
// format := data.Get("format").(string)
55-
// switch format {
56-
// case "pem":
57-
// case "der":
58-
// case "pem_bundle":
59-
// default:
60-
// format = ""
61-
// }
62-
// return format
63-
// }
64-
6528
// fetch the CA info from keyfactor
6629
func fetchCAInfo(ctx context.Context, req *logical.Request, b *keyfactorBackend) (response *logical.Response, retErr error) {
6730
// first we see if we have previously retreived the CA or chain

client.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package keyfactor
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"log"
7+
"strings"
8+
9+
"github.com/Keyfactor/keyfactor-go-client/api"
10+
)
11+
12+
type keyfactorClient struct {
13+
*api.Client
14+
}
15+
16+
func newClient(config *keyfactorConfig) (*api.Client, error) {
17+
if config == nil {
18+
return nil, errors.New("client configuration was nil")
19+
}
20+
21+
if config.Username == "" {
22+
return nil, errors.New("client username was not defined")
23+
}
24+
25+
if config.Password == "" {
26+
return nil, errors.New("client password was not defined")
27+
}
28+
29+
if config.KeyfactorUrl == "" {
30+
return nil, errors.New("client URL was not defined")
31+
}
32+
username := strings.Split(config.Username, "//")[1]
33+
domain := strings.Split(config.Username, "//")[1]
34+
hostname := config.KeyfactorUrl
35+
if strings.HasPrefix(config.KeyfactorUrl, "http") {
36+
hostname = strings.Split(config.KeyfactorUrl, "//")[1] //extract just the domain
37+
}
38+
39+
var clientAuth api.AuthConfig
40+
clientAuth.Username = username
41+
clientAuth.Password = config.Password
42+
clientAuth.Domain = domain
43+
clientAuth.Hostname = hostname
44+
45+
fmt.Printf("clientAuth values: \n %s", clientAuth)
46+
47+
c, err := api.NewKeyfactorClient(&clientAuth)
48+
if err != nil {
49+
log.Fatalf("[ERROR] creating Keyfactor client: %s", err)
50+
}
51+
52+
return c, err
53+
}

0 commit comments

Comments
 (0)