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

Refactor role descriptor parsing #107430

Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ public String toString() {
+ "]";
}

private static final RoleDescriptor.Parser ROLE_DESCRIPTOR_PARSER = RoleDescriptor.parserBuilder().allowRestriction(true).build();
static final ConstructingObjectParser<ApiKey, Void> PARSER;
static {
PARSER = new ConstructingObjectParser<>("api_key", true, ApiKey::new);
Expand All @@ -419,7 +420,7 @@ static int initializeParser(AbstractObjectParser<?, Void> parser) {
parser.declareObject(optionalConstructorArg(), (p, c) -> p.map(), new ParseField("metadata"));
parser.declareNamedObjects(optionalConstructorArg(), (p, c, n) -> {
p.nextToken();
return RoleDescriptor.parse(n, p, false);
return ROLE_DESCRIPTOR_PARSER.parse(n, p);
}, new ParseField("role_descriptors"));
parser.declareField(
optionalConstructorArg(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ public interface BulkUpdateApiKeyRequestTranslator {
BulkUpdateApiKeyRequest translate(RestRequest request) throws IOException;

class Default implements BulkUpdateApiKeyRequestTranslator {
private static final RoleDescriptor.Parser ROLE_DESCRIPTOR_PARSER = RoleDescriptor.parserBuilder().allowRestriction(true).build();
private static final ConstructingObjectParser<BulkUpdateApiKeyRequest, Void> PARSER = createParser(
(n, p) -> RoleDescriptor.parse(n, p, false)
(n, p) -> ROLE_DESCRIPTOR_PARSER.parse(n, p)
);

@SuppressWarnings("unchecked")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,8 @@
* Request builder for populating a {@link CreateApiKeyRequest}
*/
public class CreateApiKeyRequestBuilder extends ActionRequestBuilder<CreateApiKeyRequest, CreateApiKeyResponse> {
private static final ConstructingObjectParser<CreateApiKeyRequest, Void> PARSER = createParser(
(n, p) -> RoleDescriptor.parse(n, p, false)
);
private static final RoleDescriptor.Parser ROLE_DESCRIPTOR_PARSER = RoleDescriptor.parserBuilder().allowRestriction(true).build();
private static final ConstructingObjectParser<CreateApiKeyRequest, Void> PARSER = createParser(ROLE_DESCRIPTOR_PARSER::parse);

@SuppressWarnings("unchecked")
public static ConstructingObjectParser<CreateApiKeyRequest, Void> createParser(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ public interface UpdateApiKeyRequestTranslator {
UpdateApiKeyRequest translate(RestRequest request) throws IOException;

class Default implements UpdateApiKeyRequestTranslator {
private static final ConstructingObjectParser<Payload, Void> PARSER = createParser((n, p) -> RoleDescriptor.parse(n, p, false));
private static final RoleDescriptor.Parser ROLE_DESCRIPTOR_PARSER = RoleDescriptor.parserBuilder().allowRestriction(true).build();
private static final ConstructingObjectParser<Payload, Void> PARSER = createParser(ROLE_DESCRIPTOR_PARSER::parse);

@SuppressWarnings("unchecked")
protected static ConstructingObjectParser<Payload, Void> createParser(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
*/
public class PutRoleRequestBuilder extends ActionRequestBuilder<PutRoleRequest, PutRoleResponse> {

private static final RoleDescriptor.Parser ROLE_DESCRIPTOR_PARSER = RoleDescriptor.parserBuilder().build();

public PutRoleRequestBuilder(ElasticsearchClient client) {
super(client, PutRoleAction.INSTANCE, new PutRoleRequest());
}
Expand All @@ -29,9 +31,8 @@ public PutRoleRequestBuilder(ElasticsearchClient client) {
* Populate the put role request from the source and the role's name
*/
public PutRoleRequestBuilder source(String name, BytesReference source, XContentType xContentType) throws IOException {
// we pass false as last parameter because we want to reject the request if field permissions
// are given in 2.x syntax
RoleDescriptor descriptor = RoleDescriptor.parse(name, source, false, xContentType, false);
// we want to reject the request if field permissions are given in 2.x syntax, hence we do not allow2xFormat
RoleDescriptor descriptor = ROLE_DESCRIPTOR_PARSER.parse(name, source, xContentType);
assert name.equals(descriptor.getName());
request.name(name);
request.cluster(descriptor.getClusterPrivileges());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ private void validate() {
public static final class RoleDescriptorsBytes implements Writeable {

public static final RoleDescriptorsBytes EMPTY = new RoleDescriptorsBytes(new BytesArray("{}"));

private static final RoleDescriptor.Parser ROLE_DESCRIPTOR_PARSER = RoleDescriptor.parserBuilder().build();

private final BytesReference rawBytes;

public RoleDescriptorsBytes(BytesReference rawBytes) {
Expand Down Expand Up @@ -263,7 +266,7 @@ public Set<RoleDescriptor> toRoleDescriptors() {
while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
parser.nextToken();
final String roleName = parser.currentName();
roleDescriptors.add(RoleDescriptor.parse(roleName, parser, false));
roleDescriptors.add(ROLE_DESCRIPTOR_PARSER.parse(roleName, parser));
}
return Set.copyOf(roleDescriptors);
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -420,109 +420,135 @@ public void writeTo(StreamOutput out) throws IOException {
}
}

public static RoleDescriptor parse(String name, BytesReference source, boolean allow2xFormat, XContentType xContentType)
throws IOException {
return parse(name, source, allow2xFormat, xContentType, true);
public static Parser.Builder parserBuilder() {
return new Parser.Builder();
}

public static RoleDescriptor parse(
String name,
BytesReference source,
boolean allow2xFormat,
XContentType xContentType,
boolean allowRestriction
) throws IOException {
assert name != null;
try (XContentParser parser = createParser(source, xContentType)) {
return parse(name, parser, allow2xFormat, allowRestriction);
}
}
public record Parser(boolean allow2xFormat, boolean allowRestriction) {

public static RoleDescriptor parse(String name, XContentParser parser, boolean allow2xFormat) throws IOException {
return parse(name, parser, allow2xFormat, true);
}
public static final class Builder {
private boolean allow2xFormat = false;
private boolean allowRestriction = false;

private Builder() {}

public Builder allow2xFormat(boolean allow2xFormat) {
this.allow2xFormat = allow2xFormat;
return this;
}

public Builder allowRestriction(boolean allowRestriction) {
this.allowRestriction = allowRestriction;
return this;
}

public Parser build() {
return new Parser(allow2xFormat, allowRestriction);
}

public static RoleDescriptor parse(String name, XContentParser parser, boolean allow2xFormat, boolean allowRestriction)
throws IOException {
// validate name
Validation.Error validationError = Validation.Roles.validateRoleName(name, true);
if (validationError != null) {
ValidationException ve = new ValidationException();
ve.addValidationError(validationError.toString());
throw ve;
}

// advance to the START_OBJECT token if needed
XContentParser.Token token = parser.currentToken() == null ? parser.nextToken() : parser.currentToken();
if (token != XContentParser.Token.START_OBJECT) {
throw new ElasticsearchParseException("failed to parse role [{}]. expected an object but found [{}] instead", name, token);
public RoleDescriptor parse(String name, BytesReference source, XContentType xContentType) throws IOException {
assert name != null;
try (
XContentParser parser = XContentHelper.createParserNotCompressed(
LoggingDeprecationHandler.XCONTENT_PARSER_CONFIG,
source,
xContentType
)
) {
return parse(name, parser);
}
}
String currentFieldName = null;
IndicesPrivileges[] indicesPrivileges = null;
RemoteIndicesPrivileges[] remoteIndicesPrivileges = null;
String[] clusterPrivileges = null;
List<ConfigurableClusterPrivilege> configurableClusterPrivileges = Collections.emptyList();
ApplicationResourcePrivileges[] applicationPrivileges = null;
String[] runAsUsers = null;
Restriction restriction = null;
Map<String, Object> metadata = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (Fields.INDEX.match(currentFieldName, parser.getDeprecationHandler())
|| Fields.INDICES.match(currentFieldName, parser.getDeprecationHandler())) {
indicesPrivileges = parseIndices(name, parser, allow2xFormat);
} else if (Fields.RUN_AS.match(currentFieldName, parser.getDeprecationHandler())) {
runAsUsers = readStringArray(name, parser, true);
} else if (Fields.CLUSTER.match(currentFieldName, parser.getDeprecationHandler())) {
clusterPrivileges = readStringArray(name, parser, true);
} else if (Fields.APPLICATIONS.match(currentFieldName, parser.getDeprecationHandler())
|| Fields.APPLICATION.match(currentFieldName, parser.getDeprecationHandler())) {
applicationPrivileges = parseApplicationPrivileges(name, parser);
} else if (Fields.GLOBAL.match(currentFieldName, parser.getDeprecationHandler())) {
configurableClusterPrivileges = ConfigurableClusterPrivileges.parse(parser);
} else if (Fields.METADATA.match(currentFieldName, parser.getDeprecationHandler())) {
if (token != XContentParser.Token.START_OBJECT) {
throw new ElasticsearchParseException(
"expected field [{}] to be of type object, but found [{}] instead",
currentFieldName,
token
);
}
metadata = parser.map();
} else if (Fields.TRANSIENT_METADATA.match(currentFieldName, parser.getDeprecationHandler())) {
if (token == XContentParser.Token.START_OBJECT) {
// consume object but just drop
parser.map();

public RoleDescriptor parse(String name, XContentParser parser) throws IOException {
// validate name
Validation.Error validationError = Validation.Roles.validateRoleName(name, true);
if (validationError != null) {
ValidationException ve = new ValidationException();
ve.addValidationError(validationError.toString());
throw ve;
}

// advance to the START_OBJECT token if needed
XContentParser.Token token = parser.currentToken() == null ? parser.nextToken() : parser.currentToken();
if (token != XContentParser.Token.START_OBJECT) {
throw new ElasticsearchParseException("failed to parse role [{}]. expected an object but found [{}] instead", name, token);
}
String currentFieldName = null;
IndicesPrivileges[] indicesPrivileges = null;
RemoteIndicesPrivileges[] remoteIndicesPrivileges = null;
String[] clusterPrivileges = null;
List<ConfigurableClusterPrivilege> configurableClusterPrivileges = Collections.emptyList();
ApplicationResourcePrivileges[] applicationPrivileges = null;
String[] runAsUsers = null;
Restriction restriction = null;
Map<String, Object> metadata = null;
String description = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (Fields.INDEX.match(currentFieldName, parser.getDeprecationHandler())
|| Fields.INDICES.match(currentFieldName, parser.getDeprecationHandler())) {
indicesPrivileges = parseIndices(name, parser, allow2xFormat);
} else if (Fields.RUN_AS.match(currentFieldName, parser.getDeprecationHandler())) {
runAsUsers = readStringArray(name, parser, true);
} else if (Fields.CLUSTER.match(currentFieldName, parser.getDeprecationHandler())) {
clusterPrivileges = readStringArray(name, parser, true);
} else if (Fields.APPLICATIONS.match(currentFieldName, parser.getDeprecationHandler())
|| Fields.APPLICATION.match(currentFieldName, parser.getDeprecationHandler())) {
applicationPrivileges = parseApplicationPrivileges(name, parser);
} else if (Fields.GLOBAL.match(currentFieldName, parser.getDeprecationHandler())) {
configurableClusterPrivileges = ConfigurableClusterPrivileges.parse(parser);
} else if (Fields.METADATA.match(currentFieldName, parser.getDeprecationHandler())) {
if (token != XContentParser.Token.START_OBJECT) {
throw new ElasticsearchParseException(
"expected field [{}] to be of type object, but found [{}] instead",
currentFieldName,
token
);
}
metadata = parser.map();
} else if (Fields.TRANSIENT_METADATA.match(currentFieldName, parser.getDeprecationHandler())) {
if (token == XContentParser.Token.START_OBJECT) {
// consume object but just drop
parser.map();
} else {
throw new ElasticsearchParseException(
"failed to parse role [{}]. unexpected field [{}]",
name,
currentFieldName
);
}
} else if (Fields.REMOTE_INDICES.match(currentFieldName, parser.getDeprecationHandler())) {
remoteIndicesPrivileges = parseRemoteIndices(name, parser);
} else if (allowRestriction && Fields.RESTRICTION.match(currentFieldName, parser.getDeprecationHandler())) {
restriction = Restriction.parse(name, parser);
} else if (Fields.TYPE.match(currentFieldName, parser.getDeprecationHandler())) {
// don't need it
} else {
throw new ElasticsearchParseException(
"failed to parse role [{}]. unexpected field [{}]",
name,
currentFieldName
);
}
} else if (Fields.REMOTE_INDICES.match(currentFieldName, parser.getDeprecationHandler())) {
remoteIndicesPrivileges = parseRemoteIndices(name, parser);
} else if (allowRestriction && Fields.RESTRICTION.match(currentFieldName, parser.getDeprecationHandler())) {
restriction = Restriction.parse(name, parser);
} else if (Fields.TYPE.match(currentFieldName, parser.getDeprecationHandler())) {
// don't need it
} else {
throw new ElasticsearchParseException("failed to parse role [{}]. unexpected field [{}]", name, currentFieldName);
}
}
return new RoleDescriptor(
name,
clusterPrivileges,
indicesPrivileges,
applicationPrivileges,
configurableClusterPrivileges.toArray(new ConfigurableClusterPrivilege[configurableClusterPrivileges.size()]),
runAsUsers,
metadata,
null,
remoteIndicesPrivileges,
restriction
);

}
return new RoleDescriptor(
name,
clusterPrivileges,
indicesPrivileges,
applicationPrivileges,
configurableClusterPrivileges.toArray(new ConfigurableClusterPrivilege[configurableClusterPrivileges.size()]),
runAsUsers,
metadata,
null,
remoteIndicesPrivileges,
restriction
);

}

private static String[] readStringArray(String roleName, XContentParser parser, boolean allowNull) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public record RoleDescriptorsIntersection(Collection<Set<RoleDescriptor>> roleDe

public static RoleDescriptorsIntersection EMPTY = new RoleDescriptorsIntersection(Collections.emptyList());

private static final RoleDescriptor.Parser ROLE_DESCRIPTOR_PARSER = RoleDescriptor.parserBuilder().allowRestriction(true).build();

public RoleDescriptorsIntersection(RoleDescriptor roleDescriptor) {
this(List.of(Set.of(roleDescriptor)));
}
Expand Down Expand Up @@ -70,7 +72,7 @@ public static RoleDescriptorsIntersection fromXContent(XContentParser xContentPa
while ((token = p.nextToken()) != XContentParser.Token.END_OBJECT) {
XContentParserUtils.ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, p);
XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, p.nextToken(), p);
roleDescriptors.add(RoleDescriptor.parse(p.currentName(), p, false));
roleDescriptors.add(ROLE_DESCRIPTOR_PARSER.parse(p.currentName(), p));
}
return Set.copyOf(roleDescriptors);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,9 @@ private void assertRoleDescriptorEquals(Map<String, Object> responseFragment, Ro
@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
),
RoleDescriptor.parserBuilder()
.build()
.parse(roleDescriptor.getName(), XContentTestUtils.convertToXContent(descriptorMap, XContentType.JSON), XContentType.JSON),
equalTo(roleDescriptor)
);
}
Expand Down
Loading