Search in sources :

Example 1 with CouchDbException

use of com.cloudant.client.org.lightcouch.CouchDbException in project java-cloudant by cloudant.

the class HttpIamTest method iamRenewalFailureOnSessionCookie.

/**
 * Test IAM token and cookie flow, where session expires and subsequent session cookie fails:
 * - GET a resource on the cloudant server
 * - Cookie jar empty, so get IAM token followed by session cookie
 * - GET now proceeds as normal, expected cookie value is sent in header
 * - second GET on cloudant server, re-using session cookie
 * - third GET on cloudant server, cookie expired, get IAM token, subsequent session cookie
 * request fails, no more requests are made
 *
 * @throws Exception
 */
@Test
public void iamRenewalFailureOnSessionCookie() throws Exception {
    // Request sequence
    mockWebServer.enqueue(OK_IAM_COOKIE);
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(hello));
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(hello));
    // cookie expired
    mockWebServer.enqueue(new MockResponse().setResponseCode(401).setBody("{\"error\":\"credentials_expired\"}"));
    // mock 500 on cookie renewal
    mockWebServer.enqueue(new MockResponse().setResponseCode(500));
    mockIamServer.enqueue(new MockResponse().setResponseCode(200).setBody(IAM_TOKEN));
    mockIamServer.enqueue(new MockResponse().setResponseCode(200).setBody(IAM_TOKEN_2));
    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer).iamApiKey(iamApiKey).build();
    String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertEquals(hello, response, "The expected response should be received");
    String response2 = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertEquals(hello, response2, "The expected response should be received");
    // unhelpful
    try {
        c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
        fail("Should get CouchDbException when trying to get response");
    } catch (CouchDbException cdbe) {
        ;
    }
    // cloudant mock server
    // assert that there were 5 calls
    RecordedRequest[] recordedRequests = takeN(mockWebServer, 5);
    assertEquals("/_iam_session", recordedRequests[0].getPath(), "The request should have been for /_iam_session");
    assertThat("The request body should contain the IAM token", recordedRequests[0].getBody().readString(Charset.forName("UTF-8")), containsString(IAM_TOKEN));
    // first request
    assertEquals("/", recordedRequests[1].getPath(), "The request should have been for /");
    // The cookie may or may not have the session id quoted, so check both
    assertThat("The Cookie header should contain the expected session value", recordedRequests[1].getHeader("Cookie"), anyOf(containsString(iamSession(EXPECTED_OK_COOKIE)), containsString(iamSessionUnquoted(EXPECTED_OK_COOKIE))));
    // second request
    assertEquals("/", recordedRequests[2].getPath(), "The request should have been for /");
    // third request, will be rejected due to cookie expiry
    assertEquals("/", recordedRequests[3].getPath(), "The request should have been for /");
    // try to renew cookie but get 500
    assertEquals("/_iam_session", recordedRequests[4].getPath(), "The request should have been for /_iam_session");
    assertThat("The request body should contain the IAM token", recordedRequests[4].getBody().readString(Charset.forName("UTF-8")), containsString(IAM_TOKEN_2));
    // iam mock server
    // assert that there were 2 calls
    RecordedRequest[] recordedIamRequests = takeN(mockIamServer, 2);
    // first time, automatically fetch because cookie jar is empty
    assertEquals(iamTokenEndpoint, recordedIamRequests[0].getPath(), "The request should have been for " + "/identity/token");
    assertThat("The request body should contain the IAM API key", recordedIamRequests[0].getBody().readString(Charset.forName("UTF-8")), containsString("apikey=" + iamApiKey));
    // second time, refresh because the cloudant session cookie has expired
    assertEquals(iamTokenEndpoint, recordedIamRequests[1].getPath(), "The request should have been for " + "/identity/token");
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) CouchDbException(com.cloudant.client.org.lightcouch.CouchDbException) CloudantClient(com.cloudant.client.api.CloudantClient) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Test(org.junit.jupiter.api.Test)

Example 2 with CouchDbException

use of com.cloudant.client.org.lightcouch.CouchDbException in project java-cloudant by cloudant.

the class HttpTest method basic403Test.

