Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HLRC: Get SSL Certificates API #34135

Merged
merged 13 commits into from
Oct 15, 2018
8 changes: 8 additions & 0 deletions client/rest-high-level/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ forbiddenApisMain {
addSignatureFiles 'http-signatures'
signaturesFiles += files('src/main/resources/forbidden/rest-high-level-signatures.txt')
}
File nodeCert = file("./testnode.crt")
File nodeTrustStore = file("./testnode.jks")

integTestRunner {
systemProperty 'tests.rest.cluster.username', System.getProperty('tests.rest.cluster.username', 'test_user')
Expand All @@ -85,11 +87,17 @@ integTestRunner {
integTestCluster {
setting 'xpack.license.self_generated.type', 'trial'
setting 'xpack.security.enabled', 'true'
// Truststore settings are not used since TLS is not enabled. Included for testing the get certificates API
setting 'xpack.ssl.certificate_authorities', 'testnode.crt'
setting 'xpack.security.transport.ssl.truststore.path', 'testnode.jks'
setting 'xpack.security.transport.ssl.truststore.password', 'testnode'
setupCommand 'setupDummyUser',
'bin/elasticsearch-users',
'useradd', System.getProperty('tests.rest.cluster.username', 'test_user'),
'-p', System.getProperty('tests.rest.cluster.password', 'test-password'),
'-r', 'superuser'
extraConfigFile nodeCert.name, nodeCert
extraConfigFile nodeTrustStore.name, nodeTrustStore
waitCondition = { node, ant ->
File tmpFile = new File(node.cwd, 'wait.success')
ant.get(src: "http://${node.httpUri()}/_cluster/health?wait_for_nodes=>=${numNodes}&wait_for_status=yellow",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.client;

import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;

public class EmptyBodyRequest implements Validatable, ToXContentObject {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gracefully borrowed from #33552


@Override
public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.startObject().endObject();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.client.security.DisableUserRequest;
import org.elasticsearch.client.security.EnableUserRequest;
import org.elasticsearch.client.security.GetSslCertificatesRequest;
import org.elasticsearch.client.security.GetSslCertificatesResponse;
import org.elasticsearch.client.security.PutUserRequest;
import org.elasticsearch.client.security.PutUserResponse;
import org.elasticsearch.client.security.EmptyResponse;
Expand Down Expand Up @@ -125,4 +127,31 @@ public void disableUserAsync(DisableUserRequest request, RequestOptions options,
restHighLevelClient.performRequestAsyncAndParseEntity(request, SecurityRequestConverters::disableUser, options,
EmptyResponse::fromXContent, listener, emptySet());
}

/**
* Synchronously retrieve the X.509 certificates that are used to encrypt communications in an Elasticsearch cluster.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-ssl.html">
* the docs</a> for more.
*
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response from the get certificates call
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public GetSslCertificatesResponse getSslCertificates(RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(GetSslCertificatesRequest.INSTANCE, GetSslCertificatesRequest::getRequest,
options, GetSslCertificatesResponse::fromXContent, emptySet());
}

/**
* Asynchronously retrieve the X.509 certificates that are used to encrypt communications in an Elasticsearch cluster.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-ssl.html">
* the docs</a> for more.
*
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public void getSslCertificatesAsync(RequestOptions options, ActionListener<GetSslCertificatesResponse> listener) {
restHighLevelClient.performRequestAsyncAndParseEntity(GetSslCertificatesRequest.INSTANCE, GetSslCertificatesRequest::getRequest,
options, GetSslCertificatesResponse::fromXContent, listener, emptySet());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.client.security;

import org.apache.http.client.methods.HttpGet;
import org.elasticsearch.client.EmptyBodyRequest;
import org.elasticsearch.client.Request;

public class GetSslCertificatesRequest extends EmptyBodyRequest {

public static final GetSslCertificatesRequest INSTANCE = new GetSslCertificatesRequest();
private final Request request;

private GetSslCertificatesRequest() {
request = new Request(HttpGet.METHOD_NAME, "/_xpack/ssl/certificates");
}

public Request getRequest() {
return request;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.client.security;

import org.elasticsearch.client.security.support.CertificateInfo;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.DeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class GetSslCertificatesResponse {

private final List<CertificateInfo> certificates;

public GetSslCertificatesResponse(List<CertificateInfo> certificates) {
this.certificates = certificates;
}

private static final DeprecationHandler DEPRECATION_HANDLER = new DeprecationHandler() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be added to DeprecationHandler as NOOP_DEPRECATION_HANDLER just like we have THROW_UNSUPPORTED_OPERATION so if need be others can use it, WDYT?


@Override
public void usedDeprecatedName(String usedName, String modernName) {
}

@Override
public void usedDeprecatedField(String usedName, String replacedWith) {
}
};

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final GetSslCertificatesResponse that = (GetSslCertificatesResponse) o;
return Objects.equals(this.certificates, that.certificates);
}

@Override
public int hashCode() {
return Objects.hash(certificates);
}

public static GetSslCertificatesResponse fromXContent(XContentParser parser) throws IOException {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't use ConstructingObjectParser as this API returns an array of Objects

List<Object> unparsedCerts = parser.list();
if (unparsedCerts.isEmpty()) {
return new GetSslCertificatesResponse(Collections.emptyList());
}
List<CertificateInfo> certificates = new ArrayList<>();
for (Object cert : unparsedCerts) {
try (XContentBuilder builder = XContentFactory.jsonBuilder()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am confused, why can't we just parse using the passed in parser?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because ConstructingObjectParser expects a parser with Objects in its parse() method but we get an list of objects in the parser. So I had to get the list from the passed in parser and parse each one.
Does this make sense?

Copy link
Contributor

@tvernum tvernum Oct 4, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But ConstructingObjectParser can just parse a single node within the parser stream, so you can do something like this (untested, minimal error checking):

XContentParserUtils.ensureExpectedToken( Token.START_ARRAY, parser.currentToken(), parser::getTokenLocation);
while (parser.nextToken() != Token.END_ARRAY) {
   certificates.add( CertificateInfo.PARSER.parse(parser, null) );
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Tim said is what I had in mind

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gotcha, thanks! I didn't know I could do that. Now that you mentioned it, I saw this being used elsewhere and it makes total sense too.

@SuppressWarnings("unchecked")
Map<String, ?> value = (Map<String, ?>) cert;
builder.map(value);
try (XContentParser certificateInfoParser = XContentFactory.xContent(builder.contentType()).createParser(
NamedXContentRegistry.EMPTY, DEPRECATION_HANDLER, Strings.toString(builder))) {
certificates.add(CertificateInfo.PARSER.parse(certificateInfoParser, null));
}
}
}
return new GetSslCertificatesResponse(certificates);
}

public List<CertificateInfo> getCertificates() {
return certificates;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.client.security.support;

import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
import java.util.Objects;

import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;

/**
* Simple model of an X.509 certificate
*/
public class CertificateInfo {
public static final ParseField PATH = new ParseField("path");
public static final ParseField FORMAT = new ParseField("format");
public static final ParseField ALIAS = new ParseField("alias");
public static final ParseField SUBJECT_DN = new ParseField("subject_dn");
public static final ParseField SERIAL_NUMBER = new ParseField("serial_number");
public static final ParseField HAS_PRIVATE_KEY = new ParseField("has_private_key");
public static final ParseField EXPIRY = new ParseField("expiry");

private final String path;
private final String format;
private final String alias;
private final String subjectDn;
private final String serialNumber;
private final boolean hasPrivateKey;
private final String expiry;

public CertificateInfo(String path, String format, @Nullable String alias, String subjectDn, String serialNumber, boolean hasPrivateKey,
String expiry) {
this.path = path;
this.format = format;
this.alias = alias;
this.subjectDn = subjectDn;
this.serialNumber = serialNumber;
this.hasPrivateKey = hasPrivateKey;
this.expiry = expiry;
}

public String getPath() {
return path;
}

public String getFormat() {
return format;
}

public String getAlias() {
return alias;
}

public String getSubjectDn() {
return subjectDn;
}

public String getSerialNumber() {
return serialNumber;
}

public boolean isHasPrivateKey() {
return hasPrivateKey;
}

public String getExpiry() {
return expiry;
}

jkakavas marked this conversation as resolved.
Show resolved Hide resolved

@SuppressWarnings("unchecked")
public static final ConstructingObjectParser<CertificateInfo, Void> PARSER = new ConstructingObjectParser<>("certificate_info",
true, args -> new CertificateInfo((String) args[0], (String) args[1], (String) args[2], (String) args[3], (String) args[4],
(boolean) args[5], (String) args[6]));

static {
PARSER.declareString(constructorArg(), PATH);
PARSER.declareString(constructorArg(), FORMAT);
PARSER.declareStringOrNull(constructorArg(), ALIAS);
PARSER.declareString(constructorArg(), SUBJECT_DN);
PARSER.declareString(constructorArg(), SERIAL_NUMBER);
PARSER.declareBoolean(constructorArg(), HAS_PRIVATE_KEY);
PARSER.declareString(constructorArg(), EXPIRY);
}

@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}

final CertificateInfo that = (CertificateInfo) other;
return this.path.equals(that.path)
&& this.format.equals(that.format)
&& this.hasPrivateKey == that.hasPrivateKey
&& Objects.equals(this.alias, that.alias)
&& this.serialNumber.equals(that.serialNumber)
&& this.subjectDn.equals(that.subjectDn)
&& this.expiry.equals(that.expiry);
}

@Override
public int hashCode() {
return Objects.hash(path, format, alias, subjectDn, serialNumber, hasPrivateKey, expiry);
}

jkakavas marked this conversation as resolved.
Show resolved Hide resolved

public static CertificateInfo fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
}
Loading