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 69 70 71 72 73 74 75 76 77 78
|
//go:build windows
// +build windows
package fakeworkloadapi
import (
"crypto/rand"
"fmt"
"math"
"math/big"
"net"
"strings"
"testing"
"github.com/Microsoft/go-winio"
"github.com/spiffe/go-spiffe/v2/proto/spiffe/workload"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
)
var maxUint64 = maxBigUint64()
func NewWithNamedPipeListener(tb testing.TB) *WorkloadAPI {
w := &WorkloadAPI{
x509Chans: make(map[chan *workload.X509SVIDResponse]struct{}),
jwtBundlesChans: make(map[chan *workload.JWTBundlesResponse]struct{}),
}
listener, err := winio.ListenPipe(fmt.Sprintf(`\\.\pipe\go-spiffe-test-pipe-%x`, randUint64(tb)), nil)
require.NoError(tb, err)
server := grpc.NewServer()
workload.RegisterSpiffeWorkloadAPIServer(server, &workloadAPIWrapper{w: w})
w.wg.Add(1)
go func() {
defer w.wg.Done()
_ = server.Serve(listener)
}()
w.addr = getTargetName(listener.Addr())
tb.Logf("WorkloadAPI address: %s", w.addr)
w.server = server
return w
}
func GetPipeName(s string) string {
return strings.TrimPrefix(s, `\\.\pipe`)
}
func maxBigUint64() *big.Int {
n := big.NewInt(0)
return n.SetUint64(math.MaxUint64)
}
func randUint64(t testing.TB) uint64 {
n, err := rand.Int(rand.Reader, maxUint64)
if err != nil {
t.Fail()
}
return n.Uint64()
}
func newListener(tb testing.TB) (net.Listener, error) {
return winio.ListenPipe(fmt.Sprintf(`\\.\pipe\go-spiffe-test-pipe-%x`, randUint64(tb)), nil)
}
func getTargetName(addr net.Addr) string {
if addr.Network() == "pipe" {
// The go-winio library defines the network of a
// named pipe address as "pipe", but we use the
// "npipe" scheme for named pipes URLs.
return "npipe:" + GetPipeName(addr.String())
}
return fmt.Sprintf("%s://%s", addr.Network(), addr.String())
}
|