2019-02-15 01:10:36 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2019-02-19 21:53:29 +00:00
|
|
|
"fmt"
|
2019-02-15 01:10:36 +00:00
|
|
|
|
|
|
|
hclog "github.com/hashicorp/go-hclog"
|
|
|
|
"github.com/hashicorp/vault/api"
|
|
|
|
)
|
|
|
|
|
|
|
|
// APIProxy is an implementation of the proxier interface that is used to
|
|
|
|
// forward the request to Vault and get the response.
|
|
|
|
type APIProxy struct {
|
2019-02-19 21:53:29 +00:00
|
|
|
client *api.Client
|
2019-02-15 01:10:36 +00:00
|
|
|
logger hclog.Logger
|
|
|
|
}
|
|
|
|
|
|
|
|
type APIProxyConfig struct {
|
2019-02-19 21:53:29 +00:00
|
|
|
Client *api.Client
|
2019-02-15 01:10:36 +00:00
|
|
|
Logger hclog.Logger
|
|
|
|
}
|
|
|
|
|
2019-02-19 21:53:29 +00:00
|
|
|
func NewAPIProxy(config *APIProxyConfig) (Proxier, error) {
|
|
|
|
if config.Client == nil {
|
|
|
|
return nil, fmt.Errorf("nil API client")
|
|
|
|
}
|
2019-02-15 01:10:36 +00:00
|
|
|
return &APIProxy{
|
2019-02-19 21:53:29 +00:00
|
|
|
client: config.Client,
|
2019-02-15 01:10:36 +00:00
|
|
|
logger: config.Logger,
|
2019-02-19 21:53:29 +00:00
|
|
|
}, nil
|
2019-02-15 01:10:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ap *APIProxy) Send(ctx context.Context, req *SendRequest) (*SendResponse, error) {
|
2019-02-19 21:53:29 +00:00
|
|
|
client, err := ap.client.Clone()
|
2019-02-15 01:10:36 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
client.SetToken(req.Token)
|
|
|
|
client.SetHeaders(req.Request.Header)
|
|
|
|
|
|
|
|
fwReq := client.NewRequest(req.Request.Method, req.Request.URL.Path)
|
|
|
|
fwReq.BodyBytes = req.RequestBody
|
|
|
|
|
|
|
|
// Make the request to Vault and get the response
|
|
|
|
ap.logger.Info("forwarding request", "path", req.Request.URL.Path, "method", req.Request.Method)
|
2019-03-07 01:23:20 +00:00
|
|
|
|
2019-02-15 01:10:36 +00:00
|
|
|
resp, err := client.RawRequestWithContext(ctx, fwReq)
|
2019-02-19 21:53:29 +00:00
|
|
|
|
2019-03-12 20:21:02 +00:00
|
|
|
// Before error checking from the request call, we'd want to initialize a SendResponse to
|
|
|
|
// potentially return
|
|
|
|
sendResponse, newErr := NewSendResponse(resp, nil)
|
|
|
|
if newErr != nil {
|
|
|
|
return nil, newErr
|
2019-02-15 01:10:36 +00:00
|
|
|
}
|
|
|
|
|
2019-03-12 20:21:02 +00:00
|
|
|
// Bubble back the api.Response as well for error checking/handling at the handler layer.
|
|
|
|
return sendResponse, err
|
2019-02-15 01:10:36 +00:00
|
|
|
}
|