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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
|
package client_test
import (
"encoding/json"
"fmt"
"net/url"
"runtime"
"sync"
"time"
"github.com/juju/loggo"
gc "gopkg.in/check.v1"
"gopkg.in/goose.v1/client"
"gopkg.in/goose.v1/errors"
"gopkg.in/goose.v1/identity"
"gopkg.in/goose.v1/logging"
"gopkg.in/goose.v1/swift"
"gopkg.in/goose.v1/testing/httpsuite"
"gopkg.in/goose.v1/testservices"
"gopkg.in/goose.v1/testservices/identityservice"
"gopkg.in/goose.v1/testservices/openstackservice"
)
func registerLocalTests(authModes []identity.AuthMode) {
for _, authMode := range authModes {
gc.Suite(&localLiveSuite{
LiveTests: LiveTests{
authMode: authMode,
},
})
}
gc.Suite(&localHTTPSSuite{HTTPSuite: httpsuite.HTTPSuite{UseTLS: true}})
}
// localLiveSuite runs tests from LiveTests using a fake
// identity server that runs within the test process itself.
type localLiveSuite struct {
LiveTests
// The following attributes are for using testing doubles.
httpsuite.HTTPSuite
service testservices.HttpService
versionHandlers map[string]*versionHandler
}
func (s *localLiveSuite) SetUpSuite(c *gc.C) {
c.Logf("Using identity service test double")
s.HTTPSuite.SetUpSuite(c)
s.cred = &identity.Credentials{
URL: s.Server.URL,
User: "fred",
Secrets: "secret",
Region: "zone1.some region",
TenantName: "tenant",
ProjectDomain: "default",
}
var logMsg []string
switch s.authMode {
default:
panic("Invalid authentication method")
case identity.AuthKeyPair:
// The openstack test service sets up keypair authentication.
s.service, logMsg = openstackservice.New(s.cred, identity.AuthKeyPair, s.UseTLS)
// Add an additional endpoint so region filtering can be properly tested.
serviceDef := identityservice.Service{
V2: identityservice.V2Service{
Name: "nova",
Type: "compute",
Endpoints: []identityservice.Endpoint{
{PublicURL: "http://nova2", Region: "zone2.RegionOne"},
},
}}
s.service.(*openstackservice.Openstack).Identity.AddService(serviceDef)
case identity.AuthUserPass:
// The openstack test service sets up userpass authentication.
s.service, logMsg = openstackservice.New(s.cred, identity.AuthUserPass, s.UseTLS)
// Add an additional endpoint so region filtering can be properly tested.
serviceDef := identityservice.Service{
V2: identityservice.V2Service{
Name: "nova",
Type: "compute",
Endpoints: []identityservice.Endpoint{
{PublicURL: "http://nova2", Region: "zone2.RegionOne"},
},
}}
s.service.(*openstackservice.Openstack).Identity.AddService(serviceDef)
case identity.AuthUserPassV3:
// The openstack test service sets up userpass authentication.
s.service, logMsg = openstackservice.New(s.cred, identity.AuthUserPass, s.UseTLS)
// Add an additional endpoint so region filtering can be properly tested.
serviceDef := identityservice.Service{
V3: identityservice.V3Service{
Name: "nova",
Type: "compute",
Endpoints: identityservice.NewV3Endpoints("", "", "http://nova2", "zone2.RegionOne"),
}}
s.service.(*openstackservice.Openstack).Identity.AddService(serviceDef)
case identity.AuthLegacy:
legacy := identityservice.NewLegacy()
legacy.AddUser(s.cred.User, s.cred.Secrets, s.cred.TenantName, "default")
legacy.SetManagementURL("http://management.test.invalid/url")
s.service = legacy
}
for _, msg := range logMsg {
c.Logf(msg)
}
if s.authMode != identity.AuthLegacy {
s.service.SetupHTTP(nil)
}
s.versionHandlers = make(map[string]*versionHandler)
s.LiveTests.SetUpSuite(c)
}
func (s *localLiveSuite) TearDownSuite(c *gc.C) {
s.LiveTests.TearDownSuite(c)
s.HTTPSuite.TearDownSuite(c)
s.service.Stop()
}
func (s *localLiveSuite) SetUpTest(c *gc.C) {
s.HTTPSuite.SetUpTest(c)
s.LiveTests.SetUpTest(c)
if s.authMode == identity.AuthLegacy {
s.service.SetupHTTP(s.Mux)
}
}
func (s *localLiveSuite) TearDownTest(c *gc.C) {
s.LiveTests.TearDownTest(c)
s.HTTPSuite.TearDownTest(c)
}
// Additional tests to be run against the service double only go here.
func (s *localLiveSuite) TestInvalidRegion(c *gc.C) {
if s.authMode == identity.AuthLegacy {
c.Skip("legacy authentication doesn't use regions")
}
creds := &identity.Credentials{
User: "fred",
URL: s.service.(*openstackservice.Openstack).URLs["identity"],
Secrets: "secret",
Region: "invalid",
}
cl := client.NewClient(creds, s.authMode, nil)
err := cl.Authenticate()
c.Assert(err.Error(), gc.Matches, "(.|\n)*invalid region(.|\n)*")
}
// Test service lookup with inexact region matching.
func (s *localLiveSuite) TestInexactRegionMatch(c *gc.C) {
if s.authMode == identity.AuthLegacy {
c.Skip("legacy authentication doesn't use regions")
}
cl := client.NewClient(s.cred, s.authMode, nil)
err := cl.Authenticate()
serviceURL, err := cl.MakeServiceURL("compute", "v2", []string{})
c.Assert(err, gc.IsNil)
_, err = url.Parse(serviceURL)
c.Assert(err, gc.IsNil)
serviceURL, err = cl.MakeServiceURL("object-store", "", []string{})
c.Assert(err, gc.IsNil)
_, err = url.Parse(serviceURL)
c.Assert(err, gc.IsNil)
}
type fakeAuthenticator struct {
mu sync.Mutex
nrCallers int
// authStart is used as a gate to signal the fake authenticator that it can start.
authStart chan struct{}
port string // for startApiVersionMux()
}
func newAuthenticator(bufsize int, port string) *fakeAuthenticator {
return &fakeAuthenticator{
authStart: make(chan struct{}, bufsize),
port: port,
}
}
// doNewAuthenticator sets up the HTTP listener on 127.0.0.1:<port> for testing
// api version functionality within MakeServiceURL if we're using a fakeAuthenticator.
func (s *localLiveSuite) doNewAuthenticator(c *gc.C, bufsize int, port string) *fakeAuthenticator {
newAuth := newAuthenticator(bufsize, port)
newAuth.mu.Lock()
if _, ok := s.versionHandlers[port]; !ok {
var vh versionHandler
switch port {
case "3000":
vh.authBody = authInformationBody
case "3003":
vh.authBody = authValuesInformationBody
case "3005":
vh.authBody = ""
}
vh.port = port
c.Logf(startApiVersionMux(vh))
s.versionHandlers[port] = &vh
}
newAuth.mu.Unlock()
return newAuth
}
func (auth *fakeAuthenticator) Auth(creds *identity.Credentials) (*identity.AuthDetails, error) {
auth.mu.Lock()
auth.nrCallers++
auth.mu.Unlock()
// Wait till the test says the authenticator can proceed.
<-auth.authStart
runtime.Gosched()
defer func() {
auth.mu.Lock()
auth.nrCallers--
auth.mu.Unlock()
}()
auth.mu.Lock()
tooManyCallers := auth.nrCallers > 1
auth.mu.Unlock()
if tooManyCallers {
return nil, fmt.Errorf("Too many callers of Auth function")
}
URLs := make(map[string]identity.ServiceURLs)
endpoints := make(map[string]string)
endpoints["compute"] = fmt.Sprintf("http://127.0.0.1:%s", auth.port)
endpoints["object-store"] = fmt.Sprintf("http://127.0.0.1:%s/swift/v1", auth.port)
endpoints["juju-container-test"] = fmt.Sprintf("http://127.0.0.1:%s/swift/v1", auth.port)
URLs[creds.Region] = endpoints
return &identity.AuthDetails{
Token: "token",
TenantId: "tenant",
UserId: "1",
RegionServiceURLs: URLs,
}, nil
}
func (s *localLiveSuite) TestAuthenticationTimeout(c *gc.C) {
cl := client.NewClient(s.cred, s.authMode, nil)
defer client.SetAuthenticationTimeout(1 * time.Millisecond)()
auth := s.doNewAuthenticator(c, 0, "3003")
client.SetAuthenticator(cl, auth)
var err error
err = cl.Authenticate()
// Wake up the authenticator after we have timed out.
auth.authStart <- struct{}{}
c.Assert(errors.IsTimeout(err), gc.Equals, true)
}
func (s *localLiveSuite) assertAuthenticationSuccess(c *gc.C, port string) client.AuthenticatingClient {
cl := client.NewClient(s.cred, s.authMode, logging.LoggoLogger{loggo.GetLogger("goose.client")})
cl.SetRequiredServiceTypes([]string{"compute"})
defer client.SetAuthenticationTimeout(2 * time.Millisecond)()
auth := s.doNewAuthenticator(c, 1, port)
client.SetAuthenticator(cl, auth)
// Signal that the authenticator can proceed immediately.
auth.authStart <- struct{}{}
err := cl.Authenticate()
c.Assert(err, gc.IsNil)
// It completed with no error but check it also ran correctly.
c.Assert(cl.IsAuthenticated(), gc.Equals, true)
return cl
}
func (s *localLiveSuite) TestAuthenticationSuccess(c *gc.C) {
cl := s.assertAuthenticationSuccess(c, "3000")
URL, err := cl.MakeServiceURL("compute", "v2.0", nil)
c.Assert(err, gc.IsNil)
c.Assert(URL, gc.Equals, "http://127.0.0.1:3000/v2.0")
}
func checkAuthentication(cl client.AuthenticatingClient) error {
err := cl.Authenticate()
if err != nil {
return err
}
URL, err := cl.MakeServiceURL("compute", "v3", nil)
if err != nil {
return err
}
if URL != "http://127.0.0.1:3000/v3" {
return fmt.Errorf("Unexpected URL: %s", URL)
}
return nil
}
func (s *localLiveSuite) TestAuthenticationForbidsMultipleCallers(c *gc.C) {
if s.authMode == identity.AuthLegacy {
c.Skip("legacy authentication")
}
cl := client.NewClient(s.cred, s.authMode, nil)
cl.SetRequiredServiceTypes([]string{"compute"})
auth := s.doNewAuthenticator(c, 2, "3000")
client.SetAuthenticator(cl, auth)
// Signal that the authenticator can proceed immediately.
auth.authStart <- struct{}{}
auth.authStart <- struct{}{}
var allDone sync.WaitGroup
allDone.Add(2)
var err1, err2 error
go func() {
err1 = checkAuthentication(cl)
allDone.Done()
}()
go func() {
err2 = checkAuthentication(cl)
allDone.Done()
}()
allDone.Wait()
c.Assert(err1, gc.IsNil)
c.Assert(err2, gc.IsNil)
}
type configurableAuth struct {
regionsURLs map[string]identity.ServiceURLs
}
func NewConfigurableAuth(regionsURLData string) *configurableAuth {
auth := &configurableAuth{}
err := json.Unmarshal([]byte(regionsURLData), &auth.regionsURLs)
if err != nil {
panic(err)
}
return auth
}
func (auth *configurableAuth) Auth(creds *identity.Credentials) (*identity.AuthDetails, error) {
return &identity.AuthDetails{
Token: "token",
TenantId: "tenant",
UserId: "1",
RegionServiceURLs: auth.regionsURLs,
}, nil
}
type authRegionTest struct {
region string
regionURLInfo string
errorMsg string
}
var missingEndpointMsgf = "(.|\n)*the configured region %q does not allow access to all required services, namely: %s(.|\n)*access to these services is missing: %s"
var missingEndpointSuggestRegionMsgf = "(.|\n)*the configured region %q does not allow access to all required services, namely: %s(.|\n)*access to these services is missing: %s(.|\n)*one of these regions may be suitable instead: %s"
var invalidRegionMsgf = "(.|\n)*invalid region %q"
var authRegionTests = []authRegionTest{
{
"a.region.1",
`{"a.region.1":{"compute":"http://foo"}}`,
fmt.Sprintf(missingEndpointMsgf, "a.region.1", "compute, object-store", "object-store"),
},
{
"b.region.1",
`{"a.region.1":{"compute":"http://foo"}}`,
fmt.Sprintf(invalidRegionMsgf, "b.region.1"),
},
{
"b.region.1",
`{"a.region.1":{"compute":"http://foo"}, "region.1":{"object-store":"http://foobar"}}`,
fmt.Sprintf(missingEndpointSuggestRegionMsgf, "b.region.1", "compute, object-store", "compute", "a.region.1"),
},
{
"region.1",
`{"a.region.1":{"compute":"http://foo"}, "region.1":{"object-store":"http://foobar"}}`,
fmt.Sprintf(missingEndpointSuggestRegionMsgf, "region.1", "compute, object-store", "compute", "a.region.1"),
},
}
func (s *localLiveSuite) TestNonAccessibleServiceType(c *gc.C) {
if s.authMode == identity.AuthLegacy {
c.Skip("legacy authentication")
}
for _, at := range authRegionTests {
s.cred.Region = at.region
cl := client.NewClient(s.cred, s.authMode, nil)
auth := NewConfigurableAuth(at.regionURLInfo)
client.SetAuthenticator(cl, auth)
err := cl.Authenticate()
c.Assert(err, gc.ErrorMatches, at.errorMsg)
}
}
type localHTTPSSuite struct {
// The following attributes are for using testing doubles.
httpsuite.HTTPSuite
service testservices.HttpService
cred *identity.Credentials
}
func (s *localHTTPSSuite) SetUpSuite(c *gc.C) {
c.Logf("Using identity service test double")
s.HTTPSuite.SetUpSuite(c)
c.Assert(s.Server.URL[:8], gc.Equals, "https://")
s.cred = &identity.Credentials{
User: "fred",
Secrets: "secret",
Region: "zone1.some region",
TenantName: "tenant",
}
// The openstack test service sets up userpass authentication.
var logMsg []string
s.service, logMsg = openstackservice.New(s.cred, identity.AuthUserPass, s.UseTLS)
for _, msg := range logMsg {
c.Logf(msg)
}
// Add an additional endpoint so region filtering can be properly tested.
serviceDef := identityservice.Service{
V2: identityservice.V2Service{
Name: "nova",
Type: "compute",
Endpoints: []identityservice.Endpoint{
{PublicURL: "https://nova2", Region: "zone2.RegionOne"},
},
}}
s.service.(*openstackservice.Openstack).Identity.AddService(serviceDef)
s.service.SetupHTTP(nil)
}
func (s *localHTTPSSuite) TearDownSuite(c *gc.C) {
s.HTTPSuite.TearDownSuite(c)
s.service.Stop()
}
func (s *localHTTPSSuite) SetUpTest(c *gc.C) {
s.HTTPSuite.SetUpTest(c)
}
func (s *localHTTPSSuite) TearDownTest(c *gc.C) {
s.HTTPSuite.TearDownTest(c)
}
func (s *localHTTPSSuite) TestDefaultClientRefusesSelfSigned(c *gc.C) {
cl := client.NewClient(s.cred, identity.AuthUserPass, nil)
err := cl.Authenticate()
c.Assert(err, gc.ErrorMatches, "(.|\n)*x509: certificate signed by unknown authority")
}
func (s *localHTTPSSuite) TestNonValidatingClientAcceptsSelfSigned(c *gc.C) {
cl := client.NewNonValidatingClient(s.cred, identity.AuthUserPass, nil)
err := cl.Authenticate()
c.Assert(err, gc.IsNil)
// Requests into this client should be https:// URLs
swiftURL, err := cl.MakeServiceURL("object-store", "", []string{"test_container"})
c.Assert(err, gc.IsNil)
c.Assert(swiftURL[:8], gc.Equals, "https://")
// We use swiftClient.CreateContainer to test a Binary request
swiftClient := swift.New(cl)
c.Assert(swiftClient.CreateContainer("test_container", swift.Private), gc.IsNil)
// And we use List to test the JsonRequest
contents, err := swiftClient.List("test_container", "", "", "", 0)
c.Assert(err, gc.IsNil)
c.Check(contents, gc.DeepEquals, []swift.ContainerContents{})
}
func (s *localHTTPSSuite) setupPublicContainer(c *gc.C) string {
// First set up a container that can be read publically
authClient := client.NewNonValidatingClient(s.cred, identity.AuthUserPass, nil)
authSwift := swift.New(authClient)
err := authSwift.CreateContainer("test_container", swift.PublicRead)
c.Assert(err, gc.IsNil)
baseURL, err := authClient.MakeServiceURL("object-store", "", nil)
c.Assert(err, gc.IsNil)
c.Assert(baseURL[:8], gc.Equals, "https://")
return baseURL
}
func (s *localHTTPSSuite) TestDefaultPublicClientRefusesSelfSigned(c *gc.C) {
baseURL := s.setupPublicContainer(c)
swiftClient := swift.New(client.NewPublicClient(baseURL, nil))
contents, err := swiftClient.List("test_container", "", "", "", 0)
c.Assert(err, gc.ErrorMatches, "(.|\n)*x509: certificate signed by unknown authority")
c.Assert(contents, gc.DeepEquals, []swift.ContainerContents(nil))
}
func (s *localHTTPSSuite) TestNonValidatingPublicClientAcceptsSelfSigned(c *gc.C) {
baseURL := s.setupPublicContainer(c)
swiftClient := swift.New(client.NewNonValidatingPublicClient(baseURL, nil))
contents, err := swiftClient.List("test_container", "", "", "", 0)
c.Assert(err, gc.IsNil)
c.Assert(contents, gc.DeepEquals, []swift.ContainerContents{})
}
func (s *localHTTPSSuite) TestAuthDiscover(c *gc.C) {
cl := client.NewNonValidatingClient(s.cred, identity.AuthUserPass, nil)
options, err := cl.IdentityAuthOptions()
c.Assert(err, gc.IsNil)
c.Assert(options, gc.DeepEquals, identity.AuthOptions{identity.AuthOption{Mode: 3, Endpoint: s.cred.URL + "/v3/"}, identity.AuthOption{Mode: 1, Endpoint: s.cred.URL + "/v2.0/"}})
}
|