2023-03-15 16:00:52 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2019-02-15 01:10:36 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
2019-03-12 20:21:02 +00:00
|
|
|
"time"
|
2019-02-15 01:10:36 +00:00
|
|
|
|
2022-02-18 01:10:26 +00:00
|
|
|
"github.com/armon/go-metrics"
|
2022-05-12 16:25:55 +00:00
|
|
|
"github.com/hashicorp/go-hclog"
|
2019-02-15 01:10:36 +00:00
|
|
|
"github.com/hashicorp/vault/api"
|
2023-05-17 13:38:34 +00:00
|
|
|
"github.com/hashicorp/vault/command/agentproxyshared/sink"
|
2019-04-12 21:54:35 +00:00
|
|
|
"github.com/hashicorp/vault/sdk/helper/consts"
|
|
|
|
"github.com/hashicorp/vault/sdk/logical"
|
2019-02-15 01:10:36 +00:00
|
|
|
)
|
|
|
|
|
2022-12-05 15:51:03 +00:00
|
|
|
func ProxyHandler(ctx context.Context, logger hclog.Logger, proxier Proxier, inmemSink sink.Sink, proxyVaultToken bool) http.Handler {
|
2019-02-15 01:10:36 +00:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2019-05-22 16:21:47 +00:00
|
|
|
logger.Info("received request", "method", r.Method, "path", r.URL.Path)
|
2019-02-15 01:10:36 +00:00
|
|
|
|
2020-01-30 15:08:42 +00:00
|
|
|
if !proxyVaultToken {
|
|
|
|
r.Header.Del(consts.AuthHeaderName)
|
|
|
|
}
|
|
|
|
|
2019-02-15 01:10:36 +00:00
|
|
|
token := r.Header.Get(consts.AuthHeaderName)
|
2020-01-30 15:08:42 +00:00
|
|
|
|
2019-02-20 07:11:05 +00:00
|
|
|
if token == "" && inmemSink != nil {
|
2019-05-22 16:21:47 +00:00
|
|
|
logger.Debug("using auto auth token", "method", r.Method, "path", r.URL.Path)
|
2019-02-20 07:11:05 +00:00
|
|
|
token = inmemSink.(sink.SinkReader).Token()
|
2019-02-15 01:10:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Parse and reset body.
|
2022-12-05 15:51:03 +00:00
|
|
|
reqBody, err := io.ReadAll(r.Body)
|
2019-02-15 01:10:36 +00:00
|
|
|
if err != nil {
|
|
|
|
logger.Error("failed to read request body")
|
2019-03-05 16:43:30 +00:00
|
|
|
logical.RespondError(w, http.StatusInternalServerError, errors.New("failed to read request body"))
|
2020-04-21 22:30:36 +00:00
|
|
|
return
|
2019-02-15 01:10:36 +00:00
|
|
|
}
|
|
|
|
if r.Body != nil {
|
|
|
|
r.Body.Close()
|
|
|
|
}
|
2022-12-05 15:51:03 +00:00
|
|
|
r.Body = io.NopCloser(bytes.NewReader(reqBody))
|
2019-02-15 01:10:36 +00:00
|
|
|
req := &SendRequest{
|
|
|
|
Token: token,
|
|
|
|
Request: r,
|
|
|
|
RequestBody: reqBody,
|
|
|
|
}
|
|
|
|
|
|
|
|
resp, err := proxier.Send(ctx, req)
|
|
|
|
if err != nil {
|
2022-09-06 14:35:54 +00:00
|
|
|
// If this is an api.Response error, don't wrap the response.
|
2019-03-07 01:23:20 +00:00
|
|
|
if resp != nil && resp.Response.Error() != nil {
|
|
|
|
copyHeader(w.Header(), resp.Response.Header)
|
|
|
|
w.WriteHeader(resp.Response.StatusCode)
|
|
|
|
io.Copy(w, resp.Response.Body)
|
2022-02-18 01:10:26 +00:00
|
|
|
metrics.IncrCounter([]string{"agent", "proxy", "client_error"}, 1)
|
2019-03-07 01:23:20 +00:00
|
|
|
} else {
|
2022-02-18 01:10:26 +00:00
|
|
|
metrics.IncrCounter([]string{"agent", "proxy", "error"}, 1)
|
2021-06-02 13:22:31 +00:00
|
|
|
logical.RespondError(w, http.StatusInternalServerError, fmt.Errorf("failed to get the response: %w", err))
|
2019-03-07 01:23:20 +00:00
|
|
|
}
|
2019-02-15 01:10:36 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-05-12 16:25:55 +00:00
|
|
|
err = sanitizeAutoAuthTokenResponse(ctx, logger, inmemSink, req, resp)
|
2019-02-15 01:10:36 +00:00
|
|
|
if err != nil {
|
2021-06-02 13:22:31 +00:00
|
|
|
logical.RespondError(w, http.StatusInternalServerError, fmt.Errorf("failed to process token lookup response: %w", err))
|
2019-02-15 01:10:36 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
defer resp.Response.Body.Close()
|
|
|
|
|
2022-02-18 01:10:26 +00:00
|
|
|
metrics.IncrCounter([]string{"agent", "proxy", "success"}, 1)
|
|
|
|
if resp.CacheMeta != nil {
|
|
|
|
if resp.CacheMeta.Hit {
|
|
|
|
metrics.IncrCounter([]string{"agent", "cache", "hit"}, 1)
|
|
|
|
} else {
|
|
|
|
metrics.IncrCounter([]string{"agent", "cache", "miss"}, 1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-12 20:21:02 +00:00
|
|
|
// Set headers
|
|
|
|
setHeaders(w, resp)
|
|
|
|
|
|
|
|
// Set response body
|
2019-02-15 01:10:36 +00:00
|
|
|
io.Copy(w, resp.Response.Body)
|
|
|
|
return
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-03-12 20:21:02 +00:00
|
|
|
// setHeaders is a helper that sets the header values based on SendResponse. It
|
|
|
|
// copies over the headers from the original response and also includes any
|
|
|
|
// cache-related headers.
|
|
|
|
func setHeaders(w http.ResponseWriter, resp *SendResponse) {
|
|
|
|
// Set header values
|
|
|
|
copyHeader(w.Header(), resp.Response.Header)
|
|
|
|
if resp.CacheMeta != nil {
|
|
|
|
xCacheVal := "MISS"
|
|
|
|
|
|
|
|
if resp.CacheMeta.Hit {
|
|
|
|
xCacheVal = "HIT"
|
|
|
|
|
|
|
|
// If this is a cache hit, we also set the Age header
|
|
|
|
age := fmt.Sprintf("%.0f", resp.CacheMeta.Age.Seconds())
|
|
|
|
w.Header().Set("Age", age)
|
|
|
|
|
|
|
|
// Update the date value
|
|
|
|
w.Header().Set("Date", time.Now().Format(http.TimeFormat))
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("X-Cache", xCacheVal)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set status code
|
|
|
|
w.WriteHeader(resp.Response.StatusCode)
|
|
|
|
}
|
|
|
|
|
2022-05-12 16:25:55 +00:00
|
|
|
// sanitizeAutoAuthTokenResponse checks if the request was a lookup or renew
|
|
|
|
// and if the auto-auth token was used to perform lookup-self, the identifier
|
|
|
|
// of the token and its accessor same will be stripped off of the response.
|
|
|
|
func sanitizeAutoAuthTokenResponse(ctx context.Context, logger hclog.Logger, inmemSink sink.Sink, req *SendRequest, resp *SendResponse) error {
|
2019-02-15 01:10:36 +00:00
|
|
|
// If auto-auth token is not being used, there is nothing to do.
|
2019-02-20 07:11:05 +00:00
|
|
|
if inmemSink == nil {
|
2019-02-15 01:10:36 +00:00
|
|
|
return nil
|
|
|
|
}
|
2019-02-20 07:11:05 +00:00
|
|
|
autoAuthToken := inmemSink.(sink.SinkReader).Token()
|
2019-02-15 01:10:36 +00:00
|
|
|
|
|
|
|
// If lookup responded with non 200 status, there is nothing to do.
|
|
|
|
if resp.Response.StatusCode != http.StatusOK {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
_, path := deriveNamespaceAndRevocationPath(req)
|
2019-02-19 21:53:29 +00:00
|
|
|
switch path {
|
2022-05-12 16:25:55 +00:00
|
|
|
case vaultPathTokenLookupSelf, vaultPathTokenRenewSelf:
|
2019-02-20 07:11:05 +00:00
|
|
|
if req.Token != autoAuthToken {
|
|
|
|
return nil
|
|
|
|
}
|
2022-05-12 16:25:55 +00:00
|
|
|
case vaultPathTokenLookup, vaultPathTokenRenew:
|
2019-02-19 21:53:29 +00:00
|
|
|
jsonBody := map[string]interface{}{}
|
|
|
|
if err := json.Unmarshal(req.RequestBody, &jsonBody); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
tokenRaw, ok := jsonBody["token"]
|
|
|
|
if !ok {
|
|
|
|
// Input error will be caught by the API
|
|
|
|
return nil
|
2019-02-15 01:10:36 +00:00
|
|
|
}
|
2019-02-19 21:53:29 +00:00
|
|
|
token, ok := tokenRaw.(string)
|
|
|
|
if !ok {
|
|
|
|
// Input error will be caught by the API
|
|
|
|
return nil
|
2019-02-15 01:10:36 +00:00
|
|
|
}
|
2019-02-20 07:11:05 +00:00
|
|
|
if token != "" && token != autoAuthToken {
|
2019-02-19 21:53:29 +00:00
|
|
|
// Lookup is performed on the non-auto-auth token
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-05-22 16:21:47 +00:00
|
|
|
logger.Info("stripping auto-auth token from the response", "method", req.Request.Method, "path", req.Request.URL.Path)
|
2019-02-19 21:53:29 +00:00
|
|
|
secret, err := api.ParseSecret(bytes.NewReader(resp.ResponseBody))
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to parse token lookup response: %v", err)
|
2019-02-15 01:10:36 +00:00
|
|
|
}
|
2022-05-12 16:25:55 +00:00
|
|
|
if secret == nil {
|
2019-02-19 21:53:29 +00:00
|
|
|
return nil
|
2022-05-12 16:25:55 +00:00
|
|
|
} else if secret.Data != nil {
|
|
|
|
// lookup endpoints
|
|
|
|
if secret.Data["id"] == nil && secret.Data["accessor"] == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
delete(secret.Data, "id")
|
|
|
|
delete(secret.Data, "accessor")
|
|
|
|
} else if secret.Auth != nil {
|
|
|
|
// renew endpoints
|
|
|
|
if secret.Auth.Accessor == "" && secret.Auth.ClientToken == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
secret.Auth.Accessor = ""
|
|
|
|
secret.Auth.ClientToken = ""
|
|
|
|
} else {
|
|
|
|
// nothing to redact
|
2019-02-19 21:53:29 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
bodyBytes, err := json.Marshal(secret)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if resp.Response.Body != nil {
|
|
|
|
resp.Response.Body.Close()
|
|
|
|
}
|
|
|
|
resp.Response.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes))
|
|
|
|
resp.Response.ContentLength = int64(len(bodyBytes))
|
|
|
|
|
2019-07-19 01:10:15 +00:00
|
|
|
// Serialize and re-read the response
|
2019-02-19 21:53:29 +00:00
|
|
|
var respBytes bytes.Buffer
|
|
|
|
err = resp.Response.Write(&respBytes)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to serialize the updated response: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
updatedResponse, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(respBytes.Bytes())), nil)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to deserialize the updated response: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
resp.Response = &api.Response{
|
|
|
|
Response: updatedResponse,
|
|
|
|
}
|
|
|
|
resp.ResponseBody = bodyBytes
|
|
|
|
|
2019-02-15 01:10:36 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func copyHeader(dst, src http.Header) {
|
|
|
|
for k, vv := range src {
|
|
|
|
for _, v := range vv {
|
|
|
|
dst.Add(k, v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|