Initial worker porting steps (#232)
This commit is contained in:
1 parent
73a38b1433
commit
203e2b5dc2
41 files changed
+2462
-645
No files matched your search
@@ -5,11 +5,13 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/host/static"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/servers"
|
||||
)
|
||||
|
||||
type (
|
||||
IamRepoFactory func() (*iam.Repository, error)
|
||||
StaticRepoFactory func() (*static.Repository, error)
|
||||
AuthTokenRepoFactory func() (*authtoken.Repository, error)
|
||||
ServersRepoFactory func() (*servers.Repository, error)
|
||||
PasswordAuthRepoFactory func() (*password.Repository, error)
|
||||
)
|
||||
@@ -4,15 +4,21 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/auth/password"
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/cmd/config"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
"github.com/hashicorp/boundary/internal/host/static"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/servers"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common"
|
||||
"github.com/hashicorp/go-hclog"
|
||||
"github.com/hashicorp/vault/sdk/helper/base62"
|
||||
"github.com/hashicorp/vault/sdk/helper/mlock"
|
||||
"github.com/patrickmn/go-cache"
|
||||
ua "go.uber.org/atomic"
|
||||
)
|
||||
|
||||
type Controller struct {
|
||||
@@ -21,25 +27,46 @@ type Controller struct {
|
||||
|
||||
baseContext context.Context
|
||||
baseCancel context.CancelFunc
|
||||
started ua.Bool
|
||||
|
||||
workerAuthCache *cache.Cache
|
||||
|
||||
// Used for testing
|
||||
workerStatusUpdateTimes *sync.Map
|
||||
|
||||
// Repo factory methods
|
||||
IamRepoFn common.IamRepoFactory
|
||||
StaticHostRepoFn common.StaticRepoFactory
|
||||
AuthTokenRepoFn common.AuthTokenRepoFactory
|
||||
|
||||
IamRepoFn common.IamRepoFactory
|
||||
StaticHostRepoFn common.StaticRepoFactory
|
||||
AuthTokenRepoFn common.AuthTokenRepoFactory
|
||||
ServersRepoFn common.ServersRepoFactory
|
||||
PasswordAuthRepoFn common.PasswordAuthRepoFactory
|
||||
|
||||
clusterAddress string
|
||||
}
|
||||
|
||||
func New(conf *Config) (*Controller, error) {
|
||||
c := &Controller{
|
||||
conf: conf,
|
||||
logger: conf.Logger.Named("controller"),
|
||||
conf: conf,
|
||||
logger: conf.Logger.Named("controller"),
|
||||
workerStatusUpdateTimes: new(sync.Map),
|
||||
}
|
||||
|
||||
c.started.Store(false)
|
||||
|
||||
if conf.SecureRandomReader == nil {
|
||||
conf.SecureRandomReader = rand.Reader
|
||||
}
|
||||
|
||||
var err error
|
||||
if conf.RawConfig.Controller == nil {
|
||||
conf.RawConfig.Controller = new(config.Controller)
|
||||
}
|
||||
if conf.RawConfig.Controller.Name == "" {
|
||||
if conf.RawConfig.Controller.Name, err = base62.Random(10); err != nil {
|
||||
return nil, fmt.Errorf("error auto-generating controller name: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if !conf.RawConfig.DisableMlock {
|
||||
// Ensure our memory usage is locked into physical RAM
|
||||
if err := mlock.LockMemory(); err != nil {
|
||||
@@ -56,8 +83,6 @@ func New(conf *Config) (*Controller, error) {
|
||||
}
|
||||
}
|
||||
|
||||
c.baseContext, c.baseCancel = context.WithCancel(context.Background())
|
||||
|
||||
// Set up repo stuff
|
||||
dbase := db.New(c.conf.Database)
|
||||
c.IamRepoFn = func() (*iam.Repository, error) {
|
||||
@@ -69,23 +94,53 @@ func New(conf *Config) (*Controller, error) {
|
||||
c.AuthTokenRepoFn = func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(dbase, dbase, c.conf.ControllerKMS)
|
||||
}
|
||||
c.ServersRepoFn = func() (*servers.Repository, error) {
|
||||
return servers.NewRepository(c.logger.Named("servers.repository"), dbase, dbase, c.conf.ControllerKMS)
|
||||
}
|
||||
c.PasswordAuthRepoFn = func() (*password.Repository, error) {
|
||||
return password.NewRepository(dbase, dbase, c.conf.ControllerKMS)
|
||||
}
|
||||
|
||||
c.workerAuthCache = cache.New(0, 0)
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *Controller) Start() error {
|
||||
if c.started.Load() {
|
||||
c.logger.Info("already started, skipping")
|
||||
return nil
|
||||
}
|
||||
c.baseContext, c.baseCancel = context.WithCancel(context.Background())
|
||||
|
||||
if err := c.startListeners(); err != nil {
|
||||
return fmt.Errorf("error starting controller listeners: %w", err)
|
||||
}
|
||||
|
||||
c.startStatusTicking(c.baseContext)
|
||||
c.started.Store(true)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Controller) Shutdown() error {
|
||||
if err := c.stopListeners(); err != nil {
|
||||
func (c *Controller) Shutdown(serversOnly bool) error {
|
||||
if !c.started.Load() {
|
||||
c.logger.Info("already shut down, skipping")
|
||||
return nil
|
||||
}
|
||||
c.baseCancel()
|
||||
if err := c.stopListeners(serversOnly); err != nil {
|
||||
return fmt.Errorf("error stopping controller listeners: %w", err)
|
||||
}
|
||||
c.clusterAddress = ""
|
||||
c.started.Store(false)
|
||||
return nil
|
||||
}
|
||||
|
||||
// WorkerStatusUpdateTimes returns the map, which specifically is held in _this_
|
||||
// controller, not the DB. It's used in tests to verify that a given controller
|
||||
// is receiving updates from an expected set of workers, to test out balancing
|
||||
// and auto reconnection.
|
||||
func (c *Controller) WorkerStatusUpdateTimes() *sync.Map {
|
||||
return c.workerStatusUpdateTimes
|
||||
}
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
|
||||
type HandlerProperties struct {
|
||||
ListenerConfig *configutil.Listener
|
||||
CancelCtx context.Context
|
||||
}
|
||||
|
||||
// Handler returns an http.Handler for the services. This can be used on
|
||||
@@ -40,7 +41,7 @@ func (c *Controller) handler(props HandlerProperties) (http.Handler, error) {
|
||||
// Create the muxer to handle the actual endpoints
|
||||
mux := http.NewServeMux()
|
||||
|
||||
h, err := handleGrpcGateway(c)
|
||||
h, err := handleGrpcGateway(c, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -54,10 +55,10 @@ func (c *Controller) handler(props HandlerProperties) (http.Handler, error) {
|
||||
return commonWrappedHandler, nil
|
||||
}
|
||||
|
||||
func handleGrpcGateway(c *Controller) (http.Handler, error) {
|
||||
// Register*ServiceHandlerServer methods ignore the passed in ctx. Using the baseContext now just in case this changes
|
||||
// in the future, at which point we'll want to be using the baseContext.
|
||||
ctx := c.baseContext
|
||||
func handleGrpcGateway(c *Controller, props HandlerProperties) (http.Handler, error) {
|
||||
// Register*ServiceHandlerServer methods ignore the passed in ctx. Using
|
||||
// the a context now just in case this changes in the future
|
||||
ctx := props.CancelCtx
|
||||
mux := runtime.NewServeMux(
|
||||
runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.HTTPBodyMarshaler{
|
||||
Marshaler: &runtime.JSONPb{
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package workers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common"
|
||||
"github.com/hashicorp/boundary/internal/types/resource"
|
||||
"github.com/hashicorp/go-hclog"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type workerServiceServer struct {
|
||||
logger hclog.Logger
|
||||
repoFn common.ServersRepoFactory
|
||||
updateTimes *sync.Map
|
||||
}
|
||||
|
||||
func NewWorkerServiceServer(logger hclog.Logger, repoFn common.ServersRepoFactory, updateTimes *sync.Map) *workerServiceServer {
|
||||
return &workerServiceServer{
|
||||
logger: logger,
|
||||
repoFn: repoFn,
|
||||
updateTimes: updateTimes,
|
||||
}
|
||||
}
|
||||
|
||||
func (ws *workerServiceServer) Status(ctx context.Context, req *pbs.StatusRequest) (*pbs.StatusResponse, error) {
|
||||
ws.logger.Trace("got status request from worker", "name", req.Worker.Name)
|
||||
ws.updateTimes.Store(req.Worker.Name, time.Now())
|
||||
repo, err := ws.repoFn()
|
||||
if err != nil {
|
||||
ws.logger.Error("error getting servers repo", "error", err)
|
||||
return &pbs.StatusResponse{}, status.Errorf(codes.Internal, "Error aqcuiring repo to store worker status: %v", err)
|
||||
}
|
||||
req.Worker.Type = resource.Worker.String()
|
||||
controllers, _, err := repo.Upsert(ctx, req.Worker)
|
||||
if err != nil {
|
||||
ws.logger.Error("error storing worker status", "error", err)
|
||||
return &pbs.StatusResponse{}, status.Errorf(codes.Internal, "Error storing worker status: %v", err)
|
||||
}
|
||||
return &pbs.StatusResponse{
|
||||
Controllers: controllers,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
// interceptingListener allows us to validate the nonce from a connection before
|
||||
// handing it off to the gRPC server. It is expected that the first thing a
|
||||
// connection sends after successful TLS validation is the nonce that was
|
||||
// contained in the KMS-encrypted TLS info. The reason is for replay attacks --
|
||||
// since the ALPN NextProtos are sent in the clear, we don't want anyone
|
||||
// sniffing the connection to simply replay the hello message and gain access.
|
||||
// By requiring the information encrypted within that message to match the first
|
||||
// bytes sent in the connection itself, we require that the service making the
|
||||
// incoming connection had to either be the service that did the initial
|
||||
// encryption, or had to be able to decrypt that against the same KMS key. This
|
||||
// means that KMS access is a requirement, and simple replay itself is not
|
||||
// sufficient.
|
||||
//
|
||||
// Note that this is semi-weak against a scenario where the value is decrypted
|
||||
// later since a controller restart would clear the cache. We could store a list
|
||||
// of seen nonces in the database, but since the original certificate was only
|
||||
// good for 3 minutes and 30 seconds anyways, the decryption would need to
|
||||
// happen within a short time window instead of much later. We can adjust this
|
||||
// window if we want (or even make it tunable), or store values in the DB as
|
||||
// well until the certificate expiration.
|
||||
type interceptingListener struct {
|
||||
baseLn net.Listener
|
||||
c *Controller
|
||||
}
|
||||
|
||||
func newInterceptingListener(c *Controller, baseLn net.Listener) *interceptingListener {
|
||||
ret := &interceptingListener{
|
||||
c: c,
|
||||
baseLn: baseLn,
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func (m *interceptingListener) Accept() (net.Conn, error) {
|
||||
conn, err := m.baseLn.Accept()
|
||||
if err != nil {
|
||||
if conn != nil {
|
||||
if err := conn.Close(); err != nil {
|
||||
m.c.logger.Error("error closing worker connection", "error", err)
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if m.c.logger.IsTrace() {
|
||||
m.c.logger.Trace("got connection", "addr", conn.RemoteAddr())
|
||||
}
|
||||
nonce := make([]byte, 20)
|
||||
read, err := conn.Read(nonce)
|
||||
if err != nil {
|
||||
if err := conn.Close(); err != nil {
|
||||
m.c.logger.Error("error closing worker connection", "error", err)
|
||||
}
|
||||
return nil, fmt.Errorf("error reading nonce from connection: %w", err)
|
||||
}
|
||||
if read != len(nonce) {
|
||||
if err := conn.Close(); err != nil {
|
||||
m.c.logger.Error("error closing worker connection", "error", err)
|
||||
}
|
||||
return nil, fmt.Errorf("error reading nonce from worker, expected %d bytes, got %d", 20, read)
|
||||
}
|
||||
workerInfoRaw, found := m.c.workerAuthCache.Get(string(nonce))
|
||||
if !found {
|
||||
if err := conn.Close(); err != nil {
|
||||
m.c.logger.Error("error closing worker connection", "error", err)
|
||||
}
|
||||
return nil, errors.New("did not find valid nonce for incoming worker")
|
||||
}
|
||||
workerInfo := workerInfoRaw.(*workerAuthEntry)
|
||||
workerInfo.conn = conn
|
||||
m.c.logger.Info("worker successfully authed", "name", workerInfo.Name)
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (m *interceptingListener) Close() error {
|
||||
return m.baseLn.Close()
|
||||
}
|
||||
|
||||
func (m *interceptingListener) Addr() net.Addr {
|
||||
return m.baseLn.Addr()
|
||||
}
|
||||
@@ -5,19 +5,21 @@ import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/cmd/base"
|
||||
"github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/workers"
|
||||
"github.com/hashicorp/go-alpnmux"
|
||||
"github.com/hashicorp/go-multierror"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
func (c *Controller) startListeners() error {
|
||||
var retErr *multierror.Error
|
||||
servers := make([]func(), 0, len(c.conf.Listeners))
|
||||
|
||||
configureForAPI := func(ln *base.ServerListener) error {
|
||||
@@ -44,6 +46,10 @@ func (c *Controller) startListeners() error {
|
||||
}
|
||||
*/
|
||||
|
||||
// Resolve it here to avoid race conditions if the base context is
|
||||
// replaced
|
||||
cancelCtx := c.baseContext
|
||||
|
||||
server := &http.Server{
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
@@ -51,7 +57,7 @@ func (c *Controller) startListeners() error {
|
||||
IdleTimeout: 5 * time.Minute,
|
||||
ErrorLog: c.logger.StandardLogger(nil),
|
||||
BaseContext: func(net.Listener) context.Context {
|
||||
return c.baseContext
|
||||
return cancelCtx
|
||||
},
|
||||
}
|
||||
ln.HTTPServer = server
|
||||
@@ -71,7 +77,10 @@ func (c *Controller) startListeners() error {
|
||||
|
||||
switch ln.Config.TLSDisable {
|
||||
case true:
|
||||
l := ln.Mux.GetListener(alpnmux.NoProto)
|
||||
l, err := ln.Mux.RegisterProto(alpnmux.NoProto, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error getting non-tls listener: %w", err)
|
||||
}
|
||||
if l == nil {
|
||||
return errors.New("could not get non-tls listener")
|
||||
}
|
||||
@@ -84,8 +93,7 @@ func (c *Controller) startListeners() error {
|
||||
for _, v := range protos {
|
||||
l := ln.Mux.GetListener(v)
|
||||
if l == nil {
|
||||
retErr = multierror.Append(retErr, fmt.Errorf("could not get tls proto %q listener", v))
|
||||
continue
|
||||
return fmt.Errorf("could not get tls proto %q listener", v)
|
||||
}
|
||||
servers = append(servers, func() {
|
||||
go server.Serve(l)
|
||||
@@ -97,36 +105,30 @@ func (c *Controller) startListeners() error {
|
||||
}
|
||||
|
||||
configureForCluster := func(ln *base.ServerListener) error {
|
||||
// Clear out in case this is a second start of the controller
|
||||
ln.Mux.UnregisterProto(alpnmux.DefaultProto)
|
||||
l, err := ln.Mux.RegisterProto(alpnmux.DefaultProto, &tls.Config{
|
||||
GetConfigForClient: c.validateWorkerTLS,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("error getting sub-listener for worker proto: %w", err)
|
||||
}
|
||||
ln.ALPNListener = l
|
||||
c.clusterAddress = l.Addr().String()
|
||||
c.logger.Info("cluster address", "addr", c.clusterAddress)
|
||||
|
||||
// TODO: Pass this to a handler, e.g. a grpc server, in the mean time
|
||||
// just accepting what comes
|
||||
go func() {
|
||||
for {
|
||||
conn, err := ln.ALPNListener.Accept()
|
||||
if err != nil {
|
||||
if !strings.Contains(err.Error(), "use of closed network connection") {
|
||||
c.logger.Info("default alpn listener errored, exiting", "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
_, err = conn.Read(make([]byte, 3))
|
||||
if err != nil {
|
||||
retErr = multierror.Append(retErr, fmt.Errorf("error reading test string from worker for worker auth: %w", err))
|
||||
}
|
||||
_, err = conn.Write([]byte("bar"))
|
||||
if err != nil {
|
||||
retErr = multierror.Append(retErr, fmt.Errorf("error writing test string to worker for worker auth: %w", err))
|
||||
}
|
||||
conn.Close()
|
||||
}
|
||||
}()
|
||||
workerServer := grpc.NewServer(
|
||||
grpc.MaxRecvMsgSize(math.MaxInt32),
|
||||
grpc.MaxSendMsgSize(math.MaxInt32),
|
||||
)
|
||||
services.RegisterWorkerServiceServer(workerServer, workers.NewWorkerServiceServer(c.logger.Named("worker-handler"), c.ServersRepoFn, c.workerStatusUpdateTimes))
|
||||
|
||||
interceptor := newInterceptingListener(c, l)
|
||||
ln.ALPNListener = interceptor
|
||||
ln.GrpcServer = workerServer
|
||||
|
||||
servers = append(servers, func() {
|
||||
go workerServer.Serve(interceptor)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -137,23 +139,20 @@ func (c *Controller) startListeners() error {
|
||||
case "api":
|
||||
err = configureForAPI(ln)
|
||||
case "cluster":
|
||||
err = configureForCluster(ln)
|
||||
if c.clusterAddress != "" {
|
||||
err = errors.New("more than one cluster listener found")
|
||||
} else {
|
||||
err = configureForCluster(ln)
|
||||
}
|
||||
case "worker-alpn-tls":
|
||||
// Do nothing, in a dev mode we might see it here
|
||||
default:
|
||||
err = fmt.Errorf("unknown listener purpose %q", purpose)
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
retErr = multierror.Append(retErr, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
err := retErr.ErrorOrNil()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, s := range servers {
|
||||
@@ -163,23 +162,34 @@ func (c *Controller) startListeners() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Controller) stopListeners() error {
|
||||
func (c *Controller) stopListeners(serversOnly bool) error {
|
||||
serverWg := new(sync.WaitGroup)
|
||||
for _, ln := range c.conf.Listeners {
|
||||
if ln.HTTPServer == nil {
|
||||
continue
|
||||
}
|
||||
localLn := ln
|
||||
serverWg.Add(1)
|
||||
go func() {
|
||||
defer serverWg.Done()
|
||||
|
||||
shutdownKill, shutdownKillCancel := context.WithTimeout(c.baseContext, localLn.Config.MaxRequestDuration)
|
||||
defer shutdownKillCancel()
|
||||
defer serverWg.Done()
|
||||
localLn.HTTPServer.Shutdown(shutdownKill)
|
||||
|
||||
if localLn.GrpcServer != nil {
|
||||
// Deal with the worst case
|
||||
go func() {
|
||||
<-shutdownKill.Done()
|
||||
localLn.GrpcServer.Stop()
|
||||
}()
|
||||
localLn.GrpcServer.GracefulStop()
|
||||
}
|
||||
if localLn.HTTPServer != nil {
|
||||
localLn.HTTPServer.Shutdown(shutdownKill)
|
||||
}
|
||||
}()
|
||||
}
|
||||
serverWg.Wait()
|
||||
|
||||
if serversOnly {
|
||||
return nil
|
||||
}
|
||||
var retErr *multierror.Error
|
||||
for _, ln := range c.conf.Listeners {
|
||||
if err := ln.Mux.Close(); err != nil {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package controller_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/boundary/api/authmethods"
|
||||
"github.com/hashicorp/boundary/api/scopes"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller"
|
||||
"github.com/hashicorp/go-hclog"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAuthenticationMulti(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
amId := "paum_1234567890"
|
||||
user := "user"
|
||||
password := "passpass"
|
||||
orgId := "o_1234567890"
|
||||
logger := hclog.New(&hclog.LoggerOptions{
|
||||
Level: hclog.Trace,
|
||||
})
|
||||
|
||||
c1 := controller.NewTestController(t, &controller.TestControllerOpts{
|
||||
DefaultOrgId: orgId,
|
||||
DefaultAuthMethodId: amId,
|
||||
DefaultLoginName: user,
|
||||
DefaultPassword: password,
|
||||
Logger: logger.Named("c1"),
|
||||
})
|
||||
defer c1.Shutdown()
|
||||
|
||||
c2 := c1.AddClusterControllerMember(t, &controller.TestControllerOpts{
|
||||
Logger: logger.Named("c2"),
|
||||
})
|
||||
defer c2.Shutdown()
|
||||
|
||||
auth := authmethods.NewAuthMethodsClient(c1.Client())
|
||||
token1, apiErr, err := auth.Authenticate(c1.Context(), amId, user, password)
|
||||
require.Nil(err)
|
||||
require.Nil(apiErr)
|
||||
require.NotNil(token1)
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
auth = authmethods.NewAuthMethodsClient(c2.Client())
|
||||
token2, apiErr, err := auth.Authenticate(c2.Context(), amId, user, password)
|
||||
require.Nil(err)
|
||||
require.Nil(apiErr)
|
||||
require.NotNil(token2)
|
||||
|
||||
assert.NotEqual(token1.Token, token2.Token)
|
||||
|
||||
c1.Client().SetToken(token1.Token)
|
||||
c2.Client().SetToken(token1.Token) // Same token, as it should work on both
|
||||
|
||||
// Create a project, read from the other
|
||||
proj, apiErr, err := scopes.NewScopesClient(c1.Client()).Create(c1.Context(), orgId)
|
||||
require.NoError(err)
|
||||
require.Nil(apiErr)
|
||||
require.NotNil(proj)
|
||||
projId := proj.Id
|
||||
|
||||
proj, apiErr, err = scopes.NewScopesClient(c2.Client()).Read(c2.Context(), projId)
|
||||
require.NoError(err)
|
||||
require.Nil(apiErr)
|
||||
require.NotNil(proj)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/servers"
|
||||
"github.com/hashicorp/boundary/internal/types/resource"
|
||||
)
|
||||
|
||||
// In the future we could make this configurable
|
||||
const (
|
||||
statusInterval = 10 * time.Second
|
||||
)
|
||||
|
||||
func (c *Controller) startStatusTicking(cancelCtx context.Context) {
|
||||
go func() {
|
||||
timer := time.NewTimer(0)
|
||||
for {
|
||||
select {
|
||||
case <-cancelCtx.Done():
|
||||
c.logger.Info("status ticking shutting down")
|
||||
return
|
||||
|
||||
case <-timer.C:
|
||||
server := &servers.Server{
|
||||
PrivateId: c.conf.RawConfig.Controller.Name,
|
||||
Name: c.conf.RawConfig.Controller.Name,
|
||||
Type: resource.Controller.String(),
|
||||
Description: c.conf.RawConfig.Controller.Description,
|
||||
Address: c.clusterAddress,
|
||||
}
|
||||
repo, err := c.ServersRepoFn()
|
||||
if err != nil {
|
||||
c.logger.Error("error fetching repository for status update", "error", err)
|
||||
} else {
|
||||
_, _, err = repo.Upsert(cancelCtx, server)
|
||||
if err != nil {
|
||||
c.logger.Error("error performing status update", "error", err)
|
||||
} else {
|
||||
c.logger.Trace("controller status successfully saved")
|
||||
}
|
||||
}
|
||||
timer.Reset(statusInterval)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -10,19 +10,23 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/cmd/base"
|
||||
"github.com/hashicorp/boundary/internal/cmd/config"
|
||||
"github.com/hashicorp/go-hclog"
|
||||
wrapping "github.com/hashicorp/go-kms-wrapping"
|
||||
"github.com/hashicorp/vault/sdk/helper/base62"
|
||||
)
|
||||
|
||||
// TestController wraps a base.Server and Controller to provide a
|
||||
// fully-programmatic controller for tests. Error checking (for instance, for
|
||||
// valid config) is not stringent at the moment.
|
||||
type TestController struct {
|
||||
b *base.Server
|
||||
c *Controller
|
||||
t *testing.T
|
||||
addrs []string // The address the Controller API is listening on
|
||||
client *api.Client
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
b *base.Server
|
||||
c *Controller
|
||||
t *testing.T
|
||||
apiAddrs []string // The address the Controller API is listening on
|
||||
clusterAddrs []string
|
||||
client *api.Client
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
name string
|
||||
}
|
||||
|
||||
// Controller returns the underlying controller
|
||||
@@ -30,6 +34,10 @@ func (tc *TestController) Controller() *Controller {
|
||||
return tc.c
|
||||
}
|
||||
|
||||
func (tc *TestController) Config() *Config {
|
||||
return tc.c.conf
|
||||
}
|
||||
|
||||
func (tc *TestController) Client() *api.Client {
|
||||
return tc.client
|
||||
}
|
||||
@@ -42,23 +50,52 @@ func (tc *TestController) Cancel() {
|
||||
tc.cancel()
|
||||
}
|
||||
|
||||
func (tc *TestController) Name() string {
|
||||
return tc.name
|
||||
}
|
||||
|
||||
func (tc *TestController) ApiAddrs() []string {
|
||||
if tc.addrs != nil {
|
||||
return tc.addrs
|
||||
return tc.addrs("api")
|
||||
}
|
||||
|
||||
func (tc *TestController) ClusterAddrs() []string {
|
||||
return tc.addrs("cluster")
|
||||
}
|
||||
|
||||
func (tc *TestController) addrs(purpose string) []string {
|
||||
var prefix string
|
||||
switch purpose {
|
||||
case "api":
|
||||
if tc.apiAddrs != nil {
|
||||
return tc.apiAddrs
|
||||
}
|
||||
prefix = "http://"
|
||||
case "cluster":
|
||||
if tc.clusterAddrs != nil {
|
||||
return tc.clusterAddrs
|
||||
}
|
||||
}
|
||||
|
||||
addrs := make([]string, 0, len(tc.b.Listeners))
|
||||
for _, listener := range tc.b.Listeners {
|
||||
if listener.Config.Purpose[0] == "api" {
|
||||
if listener.Config.Purpose[0] == purpose {
|
||||
tcpAddr, ok := listener.Mux.Addr().(*net.TCPAddr)
|
||||
if !ok {
|
||||
tc.t.Fatal("could not parse address as a TCP addr")
|
||||
}
|
||||
addr := fmt.Sprintf("http://%s:%d", tcpAddr.IP.String(), tcpAddr.Port)
|
||||
tc.addrs = append(tc.addrs, addr)
|
||||
addr := fmt.Sprintf("%s%s:%d", prefix, tcpAddr.IP.String(), tcpAddr.Port)
|
||||
addrs = append(addrs, addr)
|
||||
}
|
||||
}
|
||||
|
||||
return tc.addrs
|
||||
switch purpose {
|
||||
case "api":
|
||||
tc.apiAddrs = addrs
|
||||
case "cluster":
|
||||
tc.clusterAddrs = addrs
|
||||
}
|
||||
|
||||
return addrs
|
||||
}
|
||||
|
||||
func (tc *TestController) buildClient() {
|
||||
@@ -90,7 +127,7 @@ func (tc *TestController) Shutdown() {
|
||||
tc.cancel()
|
||||
|
||||
if tc.c != nil {
|
||||
if err := tc.c.Shutdown(); err != nil {
|
||||
if err := tc.c.Shutdown(false); err != nil {
|
||||
tc.t.Error(err)
|
||||
}
|
||||
}
|
||||
@@ -127,6 +164,10 @@ type TestControllerOpts struct {
|
||||
// database
|
||||
DisableDatabaseCreation bool
|
||||
|
||||
// If set, instead of creating a dev database, it will connect to an
|
||||
// existing database given the url
|
||||
DatabaseUrl string
|
||||
|
||||
// If true, the controller will not be started
|
||||
DisableAutoStart bool
|
||||
|
||||
@@ -134,6 +175,19 @@ type TestControllerOpts struct {
|
||||
// performed but they won't cause 403 Forbidden. Useful for API-level
|
||||
// testing to avoid a lot of faff.
|
||||
DisableAuthorizationFailures bool
|
||||
|
||||
// The controller KMS to use, or one will be created
|
||||
ControllerKMS wrapping.Wrapper
|
||||
|
||||
// The worker auth KMS to use, or one will be created
|
||||
WorkerAuthKMS wrapping.Wrapper
|
||||
|
||||
// The name to use for the controller, otherwise one will be randomly
|
||||
// generated, unless provided in a non-nil Config
|
||||
Name string
|
||||
|
||||
// The logger to use, or one will be created
|
||||
Logger hclog.Logger
|
||||
}
|
||||
|
||||
func NewTestController(t *testing.T, opts *TestControllerOpts) *TestController {
|
||||
@@ -162,6 +216,7 @@ func NewTestController(t *testing.T, opts *TestControllerOpts) *TestController {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
opts.Config.Controller.Name = opts.Name
|
||||
}
|
||||
|
||||
// Set default org ID, preferring one passed in from opts over config
|
||||
@@ -182,24 +237,52 @@ func NewTestController(t *testing.T, opts *TestControllerOpts) *TestController {
|
||||
}
|
||||
|
||||
// Start a logger
|
||||
tc.b.Logger = hclog.New(&hclog.LoggerOptions{
|
||||
Level: hclog.Trace,
|
||||
})
|
||||
tc.b.Logger = opts.Logger
|
||||
if tc.b.Logger == nil {
|
||||
tc.b.Logger = hclog.New(&hclog.LoggerOptions{
|
||||
Level: hclog.Trace,
|
||||
})
|
||||
}
|
||||
|
||||
if opts.Config.Controller == nil {
|
||||
opts.Config.Controller = new(config.Controller)
|
||||
}
|
||||
if opts.Config.Controller.Name == "" {
|
||||
opts.Config.Controller.Name, err = base62.Random(5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tc.b.Logger.Info("controller name generated", "name", opts.Config.Controller.Name)
|
||||
}
|
||||
tc.name = opts.Config.Controller.Name
|
||||
|
||||
// Set up KMSes
|
||||
if err := tc.b.SetupKMSes(nil, opts.Config.SharedConfig, []string{"controller", "worker-auth"}); err != nil {
|
||||
t.Fatal(err)
|
||||
switch {
|
||||
case opts.ControllerKMS != nil && opts.WorkerAuthKMS != nil:
|
||||
tc.b.ControllerKMS = opts.ControllerKMS
|
||||
tc.b.WorkerAuthKMS = opts.WorkerAuthKMS
|
||||
case opts.ControllerKMS == nil && opts.WorkerAuthKMS == nil:
|
||||
if err := tc.b.SetupKMSes(nil, opts.Config.SharedConfig, []string{"controller", "worker-auth"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
default:
|
||||
t.Fatal("either controller and worker auth KMS must both be set, or neither")
|
||||
}
|
||||
|
||||
// Ensure the listeners use random port allocation
|
||||
for _, listener := range opts.Config.Listeners {
|
||||
listener.RandomPort = true
|
||||
}
|
||||
if err := tc.b.SetupListeners(nil, opts.Config.SharedConfig); err != nil {
|
||||
if err := tc.b.SetupListeners(nil, opts.Config.SharedConfig, []string{"api", "cluster"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !opts.DisableDatabaseCreation {
|
||||
if opts.DatabaseUrl != "" {
|
||||
tc.b.DatabaseUrl = opts.DatabaseUrl
|
||||
if err := tc.b.ConnectToDatabase("postgres"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else if !opts.DisableDatabaseCreation {
|
||||
if err := tc.b.CreateDevDatabase("postgres"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -228,3 +311,30 @@ func NewTestController(t *testing.T, opts *TestControllerOpts) *TestController {
|
||||
|
||||
return tc
|
||||
}
|
||||
|
||||
func (tc *TestController) AddClusterControllerMember(t *testing.T, opts *TestControllerOpts) *TestController {
|
||||
if opts == nil {
|
||||
opts = new(TestControllerOpts)
|
||||
}
|
||||
nextOpts := &TestControllerOpts{
|
||||
DatabaseUrl: tc.c.conf.DatabaseUrl,
|
||||
DefaultAuthMethodId: tc.c.conf.DevAuthMethodId,
|
||||
DefaultOrgId: tc.c.conf.DefaultOrgId,
|
||||
ControllerKMS: tc.c.conf.ControllerKMS,
|
||||
WorkerAuthKMS: tc.c.conf.WorkerAuthKMS,
|
||||
Name: opts.Name,
|
||||
Logger: tc.c.conf.Logger,
|
||||
}
|
||||
if opts.Logger != nil {
|
||||
nextOpts.Logger = opts.Logger
|
||||
}
|
||||
if nextOpts.Name == "" {
|
||||
var err error
|
||||
nextOpts.Name, err = base62.Random(5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextOpts.Logger.Info("controller name generated", "name", nextOpts.Name)
|
||||
}
|
||||
return NewTestController(t, nextOpts)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/cmd/base"
|
||||
@@ -14,17 +15,29 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type workerAuthEntry struct {
|
||||
*base.WorkerAuthInfo
|
||||
conn net.Conn
|
||||
}
|
||||
|
||||
func (c Controller) validateWorkerTLS(hello *tls.ClientHelloInfo) (*tls.Config, error) {
|
||||
for _, p := range hello.SupportedProtos {
|
||||
switch {
|
||||
case strings.HasPrefix(p, "v1workerauth-"):
|
||||
return c.v1WorkerAuthConfig(hello.SupportedProtos)
|
||||
tlsConf, workerInfo, err := c.v1WorkerAuthConfig(hello.SupportedProtos)
|
||||
if err == nil {
|
||||
// Set the info we need to prevent replays
|
||||
c.workerAuthCache.Set(workerInfo.ConnectionNonce, &workerAuthEntry{
|
||||
WorkerAuthInfo: workerInfo,
|
||||
}, 0)
|
||||
}
|
||||
return tlsConf, err
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (c Controller) v1WorkerAuthConfig(protos []string) (*tls.Config, error) {
|
||||
func (c Controller) v1WorkerAuthConfig(protos []string) (*tls.Config, *base.WorkerAuthInfo, error) {
|
||||
var firstMatchProto string
|
||||
var encString string
|
||||
for _, p := range protos {
|
||||
@@ -37,32 +50,32 @@ func (c Controller) v1WorkerAuthConfig(protos []string) (*tls.Config, error) {
|
||||
}
|
||||
}
|
||||
if firstMatchProto == "" {
|
||||
return nil, errors.New("no matching proto found")
|
||||
return nil, nil, errors.New("no matching proto found")
|
||||
}
|
||||
marshaledEncInfo, err := base64.RawStdEncoding.DecodeString(encString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
encInfo := new(wrapping.EncryptedBlobInfo)
|
||||
if err := proto.Unmarshal(marshaledEncInfo, encInfo); err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
marshaledInfo, err := c.conf.WorkerAuthKMS.Decrypt(context.Background(), encInfo, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
info := new(base.WorkerAuthCertInfo)
|
||||
info := new(base.WorkerAuthInfo)
|
||||
if err := json.Unmarshal(marshaledInfo, info); err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
rootCAs := x509.NewCertPool()
|
||||
if ok := rootCAs.AppendCertsFromPEM(info.CACertPEM); !ok {
|
||||
return nil, errors.New("unable to add ca cert to cert pool")
|
||||
return nil, info, errors.New("unable to add ca cert to cert pool")
|
||||
}
|
||||
tlsCert, err := tls.X509KeyPair(info.CertPEM, info.KeyPEM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, info, err
|
||||
}
|
||||
tlsConfig := &tls.Config{
|
||||
Certificates: []tls.Certificate{tlsCert},
|
||||
@@ -73,5 +86,5 @@ func (c Controller) v1WorkerAuthConfig(protos []string) (*tls.Config, error) {
|
||||
}
|
||||
tlsConfig.BuildNameToCertificate()
|
||||
|
||||
return tlsConfig, nil
|
||||
return tlsConfig, info, nil
|
||||
}
|
||||
Reference in new issue
Block a user