/**
 * Method that performs a basic test for a 403 response. The sequence of requests is:
 * <OL>
 * <LI>_session request to get Cookie</LI>
 * <LI>GET request -> a 403 response</LI>
 * <LI>_session for new cookie*</LI>
 * <LI>GET replay -> a 200 response*</LI>
 * </OL>
 * The requests annotated * should only happen in the credentials_expired 403 case
 *
 * @param error  the response JSON error content for the 403
 * @param reason the response JSON reason content for the 403
 */
private void basic403Test(String error, String reason, int expectedRequests) throws Exception {
    mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
    JsonObject responseBody = new JsonObject();
    responseBody.add("error", new JsonPrimitive(error));
    JsonElement jsonReason;
    if (reason != null) {
        if ("null".equals(reason)) {
            jsonReason = JsonNull.INSTANCE;
            // For the assertion we need a real null, not a JsonNull
            reason = null;
        } else {
            jsonReason = new JsonPrimitive(reason);
        }
        responseBody.add("reason", jsonReason);
    }
    mockWebServer.enqueue(new MockResponse().setResponseCode(403).setBody(responseBody.toString()));
    mockWebServer.enqueue(MockWebServerResources.OK_COOKIE);
    mockWebServer.enqueue(new MockResponse());
    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer).username("a").password("b").build();
    // _session followed by a replay of GET
    try {
        String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
        assertTrue(response.isEmpty(), "There should be no response body on the mock response");
        if (!error.equals("credentials_expired")) {
            fail("A 403 not due to cookie expiry should result in a CouchDbException");
        }
    } catch (CouchDbException e) {
        assertEquals(error, e.getError(), "The exception error should be the expected message");
        assertEquals(reason, e.getReason(), "The exception reason should be the expected message");
    }
    // also assert that there were the correct number of calls
    assertEquals(expectedRequests, mockWebServer.getRequestCount(), "The server should receive the expected number of " + "requests");
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) CouchDbException(com.cloudant.client.org.lightcouch.CouchDbException) CloudantClient(com.cloudant.client.api.CloudantClient) JsonPrimitive(com.google.gson.JsonPrimitive) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString)

Example 3 with CouchDbException

use of com.cloudant.client.org.lightcouch.CouchDbException in project java-cloudant by cloudant.

the class SslAuthenticationTest method localSSLAuthenticationEnabledWithCookieAuth.

/**
 * Repeat the localSSLAuthenticationEnabled, but with the cookie auth enabled.
 * This test validates that the SSL settings also get applied to the cookie interceptor.
 */
