[XAPID-1037] add more tests and increase coverage
diff --git a/api.go b/api.go
index 784ffcf..4da5b50 100644
--- a/api.go
+++ b/api.go
@@ -20,14 +20,13 @@
"io"
"io/ioutil"
"net/http"
- "strconv"
"strings"
)
type apiManagerInterface interface {
InitAPI()
handleRequest(w http.ResponseWriter, r *http.Request)
- verifyAPIKey(verifyApiKeyReq VerifyApiKeyRequest) ([]byte, error)
+ verifyAPIKey(verifyApiKeyReq VerifyApiKeyRequest) (*VerifyApiKeySuccessResponse, *ErrorResponse)
}
type apiManager struct {
@@ -47,27 +46,32 @@
// handle client API
func (a *apiManager) handleRequest(w http.ResponseWriter, r *http.Request) {
+
w.Header().Set("Content-Type", "application/json")
- verifyApiKeyReq, err := validateRequest(r.Body, w)
- if err != nil {
- return
- }
- b, err := a.verifyAPIKey(verifyApiKeyReq)
+ var returnValue interface{}
- if err != nil {
- respStatusCode, atoierr := strconv.Atoi(err.Error())
- if atoierr != nil {
- w.WriteHeader(http.StatusInternalServerError)
+ if verifyApiKeyReq, err := validateRequest(r.Body, w); err == nil {
+ verifyApiKeyResponse, errorResponse := a.verifyAPIKey(verifyApiKeyReq)
+
+ if errorResponse != nil {
+ setResponseHeader(errorResponse, w)
+ returnValue = errorResponse
} else {
- w.WriteHeader(respStatusCode)
+ returnValue = verifyApiKeyResponse
}
+ b, _ := json.Marshal(returnValue)
+ log.Debugf("handleVerifyAPIKey result %s", b)
+ w.Write(b)
}
+}
- log.Debugf("handleVerifyAPIKey result %s", b)
-
- w.Write(b)
- return
+func setResponseHeader(errorResponse *ErrorResponse, w http.ResponseWriter) {
+ if errorResponse.StatusCode != 0 {
+ w.WriteHeader(errorResponse.StatusCode)
+ } else {
+ w.WriteHeader(http.StatusInternalServerError)
+ }
}
func validateRequest(requestBody io.ReadCloser, w http.ResponseWriter) (VerifyApiKeyRequest, error) {
@@ -90,11 +94,8 @@
log.Debug(verifyApiKeyReq)
// 2. verify params
- // TODO : make this method of verifyApiKeyReq struct
- // TODO : move validation to verifyApiKey struct validate method
- if verifyApiKeyReq.Action == "" || verifyApiKeyReq.ApiProxyName == "" || verifyApiKeyReq.OrganizationName == "" || verifyApiKeyReq.EnvironmentName == "" || verifyApiKeyReq.Key == "" {
- // TODO : set correct missing fields in error response
- errorResponse, _ := json.Marshal(errorResponse("Bad_REQUEST", "Missing element", http.StatusBadRequest))
+ if isValid, err := verifyApiKeyReq.validate(); !isValid {
+ errorResponse, _ := json.Marshal(errorResponse("Bad_REQUEST", err.Error(), http.StatusBadRequest))
w.WriteHeader(http.StatusBadRequest)
w.Write(errorResponse)
return verifyApiKeyReq, errors.New("Bad_REQUEST")
@@ -103,12 +104,13 @@
}
// returns []byte to be written to client
-func (apiM apiManager) verifyAPIKey(verifyApiKeyReq VerifyApiKeyRequest) ([]byte, error) {
+func (apiM apiManager) verifyAPIKey(verifyApiKeyReq VerifyApiKeyRequest) (*VerifyApiKeySuccessResponse, *ErrorResponse) {
dataWrapper := VerifyApiKeyRequestResponseDataWrapper{
verifyApiKeyRequest: verifyApiKeyReq,
}
dataWrapper.verifyApiKeySuccessResponse.ClientId.ClientId = verifyApiKeyReq.Key
+ dataWrapper.verifyApiKeySuccessResponse.Environment = verifyApiKeyReq.EnvironmentName
err := apiM.dbMan.getApiKeyDetails(&dataWrapper)
@@ -117,13 +119,13 @@
reason := "API Key verify failed for (" + verifyApiKeyReq.Key + ", " + verifyApiKeyReq.OrganizationName + ")"
errorCode := "oauth.v2.InvalidApiKey"
errResponse := errorResponse(reason, errorCode, http.StatusOK)
- return json.Marshal(errResponse)
+ return nil, &errResponse
case err != nil:
reason := err.Error()
errorCode := "SEARCH_INTERNAL_ERROR"
errResponse := errorResponse(reason, errorCode, http.StatusInternalServerError)
- return json.Marshal(errResponse)
+ return nil, &errResponse
}
dataWrapper.verifyApiKeySuccessResponse.ApiProduct = shortListApiProduct(dataWrapper.apiProducts, verifyApiKeyReq)
@@ -132,16 +134,14 @@
*/
errResponse := apiM.performValidations(dataWrapper)
if errResponse != nil {
- return json.Marshal(&errResponse)
+ return nil, errResponse
}
apiM.enrichAttributes(&dataWrapper)
setDevOrCompanyInResponseBasedOnCtype(dataWrapper.ctype, dataWrapper.tempDeveloperDetails, &dataWrapper.verifyApiKeySuccessResponse)
- resp := dataWrapper.verifyApiKeySuccessResponse
-
- return json.Marshal(resp)
+ return &dataWrapper.verifyApiKeySuccessResponse, nil
}
func setDevOrCompanyInResponseBasedOnCtype(ctype string, tempDeveloperDetails DeveloperDetails, response *VerifyApiKeySuccessResponse) {
@@ -150,6 +150,7 @@
} else {
response.Company = CompanyDetails{
Id: tempDeveloperDetails.Id,
+ Name: tempDeveloperDetails.FirstName,
DisplayName: tempDeveloperDetails.UserName,
Status: tempDeveloperDetails.Status,
CreatedAt: tempDeveloperDetails.CreatedAt,
@@ -207,11 +208,17 @@
if !strings.EqualFold("APPROVED", clientIdDetails.Status) {
reason = "API Key verify failed for (" + verifyApiKeyReq.Key + ", " + verifyApiKeyReq.OrganizationName + ")"
errorCode = "oauth.v2.ApiKeyNotApproved"
+ log.Debug("Validation error occoured ", errorCode, " ", reason)
+ ee := errorResponse(reason, errorCode, http.StatusOK)
+ return &ee
}
if !strings.EqualFold("APPROVED", appDetails.Status) {
reason = "API Key verify failed for (" + verifyApiKeyReq.Key + ", " + verifyApiKeyReq.OrganizationName + ")"
errorCode = "keymanagement.service.invalid_client-app_not_approved"
+ log.Debug("Validation error occoured ", errorCode, " ", reason)
+ ee := errorResponse(reason, errorCode, http.StatusOK)
+ return &ee
}
if !strings.EqualFold("ACTIVE", tempDeveloperDetails.Status) {
@@ -220,31 +227,39 @@
if cType == "company" {
errorCode = "keymanagement.service.CompanyStatusNotActive"
}
+ log.Debug("Validation error occoured ", errorCode, " ", reason)
+ ee := errorResponse(reason, errorCode, http.StatusOK)
+ return &ee
}
if dataWrapper.verifyApiKeySuccessResponse.ApiProduct.Id == "" {
reason = "Path Validation Failed. Product not resolved"
errorCode = "oauth.v2.InvalidApiKeyForGivenResource"
+ log.Debug("Validation error occoured ", errorCode, " ", reason)
+ ee := errorResponse(reason, errorCode, http.StatusOK)
+ return &ee
}
result := len(apiProductDetails.Resources) == 0 || validatePath(apiProductDetails.Resources, verifyApiKeyReq.UriPath)
if !result {
reason = "Path Validation Failed (" + strings.Join(apiProductDetails.Resources, ", ") + " vs " + verifyApiKeyReq.UriPath + ")"
errorCode = "oauth.v2.InvalidApiKeyForGivenResource"
+ log.Debug("Validation error occoured ", errorCode, " ", reason)
+ ee := errorResponse(reason, errorCode, http.StatusOK)
+ return &ee
}
if verifyApiKeyReq.ValidateAgainstApiProxiesAndEnvs && (len(apiProductDetails.Apiproxies) > 0 && !contains(apiProductDetails.Apiproxies, verifyApiKeyReq.ApiProxyName)) {
reason = "Proxy Validation Failed (" + strings.Join(apiProductDetails.Apiproxies, ", ") + " vs " + verifyApiKeyReq.ApiProxyName + ")"
errorCode = "oauth.v2.InvalidApiKeyForGivenResource"
+ log.Debug("Validation error occoured ", errorCode, " ", reason)
+ ee := errorResponse(reason, errorCode, http.StatusOK)
+ return &ee
}
/* Verify if the ENV matches */
if verifyApiKeyReq.ValidateAgainstApiProxiesAndEnvs && (len(apiProductDetails.Environments) > 0 && !contains(apiProductDetails.Environments, verifyApiKeyReq.EnvironmentName)) {
reason = "ENV Validation Failed (" + strings.Join(apiProductDetails.Environments, ", ") + " vs " + verifyApiKeyReq.EnvironmentName + ")"
errorCode = "oauth.v2.InvalidApiKeyForGivenResource"
-
- }
-
- if errorCode != "" {
log.Debug("Validation error occoured ", errorCode, " ", reason)
ee := errorResponse(reason, errorCode, http.StatusOK)
return &ee
diff --git a/api_test.go b/api_test.go
index 5b1df1d..8ba4ebc 100644
--- a/api_test.go
+++ b/api_test.go
@@ -18,3 +18,283 @@
// 2. happy path for company
// 3. error case for developer / company
// 4. input request validation error case
+// 5. key not found case
+
+import (
+ "encoding/json"
+ "errors"
+ "github.com/30x/apid-core"
+ "github.com/30x/apid-core/factory"
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+ "io/ioutil"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strconv"
+ "strings"
+ "sync"
+)
+
+var (
+ testServer *httptest.Server
+)
+
+var _ = Describe("end to end tests", func() {
+ var dataTestTempDir string
+ var dbMan *dbManager
+
+ var _ = BeforeEach(func() {
+ var err error
+ dataTestTempDir, err = ioutil.TempDir(testTempDirBase, "api_test_sqlite3")
+ serviceFactoryForTest := factory.DefaultServicesFactory()
+ apid.Initialize(serviceFactoryForTest)
+ config := apid.Config()
+ config.Set("data_path", testTempDir)
+ config.Set("log_level", "DEBUG")
+ serviceFactoryForTest.Config().Set("local_storage_path", dataTestTempDir)
+
+ Expect(err).NotTo(HaveOccurred())
+
+ dbMan = &dbManager{
+ data: serviceFactoryForTest.Data(),
+ dbMux: sync.RWMutex{},
+ }
+ dbMan.setDbVersion(dataTestTempDir)
+ dbMan.initDb()
+
+ apiMan := apiManager{
+ dbMan: dbMan,
+ verifiersEndpoint: apiPath,
+ }
+
+ testServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if req.URL.Path == apiPath {
+ apiMan.handleRequest(w, req)
+ }
+ }))
+
+ })
+
+ Context("veriifyApiKey Api test ", func() {
+ It("should return validation error for missing input fields", func() {
+ var respObj ErrorResponse
+ reqInput := VerifyApiKeyRequest{
+ Key: "test",
+ }
+ jsonBody, _ := json.Marshal(reqInput)
+
+ responseBody, err := performTestOperation(string(jsonBody), 400)
+ Expect(err).ShouldNot(HaveOccurred())
+
+ json.Unmarshal(responseBody, &respObj)
+ Expect(respObj.ResponseMessage).Should(Equal("Bad_REQUEST"))
+ Expect(respObj.ResponseCode).Should(Equal("Missing mandatory fields in the request : action organizationName uriPath"))
+ })
+ It("should return validation error for inavlid key", func() {
+ var respObj ErrorResponse
+ reqInput := VerifyApiKeyRequest{
+ Key: "invalid-key",
+ Action: "verify",
+ OrganizationName: "apigee-mcrosrvc-client0001",
+ EnvironmentName: "test",
+ ApiProxyName: "DevApplication",
+ UriPath: "/zoho",
+
+ ValidateAgainstApiProxiesAndEnvs: true,
+ }
+ jsonBody, _ := json.Marshal(reqInput)
+
+ responseBody, err := performTestOperation(string(jsonBody), 200)
+ Expect(err).ShouldNot(HaveOccurred())
+
+ json.Unmarshal(responseBody, &respObj)
+ Expect(respObj.ResponseMessage).Should(Equal("API Key verify failed for (invalid-key, apigee-mcrosrvc-client0001)"))
+ Expect(respObj.ResponseCode).Should(Equal("oauth.v2.InvalidApiKey"))
+ })
+ It("should return validation error for inavlid env", func() {
+ setupApikeyDeveloperTestDb(dbMan.db)
+ var respObj ErrorResponse
+ reqInput := VerifyApiKeyRequest{
+ Key: "63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0",
+ Action: "verify",
+ OrganizationName: "apigee-mcrosrvc-client0001",
+ EnvironmentName: "prod",
+ ApiProxyName: "DevApplication",
+ UriPath: "/zoho",
+
+ ValidateAgainstApiProxiesAndEnvs: true,
+ }
+ jsonBody, _ := json.Marshal(reqInput)
+
+ responseBody, err := performTestOperation(string(jsonBody), 200)
+ Expect(err).ShouldNot(HaveOccurred())
+
+ json.Unmarshal(responseBody, &respObj)
+ Expect(respObj.ResponseMessage).Should(Equal("ENV Validation Failed (test vs prod)"))
+ Expect(respObj.ResponseCode).Should(Equal("oauth.v2.InvalidApiKeyForGivenResource"))
+ })
+ It("should return validation error for inavlid resource", func() {
+ setupApikeyDeveloperTestDb(dbMan.db)
+ var respObj ErrorResponse
+ reqInput := VerifyApiKeyRequest{
+ Key: "63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0",
+ Action: "verify",
+ OrganizationName: "apigee-mcrosrvc-client0001",
+ EnvironmentName: "test",
+ ApiProxyName: "DevApplication",
+ UriPath: "/google",
+
+ ValidateAgainstApiProxiesAndEnvs: true,
+ }
+ jsonBody, _ := json.Marshal(reqInput)
+
+ responseBody, err := performTestOperation(string(jsonBody), 200)
+ Expect(err).ShouldNot(HaveOccurred())
+
+ json.Unmarshal(responseBody, &respObj)
+ Expect(respObj.ResponseMessage).Should(Equal("Path Validation Failed. Product not resolved"))
+ Expect(respObj.ResponseCode).Should(Equal("oauth.v2.InvalidApiKeyForGivenResource"))
+ })
+ It("should return validation error for inavlid proxies", func() {
+ setupApikeyDeveloperTestDb(dbMan.db)
+ var respObj ErrorResponse
+ reqInput := VerifyApiKeyRequest{
+ Key: "63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0",
+ Action: "verify",
+ OrganizationName: "apigee-mcrosrvc-client0001",
+ EnvironmentName: "test",
+ ApiProxyName: "Invalid-proxy",
+ UriPath: "/zoho",
+
+ ValidateAgainstApiProxiesAndEnvs: true,
+ }
+ jsonBody, _ := json.Marshal(reqInput)
+
+ responseBody, err := performTestOperation(string(jsonBody), 200)
+ Expect(err).ShouldNot(HaveOccurred())
+
+ json.Unmarshal(responseBody, &respObj)
+ Expect(respObj.ResponseMessage).Should(Equal("Proxy Validation Failed (DevApplication, KeysApplication vs Invalid-proxy)"))
+ Expect(respObj.ResponseCode).Should(Equal("oauth.v2.InvalidApiKeyForGivenResource"))
+ })
+ It("should peform verify api key for developer happy path", func() {
+ setupApikeyDeveloperTestDb(dbMan.db)
+ var respObj VerifyApiKeySuccessResponse
+
+ reqInput := VerifyApiKeyRequest{
+ Action: "verify",
+ OrganizationName: "apigee-mcrosrvc-client0001",
+ Key: "63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0",
+ EnvironmentName: "test",
+ ApiProxyName: "DevApplication",
+ UriPath: "/zoho",
+
+ ValidateAgainstApiProxiesAndEnvs: true,
+ }
+ jsonBody, _ := json.Marshal(reqInput)
+
+ responseBody, err := performTestOperation(string(jsonBody), 200)
+ Expect(err).ShouldNot(HaveOccurred())
+
+ json.Unmarshal(responseBody, &respObj)
+ Expect(respObj.Developer.Id).Should(Equal("209ffd18-37e9-4a67-9e30-a5c40a534b6c"))
+ Expect(respObj.Developer.FirstName).Should(Equal("Woodre"))
+ Expect(respObj.Developer.CreatedAt).Should(Equal("2017-08-08 17:24:09.008+00:00"))
+ Expect(respObj.Developer.LastmodifiedAt).Should(Equal("2017-08-08 17:24:09.008+00:00"))
+ Expect(respObj.Developer.CreatedBy).Should(Equal("defaultUser"))
+ Expect(respObj.Developer.LastmodifiedBy).Should(Equal("defaultUser"))
+ Expect(len(respObj.Developer.Attributes)).Should(Equal(0))
+ Expect(respObj.Developer.Company).Should(Equal(""))
+ Expect(respObj.Developer.Status).Should(Equal("ACTIVE"))
+ Expect(respObj.Developer.UserName).Should(Equal("wilson"))
+ Expect(respObj.Developer.Email).Should(Equal("developer@apigee.com"))
+ Expect(respObj.Developer.LastName).Should(Equal("Wilson"))
+ Expect(len(respObj.Developer.Apps)).Should(Equal(0))
+
+ Expect(respObj.ClientId.ClientId).Should(Equal("63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0"))
+ Expect(respObj.ClientId.Status).Should(Equal("APPROVED"))
+ Expect(respObj.ClientId.Attributes[0].Name).Should(Equal("Device"))
+ Expect(respObj.ClientId.Attributes[0].Value).Should(Equal("ios"))
+ Expect(respObj.ClientId.ClientSecret).Should(Equal("Ui8dcyGW3lA04YdX"))
+ Expect(respObj.ClientId.RedirectURIs[0]).Should(Equal("www.apple.com"))
+
+ Expect(respObj.Company.Id).Should(Equal(""))
+
+ Expect(respObj.App.Id).Should(Equal("d371f05a-7c04-430c-b12d-26cf4e4d5d65"))
+
+ Expect(respObj.ApiProduct.Id).Should(Equal("24987a63-edb9-4d6b-9334-87e1d70df8e3"))
+
+ Expect(respObj.Environment).Should(Equal("test"))
+
+ })
+
+ It("should peform verify api key for company happy path", func() {
+ setupApikeyCompanyTestDb(dbMan.db)
+ var respObj VerifyApiKeySuccessResponse
+
+ reqInput := VerifyApiKeyRequest{
+ Action: "verify",
+ OrganizationName: "apigee-mcrosrvc-client0001",
+ Key: "63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0",
+ EnvironmentName: "test",
+ ApiProxyName: "DevApplication",
+ UriPath: "/zoho",
+
+ ValidateAgainstApiProxiesAndEnvs: true,
+ }
+ jsonBody, _ := json.Marshal(reqInput)
+
+ responseBody, err := performTestOperation(string(jsonBody), 200)
+ Expect(err).ShouldNot(HaveOccurred())
+
+ json.Unmarshal(responseBody, &respObj)
+ Expect(respObj.Developer.Id).Should(Equal(""))
+
+ Expect(respObj.Company.Id).Should(Equal("7834c683-9453-4389-b816-34ca24dfccd9"))
+ Expect(respObj.Company.Name).Should(Equal("DevCompany"))
+ Expect(respObj.Company.CreatedAt).Should(Equal("2017-08-05 19:54:12.359+00:00"))
+ Expect(respObj.Company.LastmodifiedAt).Should(Equal("2017-08-05 19:54:12.359+00:00"))
+ Expect(respObj.Company.CreatedBy).Should(Equal("defaultUser"))
+ Expect(respObj.Company.LastmodifiedBy).Should(Equal("defaultUser"))
+ Expect(len(respObj.Company.Attributes)).Should(Equal(1))
+ Expect(respObj.Company.Attributes[0].Name).Should(Equal("country"))
+ Expect(respObj.Company.Attributes[0].Value).Should(Equal("england"))
+ Expect(respObj.Company.DisplayName).Should(Equal("East India Company"))
+ Expect(respObj.Company.Status).Should(Equal("ACTIVE"))
+ Expect(len(respObj.Developer.Apps)).Should(Equal(0))
+
+ Expect(respObj.ClientId.ClientId).Should(Equal("63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0"))
+ Expect(respObj.ClientId.Status).Should(Equal("APPROVED"))
+ Expect(len(respObj.ClientId.Attributes)).Should(Equal(0))
+ Expect(respObj.ClientId.ClientSecret).Should(Equal("Ui8dcyGW3lA04YdX"))
+ Expect(respObj.ClientId.RedirectURIs[0]).Should(Equal("www.apple.com"))
+
+ Expect(respObj.Company.Id).Should(Equal("7834c683-9453-4389-b816-34ca24dfccd9"))
+
+ Expect(respObj.App.Id).Should(Equal("d371f05a-7c04-430c-b12d-26cf4e4d5d65"))
+
+ Expect(respObj.ApiProduct.Id).Should(Equal("24987a63-edb9-4d6b-9334-87e1d70df8e3"))
+
+ Expect(respObj.Environment).Should(Equal("test"))
+ })
+
+ })
+})
+
+func performTestOperation(jsonBody string, expectedResponseCode int) ([]byte, error) {
+ uri, err := url.Parse(testServer.URL)
+ uri.Path = apiPath
+ client := &http.Client{}
+ httpReq, err := http.NewRequest("POST", uri.String(), strings.NewReader(string(jsonBody)))
+ httpReq.Header.Set("Content-Type", "application/json")
+ res, err := client.Do(httpReq)
+ defer res.Body.Close()
+ responseBody, err := ioutil.ReadAll(res.Body)
+
+ if res.StatusCode != expectedResponseCode {
+ err = errors.New("expected response status code does not match. Expected : " + strconv.Itoa(expectedResponseCode) + " ,actual : " + strconv.Itoa(res.StatusCode))
+ }
+
+ return responseBody, err
+}
diff --git a/apidVerifyAPIKey-api.yaml b/apidVerifyAPIKey-api.yaml
index 853330c..7ad84ce 100644
--- a/apidVerifyAPIKey-api.yaml
+++ b/apidVerifyAPIKey-api.yaml
@@ -13,46 +13,39 @@
# limitations under the License.
host: playground.apistudio.io
-swagger: '2.0'
+swagger: "2.0"
info:
- version: 0.0.1
- title: Edge X Verify API Key
- contact:
- name: Apigee, Inc.
- url: http://www.apigee.com/
- email: sales@apigee.com
- license:
- name: Apache 2.0
- url: https://www.apache.org/licenses/LICENSE-2.0
-basePath: /verifiers
+ version: "0.0.1"
+ title: Swagger API
+host: playground.apistudio.io
+basePath: /try/35cd6835-f2ed-4582-a1ae-d10ed29d062b
schemes:
- http
+ - https
consumes:
- application/json
produces:
- application/json
paths:
- /:
- get:
- description: List verifiers
- responses:
- '200':
- description: OK
- schema:
- type: array
- items:
- type: string
- enum:
- - "apikey"
/apikey:
post:
- description: Verify API key valid and return message context
+ tags:
+ - VerifyApiKey
+ summary: Validates the consumer key and returns the attributes associated with apikey,developer,app and apiproduct. Http method is POST but it doesnt mutates any data. POST is used for sending content in the http request.
+ description: 'Verify api key '
+ produces:
+ - application/json
+ consumes:
+ - application/json
parameters:
- name: Authorization
+ description: credentials to authenticate with apid
in: header
required: true
type: string
- description: authCode from /deployments/current
+ - name: gateway
+ in: header
+ type: string
- name: _
in: body
required: true
@@ -60,133 +53,279 @@
$ref: '#/definitions/VerifyAPIKeyRequest'
responses:
'200':
- description: The result of the request
+ description: Success. ApiKey was verified successfully.
schema:
- type: object
- enum:
- - $ref: '#/definitions/VerifyAPIKeyResponseSuccess'
- - $ref: '#/definitions/VerifyAPIKeyResponseFailed'
- examples:
- application/json:
- responseType: APIKeyContext
- resultCode: "SUCCESS"
- result:
- key: abc123
- expiresAt: 1234567890
- issuedAt: 1234567890
- status: abc123
- redirectionURIs: abc123
- appName: abc123
- appId: abc123
- cType: "developer"
+ $ref: '#/definitions/VerifyApiKeySuccessResponse'
+ '401':
+ description: Either clientId,app or developer or company is not valid or status is not approved or entity is not found
+ schema:
+ $ref: '#/definitions/ErrorResponse'
+ '403':
+ description: ClientId is not authorized to access the resourceUri,environment or proxy.
+ schema:
+ $ref: '#/definitions/ErrorResponse'
default:
- description: 4xx or 5xx errors
+ description: Unexpected error.
schema:
$ref: '#/definitions/ErrorResponse'
definitions:
-
- ErrorResult:
- type: object
- required:
- - errorCode
- - reason
- properties:
- errorCode:
- type: number
- reason:
- type: string
-
VerifyAPIKeyRequest:
type: object
required:
- action
- key
- uriPath
- - scopeuuid
+ - organizationName
+ - environmentName
+ - apiProxyName
properties:
action:
- enum:
- - "verify"
+ type: string
key:
type: string
uriPath:
type: string
- scopeuuid:
+ organizationName:
type: string
-
- VerifyAPIKeyResponse:
+ environmentName:
+ type: string
+ apiProxyName:
+ type: string
+ validateAgainstApiProxiesAndEnvs:
+ type: boolean
+ description: when this flag is false, authentication of key and authorization for uripath is done and authorization for apiproxies and environments is skipped. Default is true.
+ VerifyApiKeySuccessResponse:
type: object
- required:
- - type
+ description: 'Response object for the verification of apikey. Verification of apikey response contains details such as developer-id,developer-email-id, other fields and attributes ; app-id,app-name, other fields and attributes; apiproduct-name, fields and attributes ; '
properties:
- type:
+ self:
type: string
- result:
- description: present if type is NOT ErrorResult, override me
+ organization:
+ description: Organization Identifier/Name
+ type: string
+ environment:
+ description: Environment Identifier/Name
+ type: string
+ clientId:
+ description: fields and attributes related to clientId
type: object
- error:
- description: present if type is ErrorResult, override me
+ $ref: '#/definitions/ClientIdDetails'
+ developer:
+ description: fields and attributes related to developer
type: object
+ $ref: '#/definitions/DeveloperDetails'
+ company:
+ description: fields and attributes related to company
+ type: object
+ $ref: '#/definitions/CompanyDetails'
+ app:
+ description: fields and attributes related to app
+ type: object
+ $ref: '#/definitions/AppDetails'
+ apiProduct:
+ description: fields and attributes related to apiProduct
+ type: object
+ $ref: '#/definitions/ApiProductDetails'
- VerifyAPIKeyResponseSuccess:
- allOf:
- - $ref: '#/definitions/VerifyAPIKeyResponse'
- - type: object
- properties:
- result:
- type: object
- properties:
- key:
- type: string
- expiresAt:
- type: integer
- issuedAt:
- type: integer
- status:
- type: string
- redirectionURIs:
- type: string
- appName:
- type: string
- appId:
- type: string
- cType:
- type: string
- example:
- type: "APIKeyContext"
- result:
- key: "abc123"
- expiresAt: 1234567890
- issuedAt: 1234567890
- status: "abc123"
- redirectionURIs: "abc123"
- appName: "abc123"
- appId: "abc123"
- cType: "company OR developer"
-
- VerifyAPIKeyResponseFailed:
- allOf:
- - $ref: '#/definitions/VerifyAPIKeyResponse'
- - type: object
- properties:
- error:
- $ref: '#/definitions/ErrorResult'
- example:
- type: "ErrorResult"
- error:
- errorCode: 606
- reason: "APIKey expired"
-
+ identifier:
+ description: Identifier of the authorization code. This will be unique for each request.
+ type: string
+ kind:
+ type: string
ErrorResponse:
- required:
- - errorCode
- - reason
+ type: object
+ description: Error response returned
properties:
- errorCode:
- type: number
- reason:
+ response_code:
+ type: integer
+ format: int32
+ response_message:
type: string
- example:
- errorCode: 607
- reason: "Something wrong!"
+ kind:
+ type: string
+ Attribute:
+ type: object
+ description: Attribute details
+ properties:
+ Name:
+ type: string
+ Value:
+ type: string
+ kind:
+ type: string
+ ClientIdDetails:
+ type: object
+ description: Fields related to consumer key
+ properties:
+ clientId:
+ type: string
+ clientSecret:
+ type: string
+ redirectURIs:
+ type: array
+ items:
+ type: string
+ status:
+ type: string
+ attributes:
+ description: Attributes associated with the client Id.
+ type: array
+ items:
+ $ref: '#/definitions/Attribute'
+ DeveloperDetails:
+ type: object
+ description: Fields related to developer
+ properties:
+ id:
+ type: string
+ userName:
+ type: string
+ firstName:
+ type: string
+ lastName:
+ type: string
+ email:
+ type: string
+ status:
+ type: string
+ apps:
+ type: array
+ items:
+ type: string
+ created_at:
+ type: integer
+ format: int64
+ created_by:
+ type: string
+ lastmodified_at:
+ type: integer
+ format: int64
+ lastmodified_by:
+ type: string
+ company:
+ type: string
+ attributes:
+ description: Attributes associated with the developer.
+ type: array
+ items:
+ $ref: '#/definitions/Attribute'
+ CompanyDetails:
+ type: object
+ description: Fields related to company
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ displayName:
+ type: string
+ status:
+ type: string
+ apps:
+ type: array
+ items:
+ type: string
+ created_at:
+ type: integer
+ format: int64
+ created_by:
+ type: string
+ lastmodified_at:
+ type: integer
+ format: int64
+ lastmodified_by:
+ type: string
+ attributes:
+ description: Attributes associated with the company.
+ type: array
+ items:
+ $ref: '#/definitions/Attribute'
+ AppDetails:
+ type: object
+ description: Fields related to app
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ accessType:
+ type: string
+ callbackUrl:
+ type: string
+ displayName:
+ type: string
+ status:
+ type: string
+ apiproducts:
+ type: array
+ items:
+ type: string
+ appFamily:
+ type: string
+ created_at:
+ type: integer
+ format: int64
+ created_by:
+ type: string
+ lastmodified_at:
+ type: integer
+ format: int64
+ lastmodified_by:
+ type: string
+ company:
+ type: string
+ attributes:
+ description: Attributes associated with the app.
+ type: array
+ items:
+ $ref: '#/definitions/Attribute'
+ ApiProductDetails:
+ type: object
+ description: Fields related to app
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ displayName:
+ type: string
+ quota.limit:
+ type: integer
+ format: int64
+ quota.interval:
+ type: integer
+ format: int64
+ quota.timeunit:
+ type: integer
+ format: int64
+ status:
+ type: string
+ created_at:
+ type: integer
+ format: int64
+ created_by:
+ type: string
+ lastmodified_at:
+ type: integer
+ format: int64
+ lastmodified_by:
+ type: string
+ company:
+ type: string
+ environments:
+ type: array
+ items:
+ type: string
+ apiproxies:
+ type: array
+ items:
+ type: string
+ attributes:
+ description: Attributes associated with the apiproduct.
+ type: array
+ items:
+ $ref: '#/definitions/Attribute'
+
+
+
diff --git a/data.go b/data.go
index dc9ea93..65583b7 100644
--- a/data.go
+++ b/data.go
@@ -135,7 +135,7 @@
)
if err != nil {
- log.Error("error fetching verify apikey details ", err)
+ log.Debug("error fetching verify apikey details ", err)
return errors.New("InvalidApiKey")
}
diff --git a/data_helper_test.go b/data_helper_test.go
new file mode 100644
index 0000000..0b3f746
--- /dev/null
+++ b/data_helper_test.go
@@ -0,0 +1,155 @@
+// Copyright 2017 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package apidVerifyApiKey
+
+import (
+ "github.com/30x/apid-core"
+ . "github.com/onsi/gomega"
+)
+
+//initialize DB for tests
+func setupApikeyDeveloperTestDb(db apid.DB) {
+ _, err := db.Exec(`CREATE TABLE IF NOT EXISTS kms_organization (id text,name text,display_name text,type text,tenant_id text,customer_id text,description text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_organization" VALUES('85629786-37c5-4e8c-bb45-208f3360d005','apigee-mcrosrvc-client0001','apigee-mcrosrvc-client0001','trial','bc811169','2277ba6c-8991-4a38-a5fc-12d8d36e5812','','2017-07-03 19:21:09.388+00:00','defaultUser','2017-07-05 16:24:35.413+00:00','rajanish@apigee.com','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE kms_developer (id text,tenant_id text,username text,first_name text,last_name text,password text,email text,status text,encrypted_password text,salt text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_developer" VALUES('209ffd18-37e9-4a67-9e30-a5c40a534b6c','bc811169','wilson','Woodre','Wilson','','developer@apigee.com','ACTIVE','','','2017-08-08 17:24:09.008+00:00','defaultUser','2017-08-08 17:24:09.008+00:00','defaultUser','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE IF NOT EXISTS kms_company (id text,tenant_id text,name text,display_name text,status text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_company" VALUES('7834c683-9453-4389-b816-34ca24dfccd9','bc811169','DevCompany','East India Company','ACTIVE','2017-08-05 19:54:12.359+00:00','defaultUser','2017-08-05 19:54:12.359+00:00','defaultUser','bc811169');`)
+
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`CREATE TABLE IF NOT EXISTS kms_app (id text,tenant_id text,name text,display_name text,access_type text,callback_url text,status text,app_family text,company_id text,developer_id text,parent_id text,type text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_app" VALUES('d371f05a-7c04-430c-b12d-26cf4e4d5d65','bc811169','DeveloperApp','','READ','www.apple.com','APPROVED','default','','209ffd18-37e9-4a67-9e30-a5c40a534b6c','209ffd18-37e9-4a67-9e30-a5c40a534b6c','DEVELOPER','2017-08-07 17:00:54.25+00:00','defaultUser','2017-08-07 17:09:08.259+00:00','defaultUser','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE kms_api_product (id text,tenant_id text,name text,display_name text,description text,api_resources text,approval_type text,scopes text,proxies text,environments text,quota text,quota_time_unit text,quota_interval integer,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_api_product" VALUES('24987a63-edb9-4d6b-9334-87e1d70df8e3','bc811169','KeyProduct4','Sandbox Diamond','','{/zoho,/twitter,/nike}','AUTO','{READ,WRITE}','{DevApplication,KeysApplication}','{test}','','',NULL,'2017-08-08 02:53:32.726+00:00','defaultUser','2017-08-08 02:53:32.726+00:00','defaultUser','bc811169')`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE IF NOT EXISTS kms_app_credential (id text,tenant_id text,consumer_secret text,app_id text,method_type text,status text,issued_at blob,expires_at blob,app_status text,scopes text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO kms_app_credential VALUES('63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0','bc811169','Ui8dcyGW3lA04YdX','d371f05a-7c04-430c-b12d-26cf4e4d5d65','','APPROVED','2017-08-07 17:00:54.258+00:00','','','{DELETE}','2017-08-07 17:00:54.258+00:00','-NA-','2017-08-07 17:06:06.242+00:00','-NA-','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE IF NOT EXISTS kms_app_credential_apiproduct_mapper (tenant_id text,appcred_id text,app_id text,apiprdt_id text,status text,_change_selector text, primary key (tenant_id,appcred_id,app_id,apiprdt_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_app_credential_apiproduct_mapper" VALUES('bc811169','63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0','d371f05a-7c04-430c-b12d-26cf4e4d5d65','24987a63-edb9-4d6b-9334-87e1d70df8e3','APPROVED','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE IF NOT EXISTS kms_attributes (tenant_id text,entity_id text,cust_id text,org_id text,dev_id text,comp_id text,apiprdt_id text,app_id text,appcred_id text,name text,type text,value text,_change_selector text, primary key (tenant_id,entity_id,name,type));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','d371f05a-7c04-430c-b12d-26cf4e4d5d65','','','','','','d371f05a-7c04-430c-b12d-26cf4e4d5d65','','Company','APP','Apple','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','7834c683-9453-4389-b816-34ca24dfccd9','','','','7834c683-9453-4389-b816-34ca24dfccd9','','','','country','COMPANY','england','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0','','','','','','','63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0','Device','APP_CREDENTIAL','ios','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+}
+
+//initialize DB for tests
+func setupApikeyCompanyTestDb(db apid.DB) {
+ _, err := db.Exec(`CREATE TABLE IF NOT EXISTS kms_organization (id text,name text,display_name text,type text,tenant_id text,customer_id text,description text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_organization" VALUES('85629786-37c5-4e8c-bb45-208f3360d005','apigee-mcrosrvc-client0001','apigee-mcrosrvc-client0001','trial','bc811169','2277ba6c-8991-4a38-a5fc-12d8d36e5812','','2017-07-03 19:21:09.388+00:00','defaultUser','2017-07-05 16:24:35.413+00:00','rajanish@apigee.com','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE kms_developer (id text,tenant_id text,username text,first_name text,last_name text,password text,email text,status text,encrypted_password text,salt text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE IF NOT EXISTS kms_company (id text,tenant_id text,name text,display_name text,status text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_company" VALUES('7834c683-9453-4389-b816-34ca24dfccd9','bc811169','DevCompany','East India Company','ACTIVE','2017-08-05 19:54:12.359+00:00','defaultUser','2017-08-05 19:54:12.359+00:00','defaultUser','bc811169');`)
+
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`CREATE TABLE IF NOT EXISTS kms_app (id text,tenant_id text,name text,display_name text,access_type text,callback_url text,status text,app_family text,company_id text,developer_id text,parent_id text,type text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_app" VALUES('d371f05a-7c04-430c-b12d-26cf4e4d5d65','bc811169','CompApp2','','READ','www.apple.com','APPROVED','default','7834c683-9453-4389-b816-34ca24dfccd9','','7834c683-9453-4389-b816-34ca24dfccd9','COMPANY','2017-08-07 17:00:54.25+00:00','defaultUser','2017-08-07 17:09:08.259+00:00','defaultUser','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE kms_api_product (id text,tenant_id text,name text,display_name text,description text,api_resources text,approval_type text,scopes text,proxies text,environments text,quota text,quota_time_unit text,quota_interval integer,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_api_product" VALUES('24987a63-edb9-4d6b-9334-87e1d70df8e3','bc811169','KeyProduct4','Sandbox Diamond','','{/zoho,/twitter,/nike}','AUTO','{READ,WRITE}','{DevApplication,KeysApplication}','{test}','','',NULL,'2017-08-08 02:53:32.726+00:00','defaultUser','2017-08-08 02:53:32.726+00:00','defaultUser','bc811169')`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE IF NOT EXISTS kms_app_credential (id text,tenant_id text,consumer_secret text,app_id text,method_type text,status text,issued_at blob,expires_at blob,app_status text,scopes text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO kms_app_credential VALUES('63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0','bc811169','Ui8dcyGW3lA04YdX','d371f05a-7c04-430c-b12d-26cf4e4d5d65','','APPROVED','2017-08-07 17:00:54.258+00:00','','','{DELETE}','2017-08-07 17:00:54.258+00:00','-NA-','2017-08-07 17:06:06.242+00:00','-NA-','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE IF NOT EXISTS kms_app_credential_apiproduct_mapper (tenant_id text,appcred_id text,app_id text,apiprdt_id text,status text,_change_selector text, primary key (tenant_id,appcred_id,app_id,apiprdt_id));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_app_credential_apiproduct_mapper" VALUES('bc811169','63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0','d371f05a-7c04-430c-b12d-26cf4e4d5d65','24987a63-edb9-4d6b-9334-87e1d70df8e3','APPROVED','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+ _, err = db.Exec(`CREATE TABLE IF NOT EXISTS kms_attributes (tenant_id text,entity_id text,cust_id text,org_id text,dev_id text,comp_id text,apiprdt_id text,app_id text,appcred_id text,name text,type text,value text,_change_selector text, primary key (tenant_id,entity_id,name,type));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','d371f05a-7c04-430c-b12d-26cf4e4d5d65','','','','','','d371f05a-7c04-430c-b12d-26cf4e4d5d65','','Company','APP','Apple','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','7834c683-9453-4389-b816-34ca24dfccd9','','','','7834c683-9453-4389-b816-34ca24dfccd9','','','','country','COMPANY','england','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+
+}
+
+func setupKmsAttributesdata(db apid.DB) {
+
+ _, err := db.Exec(`CREATE TABLE kms_attributes (tenant_id text,entity_id text,cust_id text,org_id text,dev_id text,comp_id text,apiprdt_id text,app_id text,appcred_id text,name text,type text,value text,_change_selector text, primary key (tenant_id,entity_id,name,type));`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(``)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','50321842-d6ee-4e92-91b9-37234a7920c1','','','','','50321842-d6ee-4e92-91b9-37234a7920c1','','','RateLimit','APIPRODUCT','RX100','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(``)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','85629786-37c5-4e8c-bb45-208f3360d005','','85629786-37c5-4e8c-bb45-208f3360d005','','','','','','features.isEdgexEnabled','ORGANIZATION','true','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(``)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','85629786-37c5-4e8c-bb45-208f3360d005','','85629786-37c5-4e8c-bb45-208f3360d005','','','','','','features.isCpsEnabled','ORGANIZATION','true','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(``)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','50321842-d6ee-4e92-91b9-37234a7920c1','','','','','50321842-d6ee-4e92-91b9-37234a7920c1','','','developer.quota.limit','APIPRODUCT','100','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(``)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','50321842-d6ee-4e92-91b9-37234a7920c1','','','','','50321842-d6ee-4e92-91b9-37234a7920c1','','','developer.quota.interval','APIPRODUCT','10','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(``)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','50321842-d6ee-4e92-91b9-37234a7920c1','','','','','50321842-d6ee-4e92-91b9-37234a7920c1','','','developer.quota.timeunit','APIPRODUCT','minute','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(``)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','50321842-d6ee-4e92-91b9-37234a7920c1','','','','','50321842-d6ee-4e92-91b9-37234a7920c1','','','Threshold','APIPRODUCT','TX100','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(``)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','40753e12-a50a-429d-9121-e571eb4e43a9','','','','','40753e12-a50a-429d-9121-e571eb4e43a9','','','access','APIPRODUCT','public','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(``)
+ Expect(err).NotTo(HaveOccurred())
+ _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','2d373ed6-e38f-453b-bb34-6d731d9c4815','','','','','','2d373ed6-e38f-453b-bb34-6d731d9c4815','','DisplayName','APP','demo-app','bc811169');`)
+ Expect(err).NotTo(HaveOccurred())
+}
diff --git a/data_test.go b/data_test.go
index 1d20e31..4d4e8e9 100644
--- a/data_test.go
+++ b/data_test.go
@@ -15,53 +15,185 @@
import (
"github.com/30x/apid-core"
+ "github.com/30x/apid-core/factory"
+ . "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
+ "io/ioutil"
+ "sync"
)
-// TODO: sql tests
-// 1. get api key sql test.. verify all fields, json to array conversions
-// 2. get api - no row should return proper error
-// 3. get attributes query tests
-// 4. get attributes with all empty results returned
-// 5. get product with no results
-// 6. get product with status != approved
-// 7. get products happy path
+var _ = Describe("DataTest", func() {
-//initialize DB for tests
-func initTestDb(db apid.DB) {
- _, err := db.Exec(`CREATE TABLE kms_organization (id text,name text,display_name text,type text,tenant_id text,customer_id text,description text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`INSERT INTO "kms_organization" VALUES('85629786-37c5-4e8c-bb45-208f3360d005','apigee-mcrosrvc-client0001','apigee-mcrosrvc-client0001','trial','bc811169','2277ba6c-8991-4a38-a5fc-12d8d36e5812','','2017-07-03 19:21:09.388+00:00','defaultUser','2017-07-05 16:24:35.413+00:00','rajanish@apigee.com','bc811169');`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`CREATE TABLE kms_company (id text,tenant_id text,name text,display_name text,status text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`INSERT INTO "kms_company" VALUES('7834c683-9453-4389-b816-34ca24dfccd9','bc811169','DevCompany','East India Company','ACTIVE','2017-08-05 19:54:12.359+00:00','defaultUser','2017-08-05 19:54:12.359+00:00','defaultUser','bc811169');`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(``)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`CREATE TABLE kms_app (id text,tenant_id text,name text,display_name text,access_type text,callback_url text,status text,app_family text,company_id text,developer_id text,parent_id text,type text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`INSERT INTO "kms_app" VALUES('d371f05a-7c04-430c-b12d-26cf4e4d5d65','bc811169','CompApp2','','READ','www.apple.com','APPROVED','default','7834c683-9453-4389-b816-34ca24dfccd9','','7834c683-9453-4389-b816-34ca24dfccd9','COMPANY','2017-08-07 17:00:54.25+00:00','defaultUser','2017-08-07 17:09:08.259+00:00','defaultUser','bc811169');`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(``)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`CREATE TABLE kms_app_credential (id text,tenant_id text,consumer_secret text,app_id text,method_type text,status text,issued_at blob,expires_at blob,app_status text,scopes text,created_at blob,created_by text,updated_at blob,updated_by text,_change_selector text, primary key (id,tenant_id));`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`INSERT INTO "kms_app_credential" VALUES('63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0','bc811169','Ui8dcyGW3lA04YdX','d371f05a-7c04-430c-b12d-26cf4e4d5d65','','APPROVED','2017-08-07 17:00:54.258+00:00','','','{DELETE}','2017-08-07 17:00:54.258+00:00','-NA-','2017-08-07 17:06:06.242+00:00','-NA-','bc811169');`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(``)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`CREATE TABLE kms_app_credential_apiproduct_mapper (tenant_id text,appcred_id text,app_id text,apiprdt_id text,status text,_change_selector text, primary key (tenant_id,appcred_id,app_id,apiprdt_id));`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`INSERT INTO "kms_app_credential_apiproduct_mapper" VALUES('bc811169','63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0','d371f05a-7c04-430c-b12d-26cf4e4d5d65','b6c9fa49-35d6-48b2-b5f5-99dd3953bd18','APPROVED','bc811169');`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(``)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`CREATE TABLE kms_attributes (tenant_id text,entity_id text,cust_id text,org_id text,dev_id text,comp_id text,apiprdt_id text,app_id text,appcred_id text,name text,type text,value text,_change_selector text, primary key (tenant_id,entity_id,name,type));`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','d371f05a-7c04-430c-b12d-26cf4e4d5d65','','','','','','d371f05a-7c04-430c-b12d-26cf4e4d5d65','','Company','APP','Apple','bc811169');`)
- Expect(err).Should(Succeed())
- _, err = db.Exec(`INSERT INTO "kms_attributes" VALUES('bc811169','7834c683-9453-4389-b816-34ca24dfccd9','','','','7834c683-9453-4389-b816-34ca24dfccd9','','','','country','COMPANY','england','bc811169');`)
- Expect(err).Should(Succeed())
+ Context("query db to get api key details", func() {
+ var dataTestTempDir string
+ var dbMan *dbManager
+ var _ = BeforeEach(func() {
+ var err error
+ dataTestTempDir, err = ioutil.TempDir(testTempDirBase, "sqlite3")
-}
+ s := factory.DefaultServicesFactory()
+ apid.Initialize(s)
+ config := apid.Config()
+ config.Set("local_storage_path", dataTestTempDir)
+
+ Expect(err).NotTo(HaveOccurred())
+
+ dbMan = &dbManager{
+ data: s.Data(),
+ dbMux: sync.RWMutex{},
+ }
+ dbMan.setDbVersion(dataTestTempDir)
+ dbMan.initDb()
+
+ })
+
+ It("should get compnay getApiKeyDetails for happy path", func() {
+ setupApikeyCompanyTestDb(dbMan.db)
+
+ dataWrapper := VerifyApiKeyRequestResponseDataWrapper{
+ verifyApiKeyRequest: VerifyApiKeyRequest{
+ OrganizationName: "apigee-mcrosrvc-client0001",
+ Key: "63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0",
+ },
+ }
+ err := dbMan.getApiKeyDetails(&dataWrapper)
+ Expect(err).NotTo(HaveOccurred())
+
+ Expect(dataWrapper.ctype).Should(BeEquivalentTo("company"))
+ Expect(dataWrapper.tenant_id).Should(BeEquivalentTo("bc811169"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.ClientId.Status).Should(BeEquivalentTo("APPROVED"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.ClientId.ClientSecret).Should(BeEquivalentTo("Ui8dcyGW3lA04YdX"))
+
+ Expect(dataWrapper.tempDeveloperDetails.Id).Should(BeEquivalentTo("7834c683-9453-4389-b816-34ca24dfccd9"))
+ Expect(dataWrapper.tempDeveloperDetails.UserName).Should(BeEquivalentTo("East India Company"))
+ Expect(dataWrapper.tempDeveloperDetails.FirstName).Should(BeEquivalentTo("DevCompany"))
+ Expect(dataWrapper.tempDeveloperDetails.LastName).Should(BeEquivalentTo(""))
+ Expect(dataWrapper.tempDeveloperDetails.Email).Should(BeEquivalentTo(""))
+ Expect(dataWrapper.tempDeveloperDetails.Status).Should(BeEquivalentTo("ACTIVE"))
+ Expect(dataWrapper.tempDeveloperDetails.CreatedAt).Should(BeEquivalentTo("2017-08-05 19:54:12.359+00:00"))
+ Expect(dataWrapper.tempDeveloperDetails.CreatedBy).Should(BeEquivalentTo("defaultUser"))
+ Expect(dataWrapper.tempDeveloperDetails.LastmodifiedAt).Should(BeEquivalentTo("2017-08-05 19:54:12.359+00:00"))
+ Expect(dataWrapper.tempDeveloperDetails.LastmodifiedBy).Should(BeEquivalentTo("defaultUser"))
+
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.Id).Should(BeEquivalentTo("d371f05a-7c04-430c-b12d-26cf4e4d5d65"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.Name).Should(BeEquivalentTo("CompApp2"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.AccessType).Should(BeEquivalentTo("READ"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.CallbackUrl).Should(BeEquivalentTo("www.apple.com"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.DisplayName).Should(BeEquivalentTo(""))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.Status).Should(BeEquivalentTo("APPROVED"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.AppFamily).Should(BeEquivalentTo("default"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.Company).Should(BeEquivalentTo("7834c683-9453-4389-b816-34ca24dfccd9"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.CreatedAt).Should(BeEquivalentTo("2017-08-07 17:00:54.25+00:00"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.CreatedBy).Should(BeEquivalentTo("defaultUser"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.LastmodifiedAt).Should(BeEquivalentTo("2017-08-07 17:09:08.259+00:00"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.LastmodifiedBy).Should(BeEquivalentTo("defaultUser"))
+
+ })
+
+ It("should get developer ApiKeyDetails - happy path", func() {
+ setupApikeyDeveloperTestDb(dbMan.db)
+
+ dataWrapper := VerifyApiKeyRequestResponseDataWrapper{
+ verifyApiKeyRequest: VerifyApiKeyRequest{
+ OrganizationName: "apigee-mcrosrvc-client0001",
+ Key: "63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0",
+ },
+ }
+ err := dbMan.getApiKeyDetails(&dataWrapper)
+ Expect(err).NotTo(HaveOccurred())
+
+ Expect(dataWrapper.ctype).Should(BeEquivalentTo("developer"))
+ Expect(dataWrapper.tenant_id).Should(BeEquivalentTo("bc811169"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.ClientId.Status).Should(BeEquivalentTo("APPROVED"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.ClientId.ClientSecret).Should(BeEquivalentTo("Ui8dcyGW3lA04YdX"))
+
+ Expect(dataWrapper.tempDeveloperDetails.Id).Should(BeEquivalentTo("209ffd18-37e9-4a67-9e30-a5c40a534b6c"))
+ Expect(dataWrapper.tempDeveloperDetails.UserName).Should(BeEquivalentTo("wilson"))
+ Expect(dataWrapper.tempDeveloperDetails.FirstName).Should(BeEquivalentTo("Woodre"))
+ Expect(dataWrapper.tempDeveloperDetails.LastName).Should(BeEquivalentTo("Wilson"))
+ Expect(dataWrapper.tempDeveloperDetails.Email).Should(BeEquivalentTo("developer@apigee.com"))
+ Expect(dataWrapper.tempDeveloperDetails.Status).Should(BeEquivalentTo("ACTIVE"))
+ Expect(dataWrapper.tempDeveloperDetails.CreatedAt).Should(BeEquivalentTo("2017-08-08 17:24:09.008+00:00"))
+ Expect(dataWrapper.tempDeveloperDetails.CreatedBy).Should(BeEquivalentTo("defaultUser"))
+ Expect(dataWrapper.tempDeveloperDetails.LastmodifiedAt).Should(BeEquivalentTo("2017-08-08 17:24:09.008+00:00"))
+ Expect(dataWrapper.tempDeveloperDetails.LastmodifiedBy).Should(BeEquivalentTo("defaultUser"))
+
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.Id).Should(BeEquivalentTo("d371f05a-7c04-430c-b12d-26cf4e4d5d65"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.Name).Should(BeEquivalentTo("DeveloperApp"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.AccessType).Should(BeEquivalentTo("READ"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.CallbackUrl).Should(BeEquivalentTo("www.apple.com"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.DisplayName).Should(BeEquivalentTo(""))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.Status).Should(BeEquivalentTo("APPROVED"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.AppFamily).Should(BeEquivalentTo("default"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.Company).Should(BeEquivalentTo(""))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.CreatedAt).Should(BeEquivalentTo("2017-08-07 17:00:54.25+00:00"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.CreatedBy).Should(BeEquivalentTo("defaultUser"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.LastmodifiedAt).Should(BeEquivalentTo("2017-08-07 17:09:08.259+00:00"))
+ Expect(dataWrapper.verifyApiKeySuccessResponse.App.LastmodifiedBy).Should(BeEquivalentTo("defaultUser"))
+
+ })
+
+ It("should throw error when apikey not found", func() {
+
+ setupApikeyCompanyTestDb(dbMan.db)
+ dataWrapper := VerifyApiKeyRequestResponseDataWrapper{
+ verifyApiKeyRequest: VerifyApiKeyRequest{
+ OrganizationName: "apigee-mcrosrvc-client0001",
+ Key: "invalid-Jkcc6GENVWGT1Zw5gek7kVJ0",
+ },
+ }
+ err := dbMan.getApiKeyDetails(&dataWrapper)
+ Expect(err).ShouldNot(BeNil())
+ Expect(err.Error()).Should(BeEquivalentTo("InvalidApiKey"))
+ })
+
+ It("should get api products ", func() {
+
+ setupApikeyCompanyTestDb(dbMan.db)
+
+ apiProducts := dbMan.getApiProductsForApiKey("63tHSNLKJkcc6GENVWGT1Zw5gek7kVJ0", "bc811169")
+ Expect(len(apiProducts)).Should(BeEquivalentTo(1))
+
+ Expect(apiProducts[0].Id).Should(BeEquivalentTo("24987a63-edb9-4d6b-9334-87e1d70df8e3"))
+ Expect(apiProducts[0].Name).Should(BeEquivalentTo("KeyProduct4"))
+ Expect(apiProducts[0].DisplayName).Should(BeEquivalentTo("Sandbox Diamond"))
+ Expect(apiProducts[0].Status).Should(BeEquivalentTo(""))
+ Expect(apiProducts[0].QuotaTimeunit).Should(BeEquivalentTo(""))
+ Expect(apiProducts[0].QuotaInterval).Should(BeEquivalentTo(0))
+ Expect(apiProducts[0].QuotaLimit).Should(BeEquivalentTo(""))
+
+ Expect(apiProducts[0].Resources).Should(BeEquivalentTo([]string{"/zoho", "/twitter", "/nike"}))
+ Expect(apiProducts[0].Apiproxies).Should(BeEquivalentTo([]string{"DevApplication", "KeysApplication"}))
+ Expect(apiProducts[0].Environments).Should(BeEquivalentTo([]string{"test"}))
+ Expect(apiProducts[0].Company).Should(BeEquivalentTo(""))
+ Expect(len(apiProducts[0].Attributes)).Should(BeEquivalentTo(0))
+
+ Expect(apiProducts[0].CreatedBy).Should(BeEquivalentTo("defaultUser"))
+ Expect(apiProducts[0].CreatedAt).Should(BeEquivalentTo("2017-08-08 02:53:32.726+00:00"))
+ Expect(apiProducts[0].LastmodifiedBy).Should(BeEquivalentTo("defaultUser"))
+ Expect(apiProducts[0].LastmodifiedAt).Should(BeEquivalentTo("2017-08-08 02:53:32.726+00:00"))
+
+ })
+
+ It("should return empty array when no api products found", func() {
+
+ setupApikeyCompanyTestDb(dbMan.db)
+ apiProducts := dbMan.getApiProductsForApiKey("invalid-LKJkcc6GENVWGT1Zw5gek7kVJ0", "bc811169")
+ Expect(len(apiProducts)).Should(BeEquivalentTo(0))
+
+ })
+
+ It("should get kms attributes", func() {
+
+ setupKmsAttributesdata(dbMan.db)
+ attributes := dbMan.getKmsAttributes("bc811169", "40753e12-a50a-429d-9121-e571eb4e43a9", "85629786-37c5-4e8c-bb45-208f3360d005", "50321842-d6ee-4e92-91b9-37234a7920c1", "test-invalid")
+ Expect(len(attributes)).Should(BeEquivalentTo(3))
+ Expect(len(attributes["40753e12-a50a-429d-9121-e571eb4e43a9"])).Should(BeEquivalentTo(1))
+ Expect(len(attributes["85629786-37c5-4e8c-bb45-208f3360d005"])).Should(BeEquivalentTo(2))
+ Expect(len(attributes["50321842-d6ee-4e92-91b9-37234a7920c1"])).Should(BeEquivalentTo(5))
+ Expect(len(attributes["test-invalid"])).Should(BeEquivalentTo(0))
+
+ })
+
+ })
+})
diff --git a/sqlQueries.go b/sqlQueries.go
index 3d121b0..504af9a 100644
--- a/sqlQueries.go
+++ b/sqlQueries.go
@@ -70,7 +70,7 @@
COALESCE(ad.id,"") as dev_id,
COALESCE(ad.display_name,"") as dev_username,
- COALESCE("","") as dev_first_name,
+ COALESCE(ad.name,"") as dev_first_name,
COALESCE("","") as dev_last_name,
COALESCE("","") as dev_email,
COALESCE(ad.status,"") as dev_status,
diff --git a/test_helper.go b/test_helper.go
deleted file mode 100644
index 4c1a026..0000000
--- a/test_helper.go
+++ /dev/null
@@ -1,280 +0,0 @@
-// Copyright 2017 Google Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package apidVerifyApiKey
-
-import (
- "database/sql"
- "github.com/30x/apid-core"
- "strconv"
-)
-
-func convertSuffix(i int) string {
- return strconv.FormatInt(int64(i), 10)
-}
-
-func generateTestApiProduct(suffix int, txn *sql.Tx) {
-
- s, err := txn.Prepare("INSERT INTO kms_api_product (id, api_resources, environments, tenant_id, _change_selector) VALUES(?, ?, ?, ?, ?)")
- if err != nil {
- log.Panicf("This is a bug : " + err.Error())
- }
- s.Exec("api_product_"+convertSuffix(suffix), "{/**, /test}", "{Env_0, Env_1}",
- "tenant_id_xxxx", "Org_0")
-}
-
-func generateTestDeveloper(suffix int, txn *sql.Tx) {
- s, err := txn.Prepare("INSERT INTO kms_developer (id, status, email, first_name, last_name, tenant_id, _change_selector)" +
- "VALUES (?, ?, ?, ?, ?, ?, ?)")
- if err != nil {
- log.Panicf("This is a bug : " + err.Error())
- }
- s.Exec("developer_id_"+convertSuffix(suffix), "Active", "test@apigee.com", "Apigee", "Google", "tenant_id_xxxx", "Org_0")
-}
-
-func generateTestCompany(suffix int, txn *sql.Tx) {
- s, err := txn.Prepare("INSERT INTO kms_company (id, status, name, display_name, tenant_id, _change_selector)" +
- "VALUES (?, ?, ?, ?, ?, ?)")
- if err != nil {
- log.Panicf("This is a bug: " + err.Error())
- }
- s.Exec("company_id_"+convertSuffix(suffix), "Active", "Apigee Corporation", "Apigee", "tenant_id_xxxx", "Org_0")
-}
-
-func generateTestCompanyDeveloper(suffix int, txn *sql.Tx) {
- s, err := txn.Prepare("INSERT INTO kms_company_developer (developer_id, tenant_id, _change_selector, company_id)" +
- "VALUES (?, ?, ?, ?)")
- if err != nil {
- log.Panicf("This is a bug: " + err.Error())
- }
- s.Exec("developer_id_"+convertSuffix(suffix), "tenant_id_0", "test_org0", "company_id_"+convertSuffix(suffix))
-}
-
-func generateTestApp(suffix1, suffix2 int, txn *sql.Tx) {
- s, err := txn.Prepare("INSERT INTO kms_app (id, developer_id, status, tenant_id, callback_url, _change_selector, parent_id)" +
- " VALUES(?, ?, ?, ?, ?, ?, ?)")
- if err != nil {
- log.Panicf("This is a bug: " + err.Error())
- }
- s.Exec("application_id_"+convertSuffix(suffix1), "developer_id_"+convertSuffix(suffix2), "Approved", "tenant_id_xxxx",
- "http://apigee.com", "Org_0", "developer_id_"+convertSuffix(suffix2))
-
-}
-
-func generateTestAppCompany(suffix1, suffix2 int, txn *sql.Tx) {
- s, err := txn.Prepare("INSERT INTO kms_app (id, company_id, status, tenant_id, callback_url, _change_selector, parent_id)" +
- " VALUES(?, ?, ?, ?, ?, ?, ?)")
- if err != nil {
- log.Panicf("This is a bug: " + err.Error())
- }
- s.Exec("application_id_"+convertSuffix(suffix1), "company_id_"+convertSuffix(suffix2), "Approved", "tenant_id_xxxx",
- "http://apigee.com", "Org_0", "company_id_"+convertSuffix(suffix2))
-
-}
-
-func generateTestAppCreds(suffix int, txn *sql.Tx) {
- s, err := txn.Prepare("INSERT INTO kms_app_credential (id, app_id, status, tenant_id, _change_selector) VALUES(?, ?, ?, ?, ?)")
- if err != nil {
- log.Panicf("This is a bug: " + err.Error())
- }
- s.Exec("app_credential_"+convertSuffix(suffix), "application_id_"+convertSuffix(suffix), "Approved",
- "tenant_id_xxxx", "Org_0")
-}
-
-func generateTestApiProductMapper(suffix int, txn *sql.Tx) {
- s, err := txn.Prepare("INSERT INTO kms_app_credential_apiproduct_mapper (apiprdt_id, status, app_id, appcred_id, tenant_id, _change_selector) VALUES(?, ?, ?, ?, ?, ?)")
- if err != nil {
- log.Panicf("This is a bug: " + err.Error())
- }
- s.Exec("api_product_"+convertSuffix(suffix), "Approved", "application_id_"+convertSuffix(suffix),
- "app_credential_"+convertSuffix(suffix), "tenant_id_xxxx", "Org_0")
-}
-
-func createTables(db apid.DB) {
- _, err := db.Exec(`
-CREATE TABLE IF NOT EXISTS kms_api_product (
- id text,
- tenant_id text,
- name text,
- display_name text,
- description text,
- api_resources text[],
- approval_type text,
- _change_selector text,
- proxies text[],
- environments text[],
- quota text,
- quota_time_unit text,
- quota_interval int,
- created_at int64,
- created_by text,
- updated_at int64,
- updated_by text,
- PRIMARY KEY (tenant_id, id));
-CREATE TABLE IF NOT EXISTS kms_developer (
- id text,
- tenant_id text,
- username text,
- first_name text,
- last_name text,
- password text,
- email text,
- status text,
- encrypted_password text,
- salt text,
- _change_selector text,
- created_at int64,
- created_by text,
- updated_at int64,
- updated_by text,
- PRIMARY KEY (tenant_id, id)
-);
-CREATE TABLE IF NOT EXISTS kms_company (
- id text,
- tenant_id text,
- name text,
- display_name text,
- status text,
- created_at int64,
- created_by text,
- updated_at int64,
- updated_by text,
- _change_selector text,
- PRIMARY KEY (tenant_id, id)
-);
-CREATE TABLE IF NOT EXISTS kms_company_developer (
- tenant_id text,
- company_id text,
- developer_id text,
- roles text[],
- created_at int64,
- created_by text,
- updated_at int64,
- updated_by text,
- _change_selector text,
- PRIMARY KEY (tenant_id, company_id,developer_id)
-);
-CREATE TABLE IF NOT EXISTS kms_app (
- id text,
- tenant_id text,
- name text,
- display_name text,
- access_type text,
- callback_url text,
- status text,
- app_family text,
- company_id text,
- parent_id text,
- developer_id text,
- type int,
- created_at int64,
- created_by text,
- updated_at int64,
- updated_by text,
- _change_selector text,
- PRIMARY KEY (tenant_id, id)
-);
-CREATE TABLE IF NOT EXISTS kms_app_credential (
- id text,
- tenant_id text,
- consumer_secret text,
- app_id text,
- method_type text,
- status text,
- issued_at int64,
- expires_at int64,
- app_status text,
- _change_selector text,
- PRIMARY KEY (tenant_id, id)
-);
-CREATE TABLE IF NOT EXISTS kms_app_credential_apiproduct_mapper (
- tenant_id text,
- appcred_id text,
- app_id text,
- apiprdt_id text,
- _change_selector text,
- status text,
- PRIMARY KEY (appcred_id, app_id, apiprdt_id,tenant_id)
-);
-CREATE INDEX IF NOT EXISTS company_id ON kms_company (id);
-CREATE INDEX IF NOT EXISTS developer_id ON kms_developer (id);
-CREATE INDEX IF NOT EXISTS api_product_id ON kms_api_product (id);
-CREATE INDEX IF NOT EXISTS app_id ON kms_app (id);
-`)
- if err != nil {
- log.Panic("Unable to initialize DB", err)
- }
-}
-
-func createApidClusterTables(db apid.DB) {
- _, err := db.Exec(`
-CREATE TABLE edgex_apid_cluster (
- id text,
- instance_id text,
- name text,
- description text,
- umbrella_org_app_name text,
- created int64,
- created_by text,
- updated int64,
- updated_by text,
- _change_selector text,
- snapshotInfo text,
- lastSequence text,
- PRIMARY KEY (id)
-);
-CREATE TABLE edgex_data_scope (
- id text,
- apid_cluster_id text,
- scope text,
- org text,
- env text,
- created int64,
- created_by text,
- updated int64,
- updated_by text,
- _change_selector text,
- PRIMARY KEY (id)
-);
-`)
- if err != nil {
- log.Panic("Unable to initialize DB", err)
- }
-}
-
-func addScopes(db apid.DB) {
- txn, _ := db.Begin()
- txn.Exec("INSERT INTO EDGEX_DATA_SCOPE (id, _change_selector, apid_cluster_id, scope, org, env) "+
- "VALUES"+
- "($1,$2,$3,$4,$5,$6)",
- "ABCDE",
- "some_cluster_id",
- "some_cluster_id",
- "tenant_id_xxxx",
- "test_org0",
- "Env_0",
- )
- txn.Exec("INSERT INTO EDGEX_DATA_SCOPE (id, _change_selector, apid_cluster_id, scope, org, env) "+
- "VALUES"+
- "($1,$2,$3,$4,$5,$6)",
- "XYZ",
- "test_org0",
- "somecluster_id",
- "tenant_id_0",
- "test_org0",
- "Env_0",
- )
- log.Info("Inserted EDGEX_DATA_SCOPE for test")
- txn.Commit()
-}
diff --git a/verifyAPIKey_suite_test.go b/verifyAPIKey_suite_test.go
index a7d9c9a..fdf728b 100644
--- a/verifyAPIKey_suite_test.go
+++ b/verifyAPIKey_suite_test.go
@@ -19,64 +19,19 @@
. "github.com/onsi/gomega"
"github.com/30x/apid-core"
- "github.com/30x/apid-core/factory"
- "io/ioutil"
- "net/http"
- "net/http/httptest"
"os"
- "sync"
"testing"
)
+const testTempDirBase = "./tmp/"
+
var (
testTempDir string
- testServer *httptest.Server
testSyncHandler apigeeSyncHandler
)
var _ = BeforeSuite(func() {
- var err error
- testTempDir, err = ioutil.TempDir("", "api_test")
- s := factory.DefaultServicesFactory()
- apid.Initialize(s)
- config := apid.Config()
- config.Set("data_path", testTempDir)
- config.Set("log_level", "DEBUG")
- log = apid.Log()
- Expect(err).NotTo(HaveOccurred())
-
- apid.InitializePlugins("")
-
- db, err := apid.Data().DB()
- Expect(err).NotTo(HaveOccurred())
-
- dbMan := &dbManager{
- data: s.Data(),
- dbMux: sync.RWMutex{},
- }
- dbMan.initDb()
- apiMan := apiManager{
- dbMan: dbMan,
- verifiersEndpoint: apiPath,
- }
-
- testSyncHandler = apigeeSyncHandler{
- dbMan: dbMan,
- apiMan: apiMan,
- }
-
- testSyncHandler.initListener(s)
-
- createTables(db)
- createApidClusterTables(db)
- addScopes(db)
- testServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
- if req.URL.Path == apiPath {
- apiMan.handleRequest(w, req)
- }
- }))
-
- createTestData(db)
+ _ = os.MkdirAll(testTempDirBase, os.ModePerm)
})
var _ = AfterSuite(func() {
@@ -84,78 +39,11 @@
if testServer != nil {
testServer.Close()
}
- os.RemoveAll(testTempDir)
+ os.RemoveAll(testTempDirBase)
+
})
func TestVerifyAPIKey(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "VerifyAPIKey Suite")
}
-
-func createTestData(db apid.DB) {
- txn, err := db.Begin()
- Expect(err).ShouldNot(HaveOccurred())
- // api products
- for i := 0; i < 10; i++ {
- generateTestApiProduct(i, txn)
- }
- // developers
- for i := 0; i < 10; i++ {
- generateTestDeveloper(i, txn)
- }
-
- // application
- var j, k int
- for i := 0; i < 10; i++ {
- for j = k; j < 10+k; j++ {
- generateTestApp(j, i, txn)
- }
- k = j
- }
- // app credentials
- for i := 0; i < 10; i++ {
- generateTestAppCreds(i, txn)
- }
- // api product mapper
- for i := 0; i < 10; i++ {
- generateTestApiProductMapper(i, txn)
- }
-
- // Following are data for company
- // api products
- for i := 100; i < 110; i++ {
- generateTestApiProduct(i, txn)
- }
-
- // companies
- for i := 100; i < 110; i++ {
- generateTestCompany(i, txn)
- }
-
- // company developers
- for i := 100; i < 110; i++ {
- generateTestCompanyDeveloper(i, txn)
- }
-
- // application
- k = 100
- for i := 100; i < 110; i++ {
- for j = k; j < 100+k; j++ {
- generateTestAppCompany(j, i, txn)
- }
- k = j
- }
- // app credentials
- for i := 100; i < 110; i++ {
- generateTestAppCreds(i, txn)
- }
- // api product mapper
- for i := 100; i < 110; i++ {
- generateTestApiProductMapper(i, txn)
- }
-
- txn.Commit()
- var count int64
- db.QueryRow("select count(*) from EDGEX_DATA_SCOPE").Scan(&count)
- log.Info("Found ", count)
-}
diff --git a/verifyApiKeyStructs.go b/verifyApiKeyStructs.go
index 8c15778..e791c6a 100644
--- a/verifyApiKeyStructs.go
+++ b/verifyApiKeyStructs.go
@@ -1,5 +1,7 @@
package apidVerifyApiKey
+import "errors"
+
type ClientIdDetails struct {
ClientId string `json:"clientId,omitempty"`
ClientSecret string `json:"clientSecret,omitempty"`
@@ -102,6 +104,38 @@
ValidateAgainstApiProxiesAndEnvs bool `json:"validateAgainstApiProxiesAndEnvs,omitempty"`
}
+func (v *VerifyApiKeyRequest) validate() (bool, error) {
+ var validationMsg string
+
+ if v.Action == "" {
+ validationMsg += " action"
+ }
+
+ if v.Key == "" {
+ validationMsg += " key"
+ }
+ if v.OrganizationName == "" {
+ validationMsg += " organizationName"
+ }
+ if v.UriPath == "" {
+ validationMsg += " uriPath"
+ }
+ if v.ValidateAgainstApiProxiesAndEnvs {
+ if v.ApiProxyName == "" {
+ validationMsg += " apiProxyName"
+ }
+ if v.EnvironmentName == "" {
+ validationMsg += " environmentName"
+ }
+ }
+
+ if validationMsg != "" {
+ validationMsg = "Missing mandatory fields in the request :" + validationMsg
+ return false, errors.New(validationMsg)
+ }
+ return true, nil
+}
+
type VerifyApiKeySuccessResponse struct {
Self string `json:"self,omitempty"`
// Organization Identifier/Name