Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions client/rest-high-level/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ integTestCluster {
systemProperty 'es.scripting.update.ctx_in_params', 'false'
setting 'xpack.license.self_generated.type', 'trial'
setting 'xpack.security.enabled', 'true'
setting 'xpack.security.authc.token.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'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,24 +20,26 @@
package org.elasticsearch.client;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.client.security.ChangePasswordRequest;
import org.elasticsearch.client.security.ClearRolesCacheRequest;
import org.elasticsearch.client.security.ClearRolesCacheResponse;
import org.elasticsearch.client.security.CreateTokenRequest;
import org.elasticsearch.client.security.CreateTokenResponse;
import org.elasticsearch.client.security.DeleteRoleMappingRequest;
import org.elasticsearch.client.security.DeleteRoleMappingResponse;
import org.elasticsearch.client.security.DeleteRoleRequest;
import org.elasticsearch.client.security.DeleteRoleResponse;
import org.elasticsearch.client.security.PutRoleMappingRequest;
import org.elasticsearch.client.security.PutRoleMappingResponse;
import org.elasticsearch.client.security.DisableUserRequest;
import org.elasticsearch.client.security.EmptyResponse;
import org.elasticsearch.client.security.EnableUserRequest;
import org.elasticsearch.client.security.GetRoleMappingsRequest;
import org.elasticsearch.client.security.GetRoleMappingsResponse;
import org.elasticsearch.client.security.GetSslCertificatesRequest;
import org.elasticsearch.client.security.GetSslCertificatesResponse;
import org.elasticsearch.client.security.PutRoleMappingRequest;
import org.elasticsearch.client.security.PutRoleMappingResponse;
import org.elasticsearch.client.security.PutUserRequest;
import org.elasticsearch.client.security.PutUserResponse;
import org.elasticsearch.client.security.ChangePasswordRequest;
import org.elasticsearch.client.security.DeleteRoleMappingRequest;
import org.elasticsearch.client.security.DeleteRoleMappingResponse;

import java.io.IOException;

Expand Down Expand Up @@ -350,4 +352,32 @@ public void deleteRoleAsync(DeleteRoleRequest request, RequestOptions options, A
DeleteRoleResponse::fromXContent, listener, singleton(404));
}

/**
* Creates an OAuth2 token.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-token.html">
* the docs</a> for more.
*
* @param request the request for the token
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response from the create token call
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public CreateTokenResponse createToken(CreateTokenRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, SecurityRequestConverters::createToken, options,
CreateTokenResponse::fromXContent, emptySet());
}

/**
* Asynchronously creates an OAuth2 token.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-token.html">
* the docs</a> for more.
*
* @param request the request for the token
* @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 createTokenAsync(CreateTokenRequest request, RequestOptions options, ActionListener<CreateTokenResponse> listener) {
restHighLevelClient.performRequestAsyncAndParseEntity(request, SecurityRequestConverters::createToken, options,
CreateTokenResponse::fromXContent, listener, emptySet());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.elasticsearch.client.security.ClearRolesCacheRequest;
import org.elasticsearch.client.security.CreateTokenRequest;
import org.elasticsearch.client.security.DeleteRoleMappingRequest;
import org.elasticsearch.client.security.DeleteRoleRequest;
import org.elasticsearch.client.security.PutRoleMappingRequest;
Expand Down Expand Up @@ -140,4 +141,10 @@ static Request deleteRole(DeleteRoleRequest deleteRoleRequest) {
params.withRefreshPolicy(deleteRoleRequest.getRefreshPolicy());
return request;
}

static Request createToken(CreateTokenRequest createTokenRequest) throws IOException {
Request request = new Request(HttpPost.METHOD_NAME, "/_xpack/security/oauth2/token");
request.setEntity(createEntity(createTokenRequest, REQUEST_BODY_CONTENT_TYPE));
return request;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/*
* 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.Validatable;
import org.elasticsearch.common.CharArrays;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;

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

/**
* Request to create a new OAuth2 token from the Elasticsearch cluster.
*/
public final class CreateTokenRequest implements Validatable, ToXContentObject {

private final String grantType;
private final String scope;
private final String username;
private final char[] password;
private final String refreshToken;

/**
* General purpose constructor. This constructor is typically not useful, and one of the following factory methods should be used
* instead:
* <ul>
* <li>{@link #passwordGrant(String, char[])}</li>
* <li>{@link #refreshTokenGrant(String)}</li>
* <li>{@link #clientCredentialsGrant()}</li>
* </ul>
*/
public CreateTokenRequest(String grantType, @Nullable String scope, @Nullable String username, @Nullable char[] password,
@Nullable String refreshToken) {
if (Strings.isNullOrEmpty(grantType)) {
throw new IllegalArgumentException("grant_type is required");
}
this.grantType = grantType;
this.username = username;
this.password = password;
this.scope = scope;
this.refreshToken = refreshToken;
}

public static CreateTokenRequest passwordGrant(String username, char[] password) {
if (Strings.isNullOrEmpty(username)) {
throw new IllegalArgumentException("username is required");
}
if (password == null || password.length == 0) {
throw new IllegalArgumentException("password is required");
}
return new CreateTokenRequest("password", null, username, password, null);
}

public static CreateTokenRequest refreshTokenGrant(String refreshToken) {
if (Strings.isNullOrEmpty(refreshToken)) {
throw new IllegalArgumentException("refresh_token is required");
}
return new CreateTokenRequest("refresh_token", null, null, null, refreshToken);
}

public static CreateTokenRequest clientCredentialsGrant() {
return new CreateTokenRequest("client_credentials", null, null, null, null);
}

public String getGrantType() {
return grantType;
}

public String getScope() {
return scope;
}

public String getUsername() {
return username;
}

public char[] getPassword() {
return password;
}

public String getRefreshToken() {
return refreshToken;
}

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject()
.field("grant_type", grantType);
if (scope != null) {
builder.field("scope", scope);
}
if (username != null) {
builder.field("username", username);
}
if (password != null) {
byte[] passwordBytes = CharArrays.toUtf8Bytes(password);
try {
builder.field("password").utf8Value(passwordBytes, 0, passwordBytes.length);
} finally {
Arrays.fill(passwordBytes, (byte) 0);
}
}
if (refreshToken != null) {
builder.field("refresh_token", refreshToken);
}
return builder.endObject();
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final CreateTokenRequest that = (CreateTokenRequest) o;
return Objects.equals(grantType, that.grantType) &&
Objects.equals(scope, that.scope) &&
Objects.equals(username, that.username) &&
Arrays.equals(password, that.password) &&
Objects.equals(refreshToken, that.refreshToken);
}

