Search in sources :

Example 1 with GenericSolrRequest

use of org.apache.solr.client.solrj.request.GenericSolrRequest in project lucene-solr by apache.

the class BasicAuthIntegrationTest method testBasicAuth.

@Test
public void testBasicAuth() throws Exception {
    boolean isUseV2Api = random().nextBoolean();
    String authcPrefix = "/admin/authentication";
    String authzPrefix = "/admin/authorization";
    if (isUseV2Api) {
        authcPrefix = "/____v2/cluster/security/authentication";
        authzPrefix = "/____v2/cluster/security/authorization";
    }
    NamedList<Object> rsp;
    HttpClient cl = null;
    try {
        cl = HttpClientUtil.createClient(null);
        JettySolrRunner randomJetty = cluster.getRandomJetty(random());
        String baseUrl = randomJetty.getBaseUrl().toString();
        verifySecurityStatus(cl, baseUrl + authcPrefix, "/errorMessages", null, 20);
        zkClient().setData("/security.json", STD_CONF.replaceAll("'", "\"").getBytes(UTF_8), true);
        verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/class", "solr.BasicAuthPlugin", 20);
        randomJetty.stop();
        randomJetty.start(false);
        baseUrl = randomJetty.getBaseUrl().toString();
        verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/class", "solr.BasicAuthPlugin", 20);
        String command = "{\n" + "'set-user': {'harry':'HarryIsCool'}\n" + "}";
        final SolrRequest genericReq;
        if (isUseV2Api) {
            genericReq = new V2Request.Builder("/cluster/security/authentication").withMethod(SolrRequest.METHOD.POST).build();
        } else {
            genericReq = new GenericSolrRequest(SolrRequest.METHOD.POST, authcPrefix, new ModifiableSolrParams());
            ((GenericSolrRequest) genericReq).setContentStreams(Collections.singletonList(new ContentStreamBase.ByteArrayStream(command.getBytes(UTF_8), "")));
        }
        HttpSolrClient.RemoteSolrException exp = expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
            cluster.getSolrClient().request(genericReq);
        });
        assertEquals(401, exp.code());
        command = "{\n" + "'set-user': {'harry':'HarryIsUberCool'}\n" + "}";
        HttpPost httpPost = new HttpPost(baseUrl + authcPrefix);
        setBasicAuthHeader(httpPost, "solr", "SolrRocks");
        httpPost.setEntity(new ByteArrayEntity(command.getBytes(UTF_8)));
        httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
        verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication.enabled", "true", 20);
        HttpResponse r = cl.execute(httpPost);
        int statusCode = r.getStatusLine().getStatusCode();
        Utils.consumeFully(r.getEntity());
        assertEquals("proper_cred sent, but access denied", 200, statusCode);
        baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();
        verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/credentials/harry", NOT_NULL_PREDICATE, 20);
        command = "{\n" + "'set-user-role': {'harry':'admin'}\n" + "}";
        executeCommand(baseUrl + authzPrefix, cl, command, "solr", "SolrRocks");
        baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();
        verifySecurityStatus(cl, baseUrl + authzPrefix, "authorization/user-role/harry", NOT_NULL_PREDICATE, 20);
        executeCommand(baseUrl + authzPrefix, cl, Utils.toJSONString(singletonMap("set-permission", Utils.makeMap("collection", "x", "path", "/update/*", "role", "dev"))), "harry", "HarryIsUberCool");
        verifySecurityStatus(cl, baseUrl + authzPrefix, "authorization/permissions[1]/collection", "x", 20);
        executeCommand(baseUrl + authzPrefix, cl, Utils.toJSONString(singletonMap("set-permission", Utils.makeMap("name", "collection-admin-edit", "role", "admin"))), "harry", "HarryIsUberCool");
        verifySecurityStatus(cl, baseUrl + authzPrefix, "authorization/permissions[2]/name", "collection-admin-edit", 20);
        CollectionAdminRequest.Reload reload = CollectionAdminRequest.reloadCollection(COLLECTION);
        try (HttpSolrClient solrClient = getHttpSolrClient(baseUrl)) {
            try {
                rsp = solrClient.request(reload);
                fail("must have failed");
            } catch (HttpSolrClient.RemoteSolrException e) {
            }
            reload.setMethod(SolrRequest.METHOD.POST);
            try {
                rsp = solrClient.request(reload);
                fail("must have failed");
            } catch (HttpSolrClient.RemoteSolrException e) {
            }
        }
        cluster.getSolrClient().request(CollectionAdminRequest.reloadCollection(COLLECTION).setBasicAuthCredentials("harry", "HarryIsUberCool"));
        try {
            cluster.getSolrClient().request(CollectionAdminRequest.reloadCollection(COLLECTION).setBasicAuthCredentials("harry", "Cool12345"));
            fail("This should not succeed");
        } catch (HttpSolrClient.RemoteSolrException e) {
        }
        executeCommand(baseUrl + authzPrefix, cl, "{set-permission : { name : update , role : admin}}", "harry", "HarryIsUberCool");
        SolrInputDocument doc = new SolrInputDocument();
        doc.setField("id", "4");
        UpdateRequest update = new UpdateRequest();
        update.setBasicAuthCredentials("harry", "HarryIsUberCool");
        update.add(doc);
        update.setCommitWithin(100);
        cluster.getSolrClient().request(update, COLLECTION);
        executeCommand(baseUrl + authcPrefix, cl, "{set-property : { blockUnknown: true}}", "harry", "HarryIsUberCool");
        verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/blockUnknown", "true", 20, "harry", "HarryIsUberCool");
        verifySecurityStatus(cl, baseUrl + "/admin/info/key?wt=json", "key", NOT_NULL_PREDICATE, 20);
        String[] toolArgs = new String[] { "status", "-solr", baseUrl };
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream stdoutSim = new PrintStream(baos, true, StandardCharsets.UTF_8.name());
        SolrCLI.StatusTool tool = new SolrCLI.StatusTool(stdoutSim);
        try {
            System.setProperty("basicauth", "harry:HarryIsUberCool");
            tool.runTool(SolrCLI.processCommandLineArgs(SolrCLI.joinCommonAndToolOptions(tool.getOptions()), toolArgs));
            Map obj = (Map) Utils.fromJSON(new ByteArrayInputStream(baos.toByteArray()));
            assertTrue(obj.containsKey("version"));
            assertTrue(obj.containsKey("startTime"));
            assertTrue(obj.containsKey("uptime"));
            assertTrue(obj.containsKey("memory"));
        } catch (Exception e) {
            log.error("RunExampleTool failed due to: " + e + "; stdout from tool prior to failure: " + baos.toString(StandardCharsets.UTF_8.name()));
        }
        executeCommand(baseUrl + authcPrefix, cl, "{set-property : { blockUnknown: false}}", "harry", "HarryIsUberCool");
    } finally {
        if (cl != null) {
            HttpClientUtil.close(cl);
        }
    }
}
Also used : GenericSolrRequest(org.apache.solr.client.solrj.request.GenericSolrRequest) HttpPost(org.apache.http.client.methods.HttpPost) SolrRequest(org.apache.solr.client.solrj.SolrRequest) GenericSolrRequest(org.apache.solr.client.solrj.request.GenericSolrRequest) CollectionAdminRequest(org.apache.solr.client.solrj.request.CollectionAdminRequest) SolrCLI(org.apache.solr.util.SolrCLI) ModifiableSolrParams(org.apache.solr.common.params.ModifiableSolrParams) HttpSolrClient(org.apache.solr.client.solrj.impl.HttpSolrClient) SolrInputDocument(org.apache.solr.common.SolrInputDocument) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) PrintStream(java.io.PrintStream) UpdateRequest(org.apache.solr.client.solrj.request.UpdateRequest) JettySolrRunner(org.apache.solr.client.solrj.embedded.JettySolrRunner) HttpResponse(org.apache.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) V2Request(org.apache.solr.client.solrj.request.V2Request) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpClient(org.apache.http.client.HttpClient) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) Test(org.junit.Test)

