github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/apiserver/introspection_test.go (about)

     1  // Copyright 2017 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package apiserver_test
     5  
     6  import (
     7  	"io"
     8  	"net/http"
     9  
    10  	jc "github.com/juju/testing/checkers"
    11  	gc "gopkg.in/check.v1"
    12  
    13  	apitesting "github.com/juju/juju/apiserver/testing"
    14  	"github.com/juju/juju/core/permission"
    15  	"github.com/juju/juju/state"
    16  )
    17  
    18  type introspectionSuite struct {
    19  	apiserverBaseSuite
    20  	bob *state.User
    21  	url string
    22  }
    23  
    24  var _ = gc.Suite(&introspectionSuite{})
    25  
    26  func (s *introspectionSuite) SetUpTest(c *gc.C) {
    27  	s.apiserverBaseSuite.SetUpTest(c)
    28  	bob, err := s.State.AddUser("bob", "", "hunter2", "admin")
    29  	c.Assert(err, jc.ErrorIsNil)
    30  	s.bob = bob
    31  	s.url = s.server.URL + "/introspection/navel"
    32  }
    33  
    34  func (s *introspectionSuite) TestAccess(c *gc.C) {
    35  	s.testAccess(c, s.Owner.String(), ownerPassword)
    36  
    37  	model, err := s.State.Model()
    38  	c.Assert(err, jc.ErrorIsNil)
    39  	_, err = model.AddUser(
    40  		state.UserAccessSpec{
    41  			User:      s.bob.UserTag(),
    42  			CreatedBy: s.Owner,
    43  			Access:    permission.ReadAccess,
    44  		},
    45  	)
    46  	c.Assert(err, jc.ErrorIsNil)
    47  	s.testAccess(c, "user-bob", "hunter2")
    48  }
    49  
    50  func (s *introspectionSuite) testAccess(c *gc.C, tag, password string) {
    51  	resp := apitesting.SendHTTPRequest(c, apitesting.HTTPRequestParams{
    52  		Method:   "GET",
    53  		URL:      s.url,
    54  		Tag:      tag,
    55  		Password: password,
    56  	})
    57  	defer resp.Body.Close()
    58  	c.Assert(resp.StatusCode, gc.Equals, http.StatusOK)
    59  	content, err := io.ReadAll(resp.Body)
    60  	c.Assert(err, jc.ErrorIsNil)
    61  	c.Assert(string(content), gc.Equals, "gazing")
    62  }
    63  
    64  func (s *introspectionSuite) TestAccessDenied(c *gc.C) {
    65  	resp := apitesting.SendHTTPRequest(c, apitesting.HTTPRequestParams{
    66  		Method:   "GET",
    67  		URL:      s.url,
    68  		Tag:      "user-bob",
    69  		Password: "hunter2",
    70  	})
    71  	defer resp.Body.Close()
    72  	c.Assert(resp.StatusCode, gc.Equals, http.StatusForbidden)
    73  }