@Override
public int hashCode() {
int result = Objects.hash(grantType, scope, username, refreshToken);
result = 31 * result + Arrays.hashCode(password);
return result;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* 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.common.ParseField;
import org.elasticsearch.common.unit.TimeValue;
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;
import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg;

/**
* Response when creating a new OAuth2 token in the Elasticsearch cluster. Contains an access token, the token's expiry, and an optional
* refresh token.
*/
public final class CreateTokenResponse {

private final String accessToken;
private final String type;
private final TimeValue expiresIn;
private final String scope;
private final String refreshToken;

public CreateTokenResponse(String accessToken, String type, TimeValue expiresIn, String scope, String refreshToken) {
this.accessToken = accessToken;
this.type = type;
this.expiresIn = expiresIn;
this.scope = scope;
this.refreshToken = refreshToken;
}

public String getAccessToken() {
return accessToken;
}

public String getType() {
return type;
}

public TimeValue getExpiresIn() {
return expiresIn;
}

public String getScope() {
return scope;
}

public String getRefreshToken() {
return refreshToken;
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final CreateTokenResponse that = (CreateTokenResponse) o;
return Objects.equals(accessToken, that.accessToken) &&
Objects.equals(type, that.type) &&
Objects.equals(expiresIn, that.expiresIn) &&
Objects.equals(scope, that.scope) &&
Objects.equals(refreshToken, that.refreshToken);
}

@Override
public int hashCode() {
return Objects.hash(accessToken, type, expiresIn, scope, refreshToken);
}

private static final ConstructingObjectParser<CreateTokenResponse, Void> PARSER = new ConstructingObjectParser<>(
"create_token_response", true, args -> new CreateTokenResponse(
(String) args[0], (String) args[1], TimeValue.timeValueSeconds((Long) args[2]), (String) args[3], (String) args[4]));

static {
PARSER.declareString(constructorArg(), new ParseField("access_token"));
PARSER.declareString(constructorArg(), new ParseField("type"));
PARSER.declareLong(constructorArg(), new ParseField("expires_in"));
PARSER.declareStringOrNull(optionalConstructorArg(), new ParseField("scope"));
PARSER.declareStringOrNull(optionalConstructorArg(), new ParseField("refresh_token"));
}

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

Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.elasticsearch.client.security.CreateTokenRequest;
import org.elasticsearch.client.security.DeleteRoleMappingRequest;
import org.elasticsearch.client.security.DeleteRoleRequest;
import org.elasticsearch.client.security.DisableUserRequest;
Expand Down Expand Up @@ -211,4 +212,34 @@ public void testDeleteRole() {
assertEquals(expectedParams, request.getParameters());
assertNull(request.getEntity());
}

public void testCreateTokenWithPasswordGrant() throws Exception {
final String username = randomAlphaOfLengthBetween(1, 12);
final String password = randomAlphaOfLengthBetween(8, 12);
CreateTokenRequest createTokenRequest = CreateTokenRequest.passwordGrant(username, password.toCharArray());
Request request = SecurityRequestConverters.createToken(createTokenRequest);
assertEquals(HttpPost.METHOD_NAME, request.getMethod());
assertEquals("/_xpack/security/oauth2/token", request.getEndpoint());
assertEquals(0, request.getParameters().size());
assertToXContentBody(createTokenRequest, request.getEntity());
}

public void testCreateTokenWithRefreshTokenGrant() throws Exception {
final String refreshToken = randomAlphaOfLengthBetween(8, 24);
CreateTokenRequest createTokenRequest = CreateTokenRequest.refreshTokenGrant(refreshToken);
Request request = SecurityRequestConverters.createToken(createTokenRequest);
assertEquals(HttpPost.METHOD_NAME, request.getMethod());
assertEquals("/_xpack/security/oauth2/token", request.getEndpoint());
assertEquals(0, request.getParameters().size());
assertToXContentBody(createTokenRequest, request.getEntity());
}

public void testCreateTokenWithClientCredentialsGrant() throws Exception {
CreateTokenRequest createTokenRequest = CreateTokenRequest.clientCredentialsGrant();
Request request = SecurityRequestConverters.createToken(createTokenRequest);
assertEquals(HttpPost.METHOD_NAME, request.getMethod());
assertEquals("/_xpack/security/oauth2/token", request.getEndpoint());
assertEquals(0, request.getParameters().size());
assertToXContentBody(createTokenRequest, request.getEntity());
}
}
Loading