Example 2 with GenericSolrRequest

use of org.apache.solr.client.solrj.request.GenericSolrRequest in project lucene-solr by apache.

the class BasicAuthStandaloneTest method testBasicAuth.

@Test
@LogLevel("org.apache.solr=DEBUG")
public void testBasicAuth() throws Exception {
    String authcPrefix = "/admin/authentication";
    HttpClient cl = null;
    HttpSolrClient httpSolrClient = null;
    try {
        cl = HttpClientUtil.createClient(null);
        String baseUrl = buildUrl(jetty.getLocalPort(), "/solr");
        httpSolrClient = getHttpSolrClient(baseUrl);
        verifySecurityStatus(cl, baseUrl + authcPrefix, "/errorMessages", null, 20);
        // Write security.json locally. Should cause security to be initialized
        securityConfHandler.persistConf(new SecurityConfHandler.SecurityConfig().setData(Utils.fromJSONString(STD_CONF.replaceAll("'", "\""))));
        securityConfHandler.securityConfEdited();
        verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/class", "solr.BasicAuthPlugin", 20);
        String command = "{\n" + "'set-user': {'harry':'HarryIsCool'}\n" + "}";
        GenericSolrRequest genericReq = new GenericSolrRequest(SolrRequest.METHOD.POST, authcPrefix, new ModifiableSolrParams());
        genericReq.setContentStreams(Collections.singletonList(new ContentStreamBase.ByteArrayStream(command.getBytes(UTF_8), "")));
        HttpSolrClient finalHttpSolrClient = httpSolrClient;
        HttpSolrClient.RemoteSolrException exp = expectThrows(HttpSolrClient.RemoteSolrException.class, () -> {
            finalHttpSolrClient.request(genericReq);
        });
        assertEquals(401, exp.code());
        command = "{\n" + "'set-user': {'harry':'HarryIsUberCool'}\n" + "}";
        HttpPost httpPost = new HttpPost(baseUrl + authcPrefix);
        setBasicAuthHeader(httpPost, "solr", "SolrRocks");
        httpPost.setEntity(new ByteArrayEntity(command.getBytes(UTF_8)));
        httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
        verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication.enabled", "true", 20);
        HttpResponse r = cl.execute(httpPost);
        int statusCode = r.getStatusLine().getStatusCode();
        Utils.consumeFully(r.getEntity());
        assertEquals("proper_cred sent, but access denied", 200, statusCode);
        verifySecurityStatus(cl, baseUrl + authcPrefix, "authentication/credentials/harry", NOT_NULL_PREDICATE, 20);
        // Read file from SOLR_HOME and verify that it contains our new user
        assertTrue(new String(Utils.toJSON(securityConfHandler.getSecurityConfig(false).getData()), Charset.forName("UTF-8")).contains("harry"));
    } finally {
        if (cl != null) {
            HttpClientUtil.close(cl);
            httpSolrClient.close();
        }
    }
}
Also used : HttpSolrClient(org.apache.solr.client.solrj.impl.HttpSolrClient) GenericSolrRequest(org.apache.solr.client.solrj.request.GenericSolrRequest) HttpPost(org.apache.http.client.methods.HttpPost) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) ModifiableSolrParams(org.apache.solr.common.params.ModifiableSolrParams) Test(org.junit.Test) LogLevel(org.apache.solr.util.LogLevel)

