Skip to content

Service Accounts - Get service account API #71315

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

Merged
merged 5 commits into from
Apr 6, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

package org.elasticsearch.xpack.core.security.action.service;

import org.elasticsearch.action.ActionType;

public class GetServiceAccountAction extends ActionType<GetServiceAccountResponse> {

public static final String NAME = "cluster:admin/xpack/security/service_account/get";
public static final GetServiceAccountAction INSTANCE = new GetServiceAccountAction();

public GetServiceAccountAction() {
super(NAME, GetServiceAccountResponse::new);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

package org.elasticsearch.xpack.core.security.action.service;

import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

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

public class GetServiceAccountRequest extends ActionRequest {

@Nullable
private final String namespace;
@Nullable
private final String serviceName;

public GetServiceAccountRequest(@Nullable String namespace, @Nullable String serviceName) {
this.namespace = namespace;
this.serviceName = serviceName;
}

public GetServiceAccountRequest(StreamInput in) throws IOException {
super(in);
this.namespace = in.readOptionalString();
this.serviceName = in.readOptionalString();
}

public String getNamespace() {
return namespace;
}

public String getServiceName() {
return serviceName;
}

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GetServiceAccountRequest that = (GetServiceAccountRequest) o;
return Objects.equals(namespace, that.namespace) && Objects.equals(serviceName, that.serviceName);
}

@Override
public int hashCode() {
return Objects.hash(namespace, serviceName);
}

@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalString(namespace);
out.writeOptionalString(serviceName);
}

@Override
public ActionRequestValidationException validate() {
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

package org.elasticsearch.xpack.core.security.action.service;

import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor;

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

public class GetServiceAccountResponse extends ActionResponse implements ToXContentObject {

private final Map<String, RoleDescriptor> serviceAccounts;
Copy link
Contributor

Choose a reason for hiding this comment

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

I think this will be easier to expand in the future if we introduce a ServiceAccountInfo object here.

If we do, then the serialization code here stays mostly the same, even as the response evolves.
However, with the code as it is, we would have to introduce some ugly version compat code.

Copy link
Member Author

Choose a reason for hiding this comment

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

Added ServiceAccountInfo as suggested.


public GetServiceAccountResponse(Map<String, RoleDescriptor> serviceAccounts) {
this.serviceAccounts = Objects.requireNonNull(serviceAccounts);
}

public GetServiceAccountResponse(StreamInput in) throws IOException {
super(in);
this.serviceAccounts = in.readMap(StreamInput::readString, RoleDescriptor::new);
}

public Map<String, RoleDescriptor> getServiceAccounts() {
return serviceAccounts;
}

@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeMap(serviceAccounts, StreamOutput::writeString, (o, v) -> v.writeTo(o));
}

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
for (Map.Entry<String, RoleDescriptor> entry: serviceAccounts.entrySet()) {
builder.startObject(entry.getKey());
builder.field("role_descriptor");
entry.getValue().toXContent(builder, params);
builder.endObject();
}
builder.endObject();
return builder;
}

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

@Override
public int hashCode() {
return Objects.hash(serviceAccounts);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

package org.elasticsearch.xpack.core.security.action.service;

import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.test.AbstractWireSerializingTestCase;

import java.io.IOException;

public class GetServiceAccountRequestTests extends AbstractWireSerializingTestCase<GetServiceAccountRequest> {

@Override
protected Writeable.Reader<GetServiceAccountRequest> instanceReader() {
return GetServiceAccountRequest::new;
}

@Override
protected GetServiceAccountRequest createTestInstance() {
return new GetServiceAccountRequest(randomFrom(randomAlphaOfLengthBetween(3, 8), null),
randomFrom(randomAlphaOfLengthBetween(3, 8), null));
}

@Override
protected GetServiceAccountRequest mutateInstance(GetServiceAccountRequest instance) throws IOException {
if (randomBoolean()) {
return new GetServiceAccountRequest(
randomValueOtherThan(instance.getNamespace(), () -> randomFrom(randomAlphaOfLengthBetween(3, 8), null)),
instance.getServiceName());
} else {
return new GetServiceAccountRequest(
instance.getNamespace(),
randomValueOtherThan(instance.getServiceName(), () -> randomFrom(randomAlphaOfLengthBetween(3, 8), null)));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

package org.elasticsearch.xpack.core.security.action.service;

import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.AbstractWireSerializingTestCase;
import org.elasticsearch.test.XContentTestUtils;
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor;

import java.io.IOException;
import java.util.Map;

import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.equalTo;

public class GetServiceAccountResponseTests extends AbstractWireSerializingTestCase<GetServiceAccountResponse> {

@Override
protected Writeable.Reader<GetServiceAccountResponse> instanceReader() {
return GetServiceAccountResponse::new;
}

@Override
protected GetServiceAccountResponse createTestInstance() {
final String principal = randomPrincipal();
return new GetServiceAccountResponse(randomBoolean() ? Map.of(principal, getRoleDescriptorFor(principal)) : Map.of());
}

@Override
protected GetServiceAccountResponse mutateInstance(GetServiceAccountResponse instance) throws IOException {
if (instance.getServiceAccounts().isEmpty()) {
final String principal = randomPrincipal();
return new GetServiceAccountResponse(Map.of(principal, getRoleDescriptorFor(principal)));
} else {
return new GetServiceAccountResponse(Map.of());
}
}

@SuppressWarnings("unchecked")
public void testToXContent() throws IOException {
final GetServiceAccountResponse response = createTestInstance();
XContentBuilder builder = XContentFactory.jsonBuilder();
response.toXContent(builder, ToXContent.EMPTY_PARAMS);
final Map<String, Object> responseMap = XContentHelper.convertToMap(
BytesReference.bytes(builder),
false, builder.contentType()).v2();
final Map<String, RoleDescriptor> serviceAccounts = response.getServiceAccounts();
if (serviceAccounts.isEmpty()) {
assertThat(responseMap, anEmptyMap());
} else {
assertThat(responseMap.size(), equalTo(serviceAccounts.size()));
assertThat(responseMap.keySet(), equalTo(serviceAccounts.keySet()));
for (String key : responseMap.keySet()) {
assertRoleDescriptorEquals((Map<String, Object>) responseMap.get(key), serviceAccounts.get(key));
}
}
}

private String randomPrincipal() {
return randomAlphaOfLengthBetween(3, 8) + "/" + randomAlphaOfLengthBetween(3, 8);
}

private RoleDescriptor getRoleDescriptorFor(String name) {
return new RoleDescriptor(name,
new String[] { "monitor", "manage_own_api_key" },
new RoleDescriptor.IndicesPrivileges[] {
RoleDescriptor.IndicesPrivileges.builder()
.indices("logs-*", "metrics-*", "traces-*")
.privileges("write", "create_index", "auto_configure").build() },
null,
null,
null,
null,
null);
}

private void assertRoleDescriptorEquals(Map<String, Object> responseFragment, RoleDescriptor roleDescriptor) throws IOException {
@SuppressWarnings("unchecked")
final Map<String, Object> descriptorMap = (Map<String, Object>) responseFragment.get("role_descriptor");
assertThat(RoleDescriptor.parse(roleDescriptor.getName(),
XContentTestUtils.convertToXContent(descriptorMap, XContentType.JSON), false, XContentType.JSON),
equalTo(roleDescriptor));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ public class Constants {
"cluster:admin/xpack/security/saml/invalidate",
"cluster:admin/xpack/security/saml/logout",
"cluster:admin/xpack/security/saml/prepare",
"cluster:admin/xpack/security/service_account/get",
"cluster:admin/xpack/security/service_account/token/create",
"cluster:admin/xpack/security/service_account/token/get",
"cluster:admin/xpack/security/token/create",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.util.Map;

import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
Expand Down Expand Up @@ -61,6 +62,36 @@ public class ServiceAccountIT extends ESRestTestCase {
+ " \"authentication_type\": \"token\"\n"
+ "}\n";

private static final String ELASTIC_FLEET_ROLE_DESCRIPTOR = ""
+ "{\n"
+ " \"cluster\": [\n"
+ " \"monitor\",\n"
+ " \"manage_own_api_key\"\n"
+ " ],\n"
+ " \"indices\": [\n"
+ " {\n"
+ " \"names\": [\n"
+ " \"logs-*\",\n"
+ " \"metrics-*\",\n"
+ " \"traces-*\"\n"
+ " ],\n"
+ " \"privileges\": [\n"
+ " \"write\",\n"
+ " \"create_index\",\n"
+ " \"auto_configure\"\n"
+ " ],\n"
+ " \"allow_restricted_indices\": false\n"
+ " }\n"
+ " ],\n"
+ " \"applications\": [],\n"
+ " \"run_as\": [],\n"
+ " \"metadata\": {},\n"
+ " \"transient_metadata\": {\n"
+ " \"enabled\": true\n"
+ " }\n"
+ " }\n"
+ " }";

@BeforeClass
public static void init() throws URISyntaxException, FileNotFoundException {
URL resource = ServiceAccountIT.class.getResource("/ssl/ca.crt");
Expand All @@ -84,6 +115,32 @@ protected Settings restClientSettings() {
.build();
}

public void testGetServiceAccount() throws IOException {
final Request getServiceAccountRequest1 = new Request("GET", "_security/service");
final Response getServiceAccountResponse1 = client().performRequest(getServiceAccountRequest1);
assertOK(getServiceAccountResponse1);
assertServiceAccountRoleDescriptor(getServiceAccountResponse1,
"elastic/fleet-server", ELASTIC_FLEET_ROLE_DESCRIPTOR);

final Request getServiceAccountRequest2 = new Request("GET", "_security/service/elastic");
final Response getServiceAccountResponse2 = client().performRequest(getServiceAccountRequest2);
assertOK(getServiceAccountResponse2);
assertServiceAccountRoleDescriptor(getServiceAccountResponse2,
"elastic/fleet-server", ELASTIC_FLEET_ROLE_DESCRIPTOR);

final Request getServiceAccountRequest3 = new Request("GET", "_security/service/elastic/fleet-server");
final Response getServiceAccountResponse3 = client().performRequest(getServiceAccountRequest3);
assertOK(getServiceAccountResponse3);
assertServiceAccountRoleDescriptor(getServiceAccountResponse3,
"elastic/fleet-server", ELASTIC_FLEET_ROLE_DESCRIPTOR);

final String requestPath = "_security/service/" + randomFrom("foo", "elastic/foo", "foo/bar");
final Request getServiceAccountRequest4 = new Request("GET", requestPath);
final Response getServiceAccountResponse4 = client().performRequest(getServiceAccountRequest4);
assertOK(getServiceAccountResponse4);
assertThat(responseAsMap(getServiceAccountResponse4), anEmptyMap());
}

public void testAuthenticate() throws IOException {
final Request request = new Request("GET", "_security/_authenticate");
request.setOptions(RequestOptions.DEFAULT.toBuilder().addHeader("Authorization", "Bearer " + VALID_SERVICE_TOKEN));
Expand Down Expand Up @@ -290,4 +347,12 @@ private void assertApiKeys(String apiKeyId, String name, boolean invalidated,
assertThat(apiKey.get("realm"), equalTo("service_account"));
assertThat(apiKey.get("invalidated"), is(invalidated));
}

private void assertServiceAccountRoleDescriptor(Response response,
String serviceAccountPrincipal,
String roleDescriptorString) throws IOException {
final Map<String, Object> responseMap = responseAsMap(response);
assertThat(responseMap, hasEntry(serviceAccountPrincipal, Map.of("role_descriptor",
XContentHelper.convertToMap(new BytesArray(roleDescriptorString), false, XContentType.JSON).v2())));
}
}
Loading