github.com/arunkumar7540/cli@v6.45.0+incompatible/integration/helpers/fake_server.go (about)

     1  package helpers
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"time"
     7  
     8  	. "github.com/onsi/gomega"
     9  	. "github.com/onsi/gomega/gexec"
    10  	. "github.com/onsi/gomega/ghttp"
    11  )
    12  
    13  const (
    14  	DefaultV2Version string = "2.131.0"
    15  	DefaultV3Version string = "3.66.0"
    16  )
    17  
    18  // StartAndTargetServerWithAPIVersions starts and targets a server with the given V2 and V3
    19  // API versions.
    20  func StartAndTargetServerWithAPIVersions(v2Version string, v3Version string) *Server {
    21  	server := StartServerWithAPIVersions(v2Version, v3Version)
    22  	Eventually(CF("api", server.URL(), "--skip-ssl-validation")).Should(Exit(0))
    23  
    24  	return server
    25  }
    26  
    27  // StartServerWithMinimumCLIVersion starts a server with the default V2 and V3
    28  // API versions and the given minimum CLI version.
    29  func StartServerWithMinimumCLIVersion(minCLIVersion string) *Server {
    30  	return startServerWithVersions(DefaultV2Version, DefaultV3Version, &minCLIVersion)
    31  }
    32  
    33  // StartServerWithAPIVersions starts a server with the given V2 and V3
    34  // API versions
    35  func StartServerWithAPIVersions(v2Version string, v3Version string) *Server {
    36  	return startServerWithVersions(v2Version, v3Version, nil)
    37  }
    38  
    39  func startServerWithVersions(v2Version string, v3Version string, minimumCLIVersion *string) *Server {
    40  	server := NewTLSServer()
    41  
    42  	rootResponse := fmt.Sprintf(`{
    43     "links": {
    44        "self": {
    45           "href": "%[1]s"
    46        },
    47        "cloud_controller_v2": {
    48           "href": "%[1]s/v2",
    49           "meta": {
    50              "version": "%[2]s"
    51           }
    52        },
    53        "cloud_controller_v3": {
    54           "href": "%[1]s/v3",
    55           "meta": {
    56              "version": "%[3]s"
    57           }
    58        },
    59        "network_policy_v0": {
    60           "href": "%[1]s/networking/v0/external"
    61        },
    62        "network_policy_v1": {
    63           "href": "%[1]s/networking/v1/external"
    64        },
    65        "uaa": {
    66           "href": "%[1]s"
    67        },
    68        "logging": {
    69           "href": "wss://unused:443"
    70        },
    71        "app_ssh": {
    72           "href": "unused:2222",
    73           "meta": {
    74              "host_key_fingerprint": "unused",
    75              "oauth_client": "ssh-proxy"
    76           }
    77        }
    78     }
    79   }`, server.URL(), v2Version, v3Version)
    80  
    81  	v2InfoResponse := struct {
    82  		APIVersion            string  `json:"api_version"`
    83  		AuthorizationEndpoint string  `json:"authorization_endpoint"`
    84  		MinCLIVersion         *string `json:"min_cli_version"`
    85  	}{
    86  		APIVersion:            v2Version,
    87  		AuthorizationEndpoint: server.URL(),
    88  		MinCLIVersion:         minimumCLIVersion}
    89  
    90  	server.RouteToHandler(http.MethodGet, "/v2/info", RespondWithJSONEncoded(http.StatusOK, v2InfoResponse))
    91  
    92  	v3Response := fmt.Sprintf(`{"links": {
    93  			"organizations": {
    94  				"href": "%s/v3/organizations"
    95  			}
    96  		}}`, server.URL())
    97  	server.RouteToHandler(http.MethodGet, "/v3", func(res http.ResponseWriter, req *http.Request) {
    98  		res.WriteHeader(http.StatusOK)
    99  		res.Write([]byte(v3Response))
   100  	})
   101  
   102  	server.RouteToHandler(http.MethodGet, "/login", func(res http.ResponseWriter, req *http.Request) {
   103  		res.WriteHeader(http.StatusOK)
   104  		res.Write([]byte(`{"links":{}}`))
   105  	})
   106  	server.RouteToHandler(http.MethodGet, "/", func(res http.ResponseWriter, req *http.Request) {
   107  		res.WriteHeader(http.StatusOK)
   108  		res.Write([]byte(rootResponse))
   109  	})
   110  
   111  	return server
   112  }
   113  
   114  // AddMfa adds a mock handler to the given server which returns a login response and a 200 status code
   115  // on GET requests to the /login endpoint. It adds another mock handler to validate the given password and MFA token
   116  // upon POST requests to /oauth/token.
   117  func AddMfa(server *Server, password string, mfaToken string) {
   118  	getLoginResponse := fmt.Sprintf(`{
   119      "app": {
   120          "version": "4.28.0"
   121      },
   122      "showLoginLinks": true,
   123      "links": {
   124          "uaa": "%[1]s",
   125          "passwd": "/forgot_password",
   126          "login": "%[1]s",
   127          "register": "/create_account"
   128      },
   129      "zone_name": "uaa",
   130      "entityID": "some-host-name.example.com",
   131      "commit_id": "8917980",
   132      "idpDefinitions": {},
   133      "prompts": {
   134          "username": [
   135              "text",
   136              "Email"
   137          ],
   138          "password": [
   139              "password",
   140              "Password"
   141          ],
   142          "passcode": [
   143              "password",
   144              "Temporary Authentication Code ( Get one at %[1]s/passcode )"
   145          ],
   146          "mfaCode": [
   147              "password",
   148              "MFA Code ( Register at %[1]s )"
   149          ]
   150      },
   151      "timestamp": "2019-02-19T18:08:02+0000"
   152  }`, server.URL())
   153  
   154  	server.RouteToHandler(http.MethodGet, "/login",
   155  		RespondWith(http.StatusOK, getLoginResponse),
   156  	)
   157  
   158  	server.RouteToHandler(http.MethodPost, "/oauth/token", makeMFAValidator(password, mfaToken))
   159  
   160  }
   161  
   162  func makeMFAValidator(password string, mfaToken string) http.HandlerFunc {
   163  	return func(res http.ResponseWriter, req *http.Request) {
   164  		Expect(req.ParseForm()).To(Succeed())
   165  		rightPassword := len(req.Form["password"]) == 1 && req.Form["password"][0] == password
   166  		rightCode := len(req.Form["mfaCode"]) == 1 && req.Form["mfaCode"][0] == mfaToken
   167  
   168  		if rightPassword && rightCode {
   169  			res.WriteHeader(http.StatusOK)
   170  			res.Write([]byte(`{
   171      "access_token": "some-access-token",
   172      "token_type": "bearer",
   173      "id_token": "some-id-token",
   174      "refresh_token": "some-refresh-token",
   175      "expires_in": 599,
   176      "scope": "openid routing.router_groups.write scim.read cloud_controller.admin uaa.user routing.router_groups.read cloud_controller.read password.write cloud_controller.write network.admin doppler.firehose scim.write",
   177      "jti": "66e46003f28e44c8a6582f6d6e44753f"
   178  }`))
   179  			return
   180  		}
   181  		res.WriteHeader(http.StatusUnauthorized)
   182  	}
   183  }
   184  
   185  // AddLoginRoutes adds a mock handler to the given server which returns an access token and a 200 status code
   186  // on POST requests to /oauth/token.
   187  func AddLoginRoutes(s *Server) {
   188  	s.RouteToHandler("POST", "/oauth/token", RespondWith(http.StatusOK,
   189  		fmt.Sprintf(`{
   190  			"access_token": "%s",
   191  			"expires_in": 599,
   192  			"id_token": "some-other-token",
   193  			"jti": "some-other-string",
   194  			"refresh_token": "some-refresh-token",
   195  			"scope": "openid routing.router_groups.write scim.read cloud_controller.admin uaa.user routing.router_groups.read cloud_controller.read password.write cloud_controller.write network.admin doppler.firehose scim.write",
   196  			"token_type": "bearer"
   197  		 }`, BuildTokenString(time.Now()))),
   198  	)
   199  }