Example 3 with GenericSolrRequest

use of org.apache.solr.client.solrj.request.GenericSolrRequest in project lucene-solr by apache.

the class RulesTest method testModifyColl.

@Test
public void testModifyColl() throws Exception {
    final long minGB1 = (random().nextBoolean() ? 1 : 0);
    final long minGB2 = 5;
    assumeTrue("testModifyColl needs minGB1=" + minGB1 + " usable disk space", ImplicitSnitch.getUsableSpaceInGB(Paths.get("/")) > minGB1);
    assumeTrue("testModifyColl needs minGB2=" + minGB2 + " usable disk space", ImplicitSnitch.getUsableSpaceInGB(Paths.get("/")) > minGB2);
    String rulesColl = "modifyColl";
    CollectionAdminRequest.createCollection(rulesColl, "conf", 1, 2).setRule("cores:<4", "node:*,replica:1", "freedisk:>" + minGB1).setSnitch("class:ImplicitSnitch").process(cluster.getSolrClient());
    // TODO: Make a MODIFYCOLLECTION SolrJ class
    ModifiableSolrParams p = new ModifiableSolrParams();
    p.add("collection", rulesColl);
    p.add("action", "MODIFYCOLLECTION");
    p.add("rule", "cores:<5");
    p.add("rule", "node:*,replica:1");
    p.add("rule", "freedisk:>" + minGB2);
    p.add("autoAddReplicas", "true");
    cluster.getSolrClient().request(new GenericSolrRequest(POST, COLLECTIONS_HANDLER_PATH, p));
    DocCollection rulesCollection = getCollectionState(rulesColl);
    log.info("version_of_coll {}  ", rulesCollection.getZNodeVersion());
    List list = (List) rulesCollection.get("rule");
    assertEquals(3, list.size());
    assertEquals("<5", ((Map) list.get(0)).get("cores"));
    assertEquals("1", ((Map) list.get(1)).get("replica"));
    assertEquals(">" + minGB2, ((Map) list.get(2)).get("freedisk"));
    assertEquals("true", String.valueOf(rulesCollection.getProperties().get("autoAddReplicas")));
    list = (List) rulesCollection.get("snitch");
    assertEquals(1, list.size());
    assertEquals("ImplicitSnitch", ((Map) list.get(0)).get("class"));
}
Also used : GenericSolrRequest(org.apache.solr.client.solrj.request.GenericSolrRequest) List(java.util.List) JUnitMatchers.containsString(org.junit.matchers.JUnitMatchers.containsString) DocCollection(org.apache.solr.common.cloud.DocCollection) ModifiableSolrParams(org.apache.solr.common.params.ModifiableSolrParams) Test(org.junit.Test)