@TestTemplate
public void localSSLAuthenticationEnabledWithCookieAuth() throws Exception {
    // Mock up an OK cookie response then an OK response for the getAllDbs()
    server.enqueue(MockWebServerResources.OK_COOKIE);
    // OK 200
    server.enqueue(new MockResponse());
    // Use a username and password to enable the cookie auth interceptor
    CloudantClient dbClient = CloudantClientHelper.newMockWebServerClientBuilder(server).username("user").password("password").build();
    try {
        dbClient.getAllDbs();
        fail("The SSL authentication failure should result in a CouchDbException");
    } catch (CouchDbException e) {
        validateClientAuthenticationException(e);
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) CouchDbException(com.cloudant.client.org.lightcouch.CouchDbException) CloudantClient(com.cloudant.client.api.CloudantClient) TestTemplate(org.junit.jupiter.api.TestTemplate)

Example 4 with CouchDbException

use of com.cloudant.client.org.lightcouch.CouchDbException in project java-cloudant by cloudant.

the class DatabaseTest method permissionsParsing.

@Test
public void permissionsParsing() throws Exception {
    CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer).build();
    Database db = client.database("notarealdb", false);
    // Mock up a request of all permissions
    // for GET _security
    mockWebServer.enqueue(MockWebServerResources.PERMISSIONS);
    // for PUT _security
    mockWebServer.enqueue(MockWebServerResources.JSON_OK);
    db.setPermissions("testUsername", EnumSet.allOf(Permissions.class));
    // Mock up a failing request
    String testError = "test error";
    String testReason = "test reason";
    // for GET _security
    mockWebServer.enqueue(MockWebServerResources.PERMISSIONS);
    mockWebServer.enqueue(new MockResponse().setResponseCode(400).setBody("{\"reason\":\"" + testReason + "\", \"error\":\"" + testError + "\"}"));
    try {
        db.setPermissions("testUsername", EnumSet.allOf(Permissions.class));
    } catch (CouchDbException e) {
        assertEquals(testError, e.getError());
        assertEquals(testReason, e.getReason());
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) CouchDbException(com.cloudant.client.org.lightcouch.CouchDbException) CloudantClient(com.cloudant.client.api.CloudantClient) Database(com.cloudant.client.api.Database) Permissions(com.cloudant.client.api.model.Permissions) Test(org.junit.jupiter.api.Test)

Example 5 with CouchDbException

use of com.cloudant.client.org.lightcouch.CouchDbException in project java-cloudant by cloudant.

the class Database method createIndex.

/**
 * Create a new JSON index
 * <P>
 * Example usage creating an index that sorts ascending on name, then by year:
 * </P>
 * <pre>
 * {@code
 * db.createIndex("Person_name", "Person_name", null, new IndexField[]{
 *       new IndexField("Person_name",SortOrder.asc),
 *       new IndexField("Movie_year",SortOrder.asc)});
 * }
 * </pre>
 * <P>
 * Example usage creating an index that sorts ascending by year:
 * </P>
 * <pre>
 * {@code
 * db.createIndex("Movie_year", "Movie_year", null, new IndexField[]{
 *      new IndexField("Movie_year",SortOrder.asc)});
 * }
 * </pre>
 *
 * @param indexName     optional name of the index (if not provided one will be generated)
 * @param designDocName optional name of the design doc in which the index will be created
 * @param indexType     optional, type of index (only "json" for this method)
 * @param fields        array of fields in the index
 * @see Database#createIndex(String)
 */
@Deprecated
public void createIndex(String indexName, String designDocName, String indexType, IndexField[] fields) {
    if (indexType == null || "json".equalsIgnoreCase(indexType)) {
        JsonIndex.Builder b = JsonIndex.builder().name(indexName).designDocument(designDocName);
        for (IndexField f : fields) {
            switch(f.getOrder()) {
                case desc:
                    b.desc(f.getName());
                    break;
                case asc:
                default:
                    b.asc(f.getName());
                    break;
            }
        }
        createIndex(b.definition());
    } else {
        throw new CouchDbException("Unsupported index type " + indexType);
    }
}
Also used : CouchDbException(com.cloudant.client.org.lightcouch.CouchDbException) JsonIndex(com.cloudant.client.api.query.JsonIndex) IndexField(com.cloudant.client.api.model.IndexField)

Aggregations

CouchDbException (com.cloudant.client.org.lightcouch.CouchDbException)9 CloudantClient (com.cloudant.client.api.CloudantClient)7 MockResponse (okhttp3.mockwebserver.MockResponse)6 Test (org.junit.jupiter.api.Test)4 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)3 HttpConnectionRequestInterceptor (com.cloudant.http.HttpConnectionRequestInterceptor)2 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)2 TestTemplate (org.junit.jupiter.api.TestTemplate)2 Database (com.cloudant.client.api.Database)1 IndexField (com.cloudant.client.api.model.IndexField)1 Permissions (com.cloudant.client.api.model.Permissions)1 JsonIndex (com.cloudant.client.api.query.JsonIndex)1 Key (com.cloudant.client.api.views.Key)1 IndexDeserializer (com.cloudant.client.internal.util.IndexDeserializer)1 SecurityDeserializer (com.cloudant.client.internal.util.SecurityDeserializer)1 ShardDeserializer (com.cloudant.client.internal.util.ShardDeserializer)1 CouchDbProperties (com.cloudant.client.org.lightcouch.CouchDbProperties)1 HttpConnection (com.cloudant.http.HttpConnection)1 HttpConnectionInterceptorContext (com.cloudant.http.HttpConnectionInterceptorContext)1 HttpConnectionResponseInterceptor (com.cloudant.http.HttpConnectionResponseInterceptor)1