Example 4 with GenericSolrRequest

use of org.apache.solr.client.solrj.request.GenericSolrRequest in project lucene-solr by apache.

the class RulesTest method testInvokeApi.

@Test
public void testInvokeApi() throws Exception {
    JettySolrRunner jetty = cluster.getRandomJetty(random());
    try (SolrClient client = getHttpSolrClient(jetty.getBaseUrl().toString())) {
        GenericSolrRequest req = new GenericSolrRequest(GET, "/____v2/node/invoke", new ModifiableSolrParams().add("class", ImplicitSnitch.class.getName()).add("cores", "1").add("freedisk", "1"));
        SimpleSolrResponse rsp = req.process(client);
        assertNotNull(((Map) rsp.getResponse().get(ImplicitSnitch.class.getName())).get("cores"));
        assertNotNull(((Map) rsp.getResponse().get(ImplicitSnitch.class.getName())).get("freedisk"));
    }
}
Also used : GenericSolrRequest(org.apache.solr.client.solrj.request.GenericSolrRequest) SolrClient(org.apache.solr.client.solrj.SolrClient) HttpSolrClient(org.apache.solr.client.solrj.impl.HttpSolrClient) JettySolrRunner(org.apache.solr.client.solrj.embedded.JettySolrRunner) SimpleSolrResponse(org.apache.solr.client.solrj.response.SimpleSolrResponse) ModifiableSolrParams(org.apache.solr.common.params.ModifiableSolrParams) Test(org.junit.Test)

Example 5 with GenericSolrRequest

use of org.apache.solr.client.solrj.request.GenericSolrRequest in project lucene-solr by apache.

the class ServerSnitchContext method invoke.

public SimpleSolrResponse invoke(UpdateShardHandler shardHandler, final String url, String path, SolrParams params) throws IOException, SolrServerException {
    GenericSolrRequest request = new GenericSolrRequest(SolrRequest.METHOD.GET, path, params);
    try (HttpSolrClient client = new HttpSolrClient.Builder(url).withHttpClient(shardHandler.getHttpClient()).withResponseParser(new BinaryResponseParser()).build()) {
        NamedList<Object> rsp = client.request(request);
        request.response.nl = rsp;
        return request.response;
    }
}
Also used : HttpSolrClient(org.apache.solr.client.solrj.impl.HttpSolrClient) GenericSolrRequest(org.apache.solr.client.solrj.request.GenericSolrRequest) BinaryResponseParser(org.apache.solr.client.solrj.impl.BinaryResponseParser)

Aggregations

GenericSolrRequest (org.apache.solr.client.solrj.request.GenericSolrRequest)8 ModifiableSolrParams (org.apache.solr.common.params.ModifiableSolrParams)7 HttpSolrClient (org.apache.solr.client.solrj.impl.HttpSolrClient)6 Test (org.junit.Test)5 SimpleSolrResponse (org.apache.solr.client.solrj.response.SimpleSolrResponse)3 HttpResponse (org.apache.http.HttpResponse)2 HttpClient (org.apache.http.client.HttpClient)2 HttpPost (org.apache.http.client.methods.HttpPost)2 ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)2 JettySolrRunner (org.apache.solr.client.solrj.embedded.JettySolrRunner)2 SolrInputDocument (org.apache.solr.common.SolrInputDocument)2 NamedList (org.apache.solr.common.util.NamedList)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 PrintStream (java.io.PrintStream)1 Collections.singletonMap (java.util.Collections.singletonMap)1 List (java.util.List)1 Map (java.util.Map)1 CharsRefBuilder (org.apache.lucene.util.CharsRefBuilder)1