repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/UsersAttributeValuesCapableElement.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.List; /** * This interface represent configuration element with predefined list of users and their attribute values. It provides ability to tests * to come up with own user population for the tested scenario. * * @author Josef Cacek */ public interface UsersAttributeValuesCapableElement extends ConfigurableElement { /** * Returns predefined (not {@code null}) list of users and their attributes to be created. */ List<UserWithAttributeValues> getUsersWithAttributeValues(); }
1,595
38.9
136
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/AggregateSecurityRealm.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed 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.wildfly.test.security.common.elytron; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * A {@link ConfigurableElement} to define an Aggregate SecurityRealm resource. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class AggregateSecurityRealm implements SecurityRealm { private final PathAddress address; private final String name; private final String authenticationRealm; private final String authorizationRealm; private final String[] authorizationRealms; private final String principalTransformer; AggregateSecurityRealm(final String name, final String authenticationRealm, final String authorizationRealm, final String[] authorizationRealms, final String principalTransformer) { this.name = name; this.address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "elytron"), PathElement.pathElement("aggregate-realm", name)); this.authenticationRealm = authenticationRealm; this.authorizationRealm = authorizationRealm; this.authorizationRealms = authorizationRealms; this.principalTransformer = principalTransformer; } @Override public String getName() { return name; } public ModelNode getAddOperation() { ModelNode addOperation = Util.createAddOperation(address); addOperation.get("authentication-realm").set(authenticationRealm); if (authorizationRealm != null) { addOperation.get("authorization-realm").set(authorizationRealm); } if (authorizationRealms != null) { ModelNode realms = addOperation.get("authorization-realms"); for (String realmName : authorizationRealms) { realms.add(realmName); } } if (principalTransformer != null) { addOperation.get("principal-transformer").set(principalTransformer); } return addOperation; } public ModelNode getRemoveOperation() { return Util.createRemoveOperation(address); } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getAddOperation(), client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getRemoveOperation(), client); } public static Builder builder(final String name) { return new Builder(name); } public static class Builder { private final String name; private String authenticationRealm; private String authorizationRealm; private String[] authorizationRealms; private String principalTransformer; Builder(final String name) { this.name = name; } public Builder withAuthenticationRealm(final String authenticationRealm) { this.authenticationRealm = authenticationRealm; return this; } public Builder withAuthorizationRealm(final String authorizationRealm) { this.authorizationRealm = authorizationRealm; return this; } public Builder withAuthorizationRealms(final String... authorizationRealms) { this.authorizationRealms = authorizationRealms; return this; } public Builder withPrincipalTransformer(final String principalTransformer) { this.principalTransformer = principalTransformer; return this; } public SecurityRealm build() { return new AggregateSecurityRealm(name, authenticationRealm, authorizationRealm, authorizationRealms, principalTransformer); } } }
4,655
33.488889
185
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/MatchRules.java
/* * Copyright 2017 Red Hat, Inc. * * Licensed 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.wildfly.test.security.common.elytron; /** * Helper class for adding "match-rules" attributes into CLI commands. * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public class MatchRules implements CliFragment { private final String authenticationConfiguration; private final String matchAbstractType; private final String matchAbstractTypeAuthority; private final String matchHost; private final String matchLocalSecurityDomain; private final Boolean matchNoUser; private final String matchPath; private final String matchPort; private final String matchProtocol; private final String matchPurpose; private final String matchUrn; private final String matchUser; private final String sslContext; private MatchRules(final Builder builder) { this.authenticationConfiguration = builder.authenticationConfiguration; this.matchAbstractType = builder.matchAbstractType; this.matchAbstractTypeAuthority = builder.matchAbstractTypeAuthority; this.matchHost = builder.matchHost; this.matchLocalSecurityDomain = builder.matchLocalSecurityDomain; this.matchNoUser = builder.matchNoUser; this.matchPath = builder.matchPath; this.matchPort = builder.matchPort; this.matchProtocol = builder.matchProtocol; this.matchPurpose = builder.matchPurpose; this.matchUrn = builder.matchUrn; this.matchUser = builder.matchUser; this.sslContext = builder.sslContext; } @Override public String asString() { StringBuilder sb = new StringBuilder("match-rules=[{"); if (authenticationConfiguration != null && !authenticationConfiguration.isEmpty()) { sb.append(String.format("authentication-configuration=\"%s\", ", authenticationConfiguration)); } if (matchAbstractType != null && !matchAbstractType.isEmpty()) { sb.append(String.format("match-abstract-type=\"%s\", ", matchAbstractType)); } if (matchAbstractTypeAuthority != null && !matchAbstractTypeAuthority.isEmpty()) { sb.append(String.format("match-abstract-type-authority=\"%s\", ", matchAbstractTypeAuthority)); } if (matchHost != null && !matchHost.isEmpty()) { sb.append(String.format("match-host=\"%s\", ", matchHost)); } if (matchLocalSecurityDomain != null && !matchLocalSecurityDomain.isEmpty()) { sb.append(String.format("match-local-security-domain=\"%s\", ", matchLocalSecurityDomain)); } if (matchNoUser != null) { sb.append(String.format("match-no-user=\"%s\", ", matchNoUser.toString())); } if (matchPath != null && !matchPath.isEmpty()) { sb.append(String.format("match-path=\"%s\", ", matchPath)); } if (matchPort != null && !matchPort.isEmpty()) { sb.append(String.format("match-port=\"%s\", ", matchPort)); } if (matchProtocol != null && !matchProtocol.isEmpty()) { sb.append(String.format("match-protocol=\"%s\", ", matchProtocol)); } if (matchPurpose != null && !matchPurpose.isEmpty()) { sb.append(String.format("match-purpose=\"%s\", ", matchPurpose)); } if (matchUrn != null && !matchUrn.isEmpty()) { sb.append(String.format("match-urn=\"%s\", ", matchUrn)); } if (matchUser != null && !matchUser.isEmpty()) { sb.append(String.format("match-user=\"%s\", ", matchUser)); } if (sslContext != null && !sslContext.isEmpty()) { sb.append(String.format("ssl-context=\"%s\", ", sslContext)); } sb.append("}], "); return sb.toString(); } public static Builder builder() { return new Builder(); } public static final class Builder { private String authenticationConfiguration; private String matchAbstractTypeAuthority; private String matchAbstractType; private String matchHost; private String matchLocalSecurityDomain; private Boolean matchNoUser; private String matchPath; private String matchPort; private String matchProtocol; private String matchPurpose; private String matchUrn; private String matchUser; private String sslContext; private Builder() { } public Builder withAuthenticationConfiguration(final String authenticationConfiguration) { this.authenticationConfiguration = authenticationConfiguration; return this; } public Builder withMatchAbstractType(final String matchAbstractType) { this.matchAbstractType = matchAbstractType; return this; } public Builder withMatchAbstractTypeAuthority(final String matchAbstractTypeAuthority) { this.matchAbstractTypeAuthority = matchAbstractTypeAuthority; return this; } public Builder withMatchHost(final String matchHost) { this.matchHost = matchHost; return this; } public Builder withMatchLocalSecurityDomain(final String matchLocalSecurityDomain) { this.matchLocalSecurityDomain = matchLocalSecurityDomain; return this; } public Builder withMatchNoUser(final Boolean matchNoUser) { this.matchNoUser = matchNoUser; return this; } public Builder withMatchPath(final String matchPath) { this.matchPath = matchPath; return this; } public Builder withMatchPort(final String matchPort) { this.matchPort = matchPort; return this; } public Builder withMatchProtocol(final String matchProtocol) { this.matchProtocol = matchProtocol; return this; } public Builder withMatchPurpose(final String matchPurpose) { this.matchPurpose = matchPurpose; return this; } public Builder withMatchUrn(final String matchUrn) { this.matchUrn = matchUrn; return this; } public Builder withMatchUser(final String matchUser) { this.matchUser = matchUser; return this; } public Builder withSslContext(final String sslContext) { this.sslContext = sslContext; return this; } public MatchRules build() { return new MatchRules(this); } } }
7,220
36.030769
107
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/PermissionRef.java
package org.wildfly.test.security.common.elytron; import java.security.Permission; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; public final class PermissionRef { private final String className; private final String module; private final String targetName; private final String action; public PermissionRef(Builder builder) { this.className = builder.className; this.module = builder.module; this.targetName = builder.targetName; this.action = builder.action; } public String getClassName() { return className; } public String getModule() { return module; } public String getTargetName() { return targetName; } public String getAction() { return action; } public static Builder builder() { return new Builder(); } public static PermissionRef fromPermission(Permission perm) { return fromPermission(perm, null); } public static PermissionRef fromPermission(Permission perm, String module) { return builder().className(perm.getClass().getName()).action(perm.getActions()).targetName(perm.getName()) .module(module).build(); } public String toCLIString() { StringBuilder result = new StringBuilder(); result.append("{"); List<String> arguments = new ArrayList<>(); if (action != null) { arguments.add("action=" + action); } if (module != null) { arguments.add("module=" + module); } if (targetName != null) { arguments.add("target-name=" + targetName); } if (className != null) { arguments.add("class-name=" + className); } result.append(StringUtils.join(arguments, ",")); result.append("}"); return result.toString(); } public static class Builder { private String className; private String module; private String targetName; private String action; public Builder() { } public Builder className(String className) { this.className = className; return this; } public Builder module(String module) { this.module = module; return this; } public Builder targetName(String targetName) { this.targetName = "".equals(targetName) ? null : targetName; return this; } public Builder action(String action) { this.action = "".equals(action) ? null : action; return this; } public PermissionRef build() { return new PermissionRef(this); } } }
2,794
25.121495
114
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/CredentialStore.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Interface representing Elytron credential store. * * @author Josef Cacek */ public interface CredentialStore extends ConfigurableElement { }
1,227
36.212121
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleKeyStore.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Elytron key-store configuration implementation. * * @author Josef Cacek */ public class SimpleKeyStore extends AbstractConfigurableElement implements KeyStore { private final Path path; private final CredentialReference credentialReference; private final String type; private final boolean required; private SimpleKeyStore(Builder builder) { super(builder); this.path = defaultIfNull(builder.path, Path.EMPTY); this.credentialReference = defaultIfNull(builder.credentialReference, CredentialReference.EMPTY); this.type = defaultIfNull(builder.type, "JKS"); this.required = builder.required; } @Override public void create(CLIWrapper cli) throws Exception { // /subsystem=elytron/key-store=httpsKS:add(path=keystore.jks,relative-to=jboss.server.config.dir, // credential-reference={clear-text=secret},type=JKS,required=false) cli.sendLine(String.format("/subsystem=elytron/key-store=%s:add(%s%stype=\"%s\",required=%s)", name, path.asString(), credentialReference.asString(), type, Boolean.toString(required))); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/key-store=%s:remove()", name)); } /** * Creates builder to build {@link SimpleKeyStore}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleKeyStore}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private Path path; private CredentialReference credentialReference; private String type; private boolean required; private Builder() { } public Builder withPath(Path path) { this.path = path; return this; } public Builder withCredentialReference(CredentialReference credentialReference) { this.credentialReference = credentialReference; return this; } public Builder withType(String type) { this.type = type; return this; } public Builder withRequired(boolean required) { this.required = required; return this; } public SimpleKeyStore build() { return new SimpleKeyStore(this); } @Override protected Builder self() { return this; } } }
3,777
32.732143
125
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ElytronDomainSetup.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.wildfly.test.security.common.elytron.Utils.applyRemoveAllowReload; import static org.wildfly.test.security.common.elytron.Utils.applyUpdate; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.dmr.ModelNode; /** * Utility methods to create/remove simple security domains * * @author <a href="mailto:jkalina@redhat.com">Jan Kalina</a> */ public class ElytronDomainSetup implements ServerSetupTask { private static final String SUBSYSTEM_NAME = "elytron"; private static final String DEFAULT_SECURITY_DOMAIN_NAME = "elytron-tests"; private static final String DEFAULT_PERMISSION_MAPPER_NAME = "default-permission-mapper"; private PathAddress realmAddress; private PathAddress domainAddress; private PathAddress permissionMapperAddress; private PathAddress roleDecoder1Address; private PathAddress roleDecoder2Address; private PathAddress aggregateRoleDecoderAddress; private final String usersFile; private final String groupsFile; private final String securityDomainName; private final String permissionMapperName; private final String ipAddress; public ElytronDomainSetup(final String usersFile, final String groupsFile) { this(usersFile, groupsFile, DEFAULT_SECURITY_DOMAIN_NAME, DEFAULT_PERMISSION_MAPPER_NAME, null); } public ElytronDomainSetup(final String usersFile, final String groupsFile, String securityDomainName) { this(usersFile, groupsFile, securityDomainName, DEFAULT_PERMISSION_MAPPER_NAME, null); } public ElytronDomainSetup(final String usersFile, final String groupsFile, final String securityDomainName, final String permissionMapperName, final String ipAddress) { this.usersFile = usersFile; this.groupsFile = groupsFile; this.securityDomainName = securityDomainName; this.permissionMapperName = permissionMapperName; this.ipAddress = ipAddress; } protected String getSecurityDomainName() { return securityDomainName; } protected String getSecurityRealmName() { return getSecurityDomainName() + "-ejb3-UsersRoles"; } protected String getUndertowDomainName() { return getSecurityDomainName(); } protected String getEjbDomainName() { return getSecurityDomainName(); } protected String getSaslAuthenticationName() { return getSecurityDomainName(); } protected String getRemotingConnectorName() { return "http-remoting-connector"; } protected String getHttpAuthenticationName() { return getSecurityDomainName(); } protected String getUsersFile() { return usersFile; } protected String getGroupsFile() { return groupsFile; } protected String getPermissionMapperName() { return permissionMapperName; } protected boolean isUsersFilePlain() { return true; } @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { realmAddress = PathAddress.pathAddress() .append(SUBSYSTEM, SUBSYSTEM_NAME) .append("properties-realm", getSecurityRealmName()); domainAddress = PathAddress.pathAddress() .append(SUBSYSTEM, SUBSYSTEM_NAME) .append("security-domain", getSecurityDomainName()); final ModelNode compositeOp = new ModelNode(); compositeOp.get(OP).set(ModelDescriptionConstants.COMPOSITE); compositeOp.get(OP_ADDR).setEmptyList(); ModelNode steps = compositeOp.get(STEPS); // /subsystem=elytron/properties-realm=UsersRoles:add(users-properties={path=users.properties},groups-properties={path=roles.properties}) ModelNode addRealm = Util.createAddOperation(realmAddress); addRealm.get("users-properties").get("path").set(getUsersFile()); addRealm.get("users-properties").get("plain-text").set(isUsersFilePlain()); // not hashed addRealm.get("groups-properties").get("path").set(getGroupsFile()); steps.add(addRealm); if (! permissionMapperName.equals(DEFAULT_PERMISSION_MAPPER_NAME)) { permissionMapperAddress = PathAddress.pathAddress() .append(SUBSYSTEM, SUBSYSTEM_NAME) .append("simple-permission-mapper", permissionMapperName); // /subsystem=elytron/simple-permission-mapper=ipPermissionMapper:add(permission-mappings=[{roles=[admin], // permission-sets=[{permission-set=login-permission}]}, {principals=[user2],permission-sets=[]}], mapping-mode="and") // (ensure that user1 is assigned the admin role if the IP address of the remote client matches the configured // address and ensure user2 is not assigned the admin role even if the IP address of the remote client matches) ModelNode addPermissionMapper = Util.createAddOperation(permissionMapperAddress); ModelNode permissionMapping1 = new ModelNode(); permissionMapping1.get("roles").add("Admin"); ModelNode permissionSet = new ModelNode(); permissionSet.get("permission-set").set("login-permission"); permissionMapping1.get("permission-sets").add(permissionSet); addPermissionMapper.get("permission-mappings").add(permissionMapping1); ModelNode permissionMapping2 = new ModelNode(); permissionMapping2.get("principals").add("user2"); addPermissionMapper.get("permission-mappings").add(permissionMapping2); addPermissionMapper.get("mapping-mode").set("and"); steps.add(addPermissionMapper); // /subsystem=elytron/source-address-role-decoder=decoder1:add(source-address=IP_ADDRESS, roles=["Admin"]) roleDecoder1Address = PathAddress.pathAddress() .append(SUBSYSTEM, SUBSYSTEM_NAME) .append("source-address-role-decoder", "decoder1"); ModelNode addRoleDecoder1 = Util.createAddOperation(roleDecoder1Address); addRoleDecoder1.get("source-address").set(ipAddress); addRoleDecoder1.get("roles").add("Admin"); steps.add(addRoleDecoder1); // /subsystem=elytron/source-address-role-decoder=decoder2:add(source-address="99.99.99.99", roles=["Employee"]) roleDecoder2Address = PathAddress.pathAddress() .append(SUBSYSTEM, SUBSYSTEM_NAME) .append("source-address-role-decoder", "decoder2"); ModelNode addRoleDecoder2 = Util.createAddOperation(roleDecoder2Address); addRoleDecoder2.get("source-address").set("99.99.99.99"); addRoleDecoder2.get("roles").add("Employee"); steps.add(addRoleDecoder2); // /subsystem=elytron/aggregate-role-decoder=aggregateDecoder:add(role-decoders=[decoder1, decoder2]) aggregateRoleDecoderAddress = PathAddress.pathAddress() .append(SUBSYSTEM, SUBSYSTEM_NAME) .append("aggregate-role-decoder", "aggregateRoleDecoder"); ModelNode addAggregateRoleDecoder = Util.createAddOperation(aggregateRoleDecoderAddress); addAggregateRoleDecoder.get("role-decoders").add("decoder1"); addAggregateRoleDecoder.get("role-decoders").add("decoder2"); steps.add(addAggregateRoleDecoder); } // /subsystem=elytron/security-domain=EjbDomain:add(default-realm=UsersRoles, realms=[{realm=UsersRoles}]) ModelNode addDomain = Util.createAddOperation(domainAddress); addDomain.get("permission-mapper").set(permissionMapperName); if (! permissionMapperName.equals(DEFAULT_PERMISSION_MAPPER_NAME)) { addDomain.get("role-decoder").set("aggregateRoleDecoder"); } addDomain.get("default-realm").set(getSecurityRealmName()); addDomain.get("realms").get(0).get("realm").set(getSecurityRealmName()); addDomain.get("realms").get(0).get("role-decoder").set("groups-to-roles"); // use attribute "groups" as roles (defined in standalone-elytron.xml) addDomain.get("realms").get(1).get("realm").set("local"); steps.add(addDomain); applyUpdate(managementClient.getControllerClient(), compositeOp, false); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) { applyRemoveAllowReload(managementClient.getControllerClient(), domainAddress, false); applyRemoveAllowReload(managementClient.getControllerClient(), realmAddress, false); if (! permissionMapperName.equals(DEFAULT_PERMISSION_MAPPER_NAME)) { applyRemoveAllowReload(managementClient.getControllerClient(), permissionMapperAddress, false); applyRemoveAllowReload(managementClient.getControllerClient(), aggregateRoleDecoderAddress, false); applyRemoveAllowReload(managementClient.getControllerClient(), roleDecoder1Address, false); applyRemoveAllowReload(managementClient.getControllerClient(), roleDecoder2Address, false); } } }
10,819
47.303571
172
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleConfigurableSaslServerFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * Elytron configurable-sasl-server-factory configuration. * * @author Josef Cacek */ public class SimpleConfigurableSaslServerFactory extends AbstractConfigurableElement implements SaslServerFactory { private final List<SaslFilter> filters; private final Map<String, String> properties; private final String protocol; private final String saslServerFactory; private final String serverName; private SimpleConfigurableSaslServerFactory(Builder builder) { super(builder); this.filters = builder.filters; this.properties = builder.properties; this.protocol = builder.protocol; this.saslServerFactory = Objects.requireNonNull(builder.saslServerFactory, "saslServerFactory must not be null"); this.serverName = builder.serverName; } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode op = Util.createAddOperation( PathAddress.pathAddress().append("subsystem", "elytron").append("configurable-sasl-server-factory", name)); if (!filters.isEmpty()) { ModelNode filtersNode = op.get("filters"); for (SaslFilter saslFilter : filters) { ModelNode saslFilterNode = new ModelNode(); setIfNotNull(saslFilterNode, "predefined-filter", saslFilter.getPredefinedFilter()); setIfNotNull(saslFilterNode, "pattern-filter", saslFilter.getPatternFilter()); setIfNotNull(saslFilterNode, "enabling", saslFilter.isEnabling()); filtersNode.add(saslFilterNode); } } if (!properties.isEmpty()) { ModelNode propertiesNode = op.get("properties"); for (Map.Entry<String, String> entry : properties.entrySet()) { propertiesNode.get(entry.getKey()).set(entry.getValue()); } } setIfNotNull(op, "protocol", protocol); op.get("sasl-server-factory").set(saslServerFactory); setIfNotNull(op, "server-name", serverName); Utils.applyUpdate(op, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(Util.createRemoveOperation( PathAddress.pathAddress().append("subsystem", "elytron").append("configurable-sasl-server-factory", name)), client); } /** * Creates builder to build {@link SimpleConfigurableSaslServerFactory}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleConfigurableSaslServerFactory}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private List<SaslFilter> filters = new ArrayList<SaslFilter>(); private Map<String, String> properties = new HashMap<>(); private String protocol; private String saslServerFactory; private String serverName; private Builder() { } public Builder addFilter(SaslFilter filter) { this.filters.add(filter); return this; } public Builder addProperty(String name, String value) { this.properties.put(name, value); return this; } public Builder withProtocol(String protocol) { this.protocol = protocol; return this; } public Builder withSaslServerFactory(String saslServerFactory) { this.saslServerFactory = saslServerFactory; return this; } public Builder withServerName(String serverName) { this.serverName = serverName; return this; } public SimpleConfigurableSaslServerFactory build() { return new SimpleConfigurableSaslServerFactory(this); } @Override protected Builder self() { return this; } } }
5,641
36.118421
123
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ConfigurableElement.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Interface representing a configurable object in domain model. The implementation has to override at least one of the * {@code create(...)} methods and one of the {@code remove(...)} methods. * * @author Josef Cacek */ public interface ConfigurableElement { /** * Returns name of this element. */ String getName(); /** * Creates this element in domain model and also creates other resources if needed (e.g. external files) * * @param cli connected {@link CLIWrapper} instance */ default void create(CLIWrapper cli) throws Exception { throw new IllegalStateException("The create() method was not properly implemented"); } /** * Creates this element in domain model and it also may create other resources if needed (e.g. external files). * Implementation can choose if controller client is used or provided CLI wrapper. */ default void create(ModelControllerClient client, CLIWrapper cli) throws Exception { create(cli); } /** * Reverts the changes introdued by {@code create(...)} method(s). */ default void remove(CLIWrapper cli) throws Exception { throw new IllegalStateException("The remove() method was not properly implemented"); } /** * Reverts the changes introdued by {@code create(...)} method(s). */ default void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { remove(cli); } }
2,681
36.25
119
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleHttpAuthenticationFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * Elytron http-authentication-factory configuration. * * @author Jan Kalina */ public class SimpleHttpAuthenticationFactory extends AbstractConfigurableElement implements HttpAuthenticationFactory { private final List<MechanismConfiguration> mechanismConfigurations; private final String httpServerMechanismFactory; private final String securityDomain; private SimpleHttpAuthenticationFactory(Builder builder) { super(builder); this.mechanismConfigurations = new ArrayList<>(builder.mechanismConfigurations); this.httpServerMechanismFactory = Objects.requireNonNull(builder.httpServerMechanismFactory,"httpServerMechanismFactory must be not-null"); this.securityDomain = Objects.requireNonNull(builder.securityDomain,"securityDomain must be not-null"); } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode op = Util.createAddOperation( PathAddress.pathAddress().append("subsystem", "elytron").append("http-authentication-factory", name)); setIfNotNull(op, "http-server-mechanism-factory", httpServerMechanismFactory); setIfNotNull(op, "security-domain", securityDomain); if (!mechanismConfigurations.isEmpty()) { ModelNode confs = op.get("mechanism-configurations"); for (MechanismConfiguration conf : mechanismConfigurations) { confs.add(conf.toModelNode()); } } Utils.applyUpdate(op, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(Util.createRemoveOperation( PathAddress.pathAddress().append("subsystem", "elytron").append("http-authentication-factory", name)), client); } /** * Creates builder to build {@link SimpleHttpAuthenticationFactory}. * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleHttpAuthenticationFactory}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private List<MechanismConfiguration> mechanismConfigurations = new ArrayList<>(); private String httpServerMechanismFactory; private String securityDomain; private Builder() { } public Builder addMechanismConfiguration(MechanismConfiguration mechanismConfiguration) { this.mechanismConfigurations.add(mechanismConfiguration); return this; } public Builder withHttpServerMechanismFactory(String httpServerFactory) { this.httpServerMechanismFactory = httpServerFactory; return this; } public Builder withSecurityDomain(String securityDomain) { this.securityDomain = securityDomain; return this; } public SimpleHttpAuthenticationFactory build() { return new SimpleHttpAuthenticationFactory(this); } @Override protected Builder self() { return this; } } }
4,754
37.04
147
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/AbstractConfigurableElement.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.Objects; /** * Abstract parent for {@link ConfigurableElement} implementations. It just holds common fields and provides parent for * builders. * * @author Josef Cacek */ public abstract class AbstractConfigurableElement implements ConfigurableElement { protected final String name; protected AbstractConfigurableElement(Builder<?> builder) { this.name = Objects.requireNonNull(builder.name, "Configuration name must not be null"); } @Override public final String getName() { return name; } /** * Builder to build {@link AbstractConfigurableElement}. */ public abstract static class Builder<T extends Builder<T>> { private String name; protected Builder() { } protected abstract T self(); public final T withName(String name) { this.name = name; return self(); } } }
2,008
29.907692
119
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/PropertyFileBasedDomain.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.jboss.as.test.integration.security.common.Utils.createTemporaryFolder; import static org.jboss.as.test.shared.CliUtils.asAbsolutePath; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.logging.Logger; import org.wildfly.security.auth.permission.LoginPermission; /** * Elytron Security domain implementation which uses {@code properties-realm} to hold the users. * <p> * For this given domain are created also following Elytron resources (with the same name as the domain): * </p> * <ul> * <li>properties-realm</li> * <li>simple-role-decoder</li> * <li>constant-permission-mapper</li> * </ul> * * @author Josef Cacek */ public class PropertyFileBasedDomain extends AbstractUserAttributeValuesCapableElement implements SecurityDomain { private static final Logger LOGGER = Logger.getLogger(PropertyFileBasedDomain.class); private File tempFolder; protected final String permissionMapper; private PropertyFileBasedDomain(Builder builder) { super(builder); this.permissionMapper = builder.permMapper; } @Override public void create(CLIWrapper cli) throws Exception { tempFolder = createTemporaryFolder("ely-" + getName()); final Properties usersProperties = new Properties(); final Properties rolesProperties = new Properties(); for (UserWithAttributeValues user : getUsersWithAttributeValues()) { usersProperties.setProperty(user.getName(), user.getPassword()); rolesProperties.setProperty(user.getName(), String.join(",", user.getValues())); } File usersFile = writeProperties(usersProperties, "users.properties"); File rolesFile = writeProperties(rolesProperties, "roles.properties"); // /subsystem=elytron/properties-realm=test:add(users-properties={path=/tmp/users.properties, plain-text=true}, // groups-properties={path=/tmp/groups.properties}) cli.sendLine(String.format( "/subsystem=elytron/properties-realm=%s:add(users-properties={path=\"%s\", plain-text=true}, groups-properties={path=\"%s\"})", name, asAbsolutePath(usersFile), asAbsolutePath(rolesFile))); // /subsystem=elytron/simple-role-decoder=test:add(attribute=groups) cli.sendLine(String.format("/subsystem=elytron/simple-role-decoder=%s:add(attribute=groups)", name)); if(permissionMapper == null) { // create a default permission mapper if a custom one wasn't specified // /subsystem=elytron/constant-permission-mapper=test:add(permissions=[{class-name="org.wildfly.security.auth.permission.LoginPermission"}]) cli.sendLine(String.format("/subsystem=elytron/constant-permission-mapper=%s:add(permissions=[{class-name=\"%s\"}])", name, LoginPermission.class.getName())); } final String permissionMapperName = permissionMapper == null ? name : permissionMapper; // /subsystem=elytron/security-domain=test:add(default-realm=test, permission-mapper=PERMISSION_MAPPER, realms=[{role-decoder=test, // realm=test}] cli.sendLine(String.format( "/subsystem=elytron/security-domain=%s:add(default-realm=%1$s, permission-mapper=%2$s, realms=[{role-decoder=%1$s, realm=%1$s}]", name, permissionMapperName)); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:remove()", name)); if(permissionMapper == null) { cli.sendLine(String.format("/subsystem=elytron/constant-permission-mapper=%s:remove()", name)); } cli.sendLine(String.format("/subsystem=elytron/simple-role-decoder=%s:remove()", name)); cli.sendLine(String.format("/subsystem=elytron/properties-realm=%s:remove()", name)); FileUtils.deleteQuietly(tempFolder); } /** * Creates builder to build {@link PropertyFileBasedDomain}. * * @return created builder */ public static Builder builder() { return new Builder(); } public static final class Builder extends AbstractUserAttributeValuesCapableElement.Builder<Builder> { private String permMapper; private Builder() { // empty } public PropertyFileBasedDomain build() { return new PropertyFileBasedDomain(this); } public Builder permissionMapper(String name) { permMapper = name; return self(); } @Override protected Builder self() { return this; } } private File writeProperties(Properties properties, String fileName) throws IOException { File result = new File(tempFolder, fileName); LOGGER.debugv("Creating property file {0}", result); try (FileOutputStream fos = new FileOutputStream(result)) { // comment $REALM_NAME is just a workaround for https://issues.jboss.org/browse/WFLY-7104 properties.store(fos, "$REALM_NAME=" + name + "$"); } return result; } }
6,376
40.141935
152
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/RoleMapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Marking interface for configuration classes for Elytron elements providing role-mapper capability. * * @author Josef Cacek */ public interface RoleMapper extends ConfigurableElement { }
1,272
37.575758
101
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/DirContext.java
/* * Copyright 2020 Red Hat, Inc. * * Licensed 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.wildfly.test.security.common.elytron; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * A {@link ConfigurableElement} to define the dir-context resource within the Elytron subsystem. * * @author Ondrej Kotek */ public class DirContext implements ConfigurableElement { private final PathAddress address; private final String name; private final String url; private final AuthenticationLevel authenticationLevel; private final String principal; private final Boolean enableConnectionPooling; private final String sslContext; private final ReferralMode referralMode; private final String authenticationContext; private final Integer connectionTimeout; private final Integer readTimeout; private final String module; private final List<Property> properties; private final CredentialReference credentialReference; DirContext(Builder builder) { this.name = builder.name; this.address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "elytron"), PathElement.pathElement("dir-context", name)); this.url = builder.url; this.authenticationLevel = builder.authenticationLevel; this.principal = builder.principal; this.enableConnectionPooling = builder.enableConnectionPooling; this.sslContext = builder.sslContext; this.referralMode = builder.referralMode; this.authenticationContext = builder.authenticationContext; this.connectionTimeout = builder.connectionTimeout; this.readTimeout = builder.readTimeout; this.module = builder.module; this.properties = builder.properties; this.credentialReference = builder.credentialReference; } @Override public String getName() { return name; } public ModelNode getAddOperation() { ModelNode addOperation = Util.createAddOperation(address); addOperation.get("dir-context"); if (url != null) { addOperation.get("url").set(url); } if (authenticationLevel != null) { addOperation.get("authentication-level").set(authenticationLevel == null ? null : authenticationLevel.name()); } if (principal != null) { addOperation.get("principal").set(principal); } if (enableConnectionPooling != null) { addOperation.get("enable-connection-pooling").set(enableConnectionPooling); } if (sslContext != null) { addOperation.get("ssl-context").set(sslContext); } if (referralMode != null) { addOperation.get("referral-mode").set(referralMode == null ? null : referralMode.name()); } if (authenticationContext != null) { addOperation.get("authentication-context").set(authenticationContext); } if (connectionTimeout != null) { addOperation.get("connection-timeout").set(connectionTimeout); } if (readTimeout != null) { addOperation.get("read-timeout").set(readTimeout); } if (module != null) { addOperation.get("module").set(module); } if (properties != null && !properties.isEmpty()) { ModelNode propertiesNode = new ModelNode(); for (Property property : properties) { propertiesNode.add(property.getKey(), property.getValue()); } addOperation.get("properties").set(propertiesNode.asObject()); } if (credentialReference != null) { addOperation.get("credential-reference").set(credentialReference.asModelNode()); } return addOperation; } public ModelNode getRemoveOperation() { return Util.createRemoveOperation(address); } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getAddOperation(), client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getRemoveOperation(), client); } public static Builder builder(final String name) { return new Builder(name); } public static final class Builder { private final String name; private String url; private AuthenticationLevel authenticationLevel; private String principal; private Boolean enableConnectionPooling; private String sslContext; private ReferralMode referralMode; private String authenticationContext; private Integer connectionTimeout; private Integer readTimeout; private String module; private List<Property> properties = new ArrayList<Property>(); private CredentialReference credentialReference; public Builder(String name) { this.name = name; } public Builder withUrl(String url) { this.url = url; return this; } public Builder withAuthenticationLevel(AuthenticationLevel authenticationLevel) { this.authenticationLevel = authenticationLevel; return this; } public Builder withPrincipal(String principal) { this.principal = principal; return this; } public Builder withEnableConnectionPooling(boolean enableConnectionPooling) { this.enableConnectionPooling = enableConnectionPooling; return this; } public Builder withSslContext(String sslContext) { this.sslContext = sslContext; return this; } public Builder withReferralMode(ReferralMode referralMode) { this.referralMode = referralMode; return this; } public Builder withAuthenticationContext(String authenticationContext) { this.authenticationContext = authenticationContext; return this; } public Builder withConnectionTimeout(Integer connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } public Builder withReadTimeout(Integer readTimeout) { this.readTimeout = readTimeout; return this; } public Builder withModule(String module) { this.module = module; return this; } public Builder withProperties(Property... properties) { Collections.addAll(this.properties, properties); return this; } public Builder withCredentialReference(CredentialReference credentialReference) { this.credentialReference = credentialReference; return this; } public DirContext build() { return new DirContext(this); } } public static class Property { private final String key; private final String value; public Property(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public String getValue() { return value; } } public static enum AuthenticationLevel { NONE, SIMPLE, STRONG } public static enum ReferralMode { FOLLOW, IGNORE, THROW } }
8,412
30.62782
142
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleSecurityDomain.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * Elytron Security domain configuration. * * @author Josef Cacek */ public class SimpleSecurityDomain extends AbstractConfigurableElement implements SecurityDomain { private final String defaultRealm; private final Boolean outflowAnonymous; private final String[] outflowSecurityDomains; private final String permissionMapper; private final String preRealmPrincipalTransformer; private final String postRealmPrincipalTransformer; private final String principalDecoder; private final String realmMapper; private final SecurityDomainRealm[] realms; private final String roleMapper; private final String securityEventListener; private final String[] trustedSecurityDomains; private SimpleSecurityDomain(Builder builder) { super(builder); this.defaultRealm = builder.defaultRealm; this.outflowAnonymous = builder.outflowAnonymous; this.outflowSecurityDomains = builder.outflowSecurityDomains; this.permissionMapper = builder.permissionMapper; this.preRealmPrincipalTransformer = builder.preRealmPrincipalTransformer; this.postRealmPrincipalTransformer = builder.postRealmPrincipalTransformer; this.principalDecoder = builder.principalDecoder; this.realmMapper = builder.realmMapper; this.realms = builder.realms; this.roleMapper = builder.roleMapper; this.securityEventListener = builder.securityEventListener; this.trustedSecurityDomains = builder.trustedSecurityDomains; } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode op = Util .createAddOperation(PathAddress.pathAddress().append("subsystem", "elytron").append("security-domain", name)); if (defaultRealm != null) { op.get("default-realm").set(defaultRealm); } if (outflowAnonymous != null) { op.get("outflow-anonymous").set(outflowAnonymous); } setIfNotNull(op, "outflow-security-domains", outflowSecurityDomains); setIfNotNull(op, "permission-mapper", permissionMapper); setIfNotNull(op, "post-realm-principal-transformer", postRealmPrincipalTransformer); setIfNotNull(op, "pre-realm-principal-transformer", preRealmPrincipalTransformer); setIfNotNull(op, "principal-decoder", principalDecoder); setIfNotNull(op, "realm-mapper", realmMapper); if (realms != null) { ModelNode realmsNode = op.get("realms"); for (SecurityDomainRealm realmRef : realms) { ModelNode realmRefNode = new ModelNode(); realmRefNode.get("realm").set(realmRef.realm); setIfNotNull(realmRefNode, "principal-transformer", realmRef.principalTransformer); setIfNotNull(realmRefNode, "role-decoder", realmRef.roleDecoder); setIfNotNull(realmRefNode, "role-mapper", realmRef.roleMapper); realmsNode.add(realmRefNode); } } setIfNotNull(op, "role-mapper", roleMapper); setIfNotNull(op, "security-event-listener", securityEventListener); setIfNotNull(op, "trusted-security-domains", trustedSecurityDomains); Utils.applyUpdate(op, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(Util.createRemoveOperation( PathAddress.pathAddress().append("subsystem", "elytron").append("security-domain", name)), client); } /** * Creates builder to build {@link SimpleSecurityDomain}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleSecurityDomain}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String defaultRealm; private Boolean outflowAnonymous; private String[] outflowSecurityDomains; private String permissionMapper; private String preRealmPrincipalTransformer; private String postRealmPrincipalTransformer; private String principalDecoder; private String realmMapper; private SecurityDomainRealm[] realms; private String roleMapper; private String securityEventListener; private String[] trustedSecurityDomains; private Builder() { } public Builder withDefaultRealm(String defaultRealm) { this.defaultRealm = defaultRealm; return this; } public Builder withOutflowAnonymous(Boolean outflowAnonymous) { this.outflowAnonymous = outflowAnonymous; return this; } public Builder withOutflowSecurityDomains(String... outflowSecurityDomains) { this.outflowSecurityDomains = outflowSecurityDomains; return this; } public Builder withPermissionMapper(String permissionMapper) { this.permissionMapper = permissionMapper; return this; } public Builder withPreRealmPrincipalTransformer(String preRealmPrincipalTransformer) { this.preRealmPrincipalTransformer = preRealmPrincipalTransformer; return this; } public Builder withPostRealmPrincipalTransformer(String postRealmPrincipalTransformer) { this.postRealmPrincipalTransformer = postRealmPrincipalTransformer; return this; } public Builder withPrincipalDecoder(String principalDecoder) { this.principalDecoder = principalDecoder; return this; } public Builder withRealmMapper(String realmMapper) { this.realmMapper = realmMapper; return this; } public Builder withRealms(SecurityDomainRealm... realms) { this.realms = realms; return this; } public Builder withRoleMapper(String roleMapper) { this.roleMapper = roleMapper; return this; } public Builder withSecurityEventListener(String securityEventListener) { this.securityEventListener = securityEventListener; return this; } public Builder withTrustedSecurityDomains(String[] trustedSecurityDomains) { this.trustedSecurityDomains = trustedSecurityDomains; return this; } public SimpleSecurityDomain build() { return new SimpleSecurityDomain(this); } @Override protected Builder self() { return this; } } public static class SecurityDomainRealm { private final String realm; private final String principalTransformer; private final String roleDecoder; private final String roleMapper; private SecurityDomainRealm(Builder builder) { this.realm = builder.realm; this.principalTransformer = builder.principalTransformer; this.roleDecoder = builder.roleDecoder; this.roleMapper = builder.roleMapper; } /** * Creates builder to build {@link SecurityDomainRealm}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SecurityDomainRealm}. */ public static final class Builder { private String realm; private String principalTransformer; private String roleDecoder; private String roleMapper; private Builder() { } public Builder withRealm(String realm) { this.realm = realm; return this; } public Builder withPrincipalTransformer(String principalTransformer) { this.principalTransformer = principalTransformer; return this; } public Builder withRoleDecoder(String roleDecoder) { this.roleDecoder = roleDecoder; return this; } public Builder withRoleMapper(String roleMapper) { this.roleMapper = roleMapper; return this; } public SecurityDomainRealm build() { return new SecurityDomainRealm(this); } } } }
10,026
36.414179
126
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SyslogAuditLog.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.apache.commons.lang3.StringUtils.isNotBlank; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * * @author Jan Tymel */ public class SyslogAuditLog extends AbstractConfigurableElement { private final String format; private final String hostName; private final Integer port; private final String serverAddress; private final String sslContext; private final String transport; private final Integer maxReconnectAttempts; private SyslogAuditLog(Builder builder) { super(builder); this.format = builder.format; this.hostName = builder.hostName; this.port = builder.port; this.serverAddress = builder.serverAddress; this.sslContext = builder.sslContext; this.transport = builder.transport; this.maxReconnectAttempts = builder.maxReconnectAttempts; } @Override public void create(CLIWrapper cli) throws Exception { StringBuilder command = new StringBuilder("/subsystem=elytron/syslog-audit-log=").append(name) .append(":add("); if (isNotBlank(format)) { command.append("format=\"").append(format).append("\", "); } if (isNotBlank(hostName)) { command.append("host-name=\"").append(hostName).append("\", "); } if (port != null) { command.append("port=").append(port).append(", "); } if (isNotBlank(serverAddress)) { command.append("server-address=\"").append(serverAddress).append("\", "); } if (isNotBlank(sslContext)) { command.append("ssl-context=\"").append(sslContext).append("\", "); } if (isNotBlank(transport)) { command.append("transport=\"").append(transport).append("\", "); } if (maxReconnectAttempts != null) { command.append("reconnect-attempts=").append(maxReconnectAttempts).append(", "); } command.append(")"); cli.sendLine(command.toString()); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/syslog-audit-log=%s:remove()", name)); } /** * Creates builder to build {@link FileAuditLog}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link FileAuditLog}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String format; private String hostName; private Integer port; private String serverAddress; private String sslContext; private String transport; private Integer maxReconnectAttempts; private Builder() { } public Builder withServerAddress(String serverAddress) { this.serverAddress = serverAddress; return this; } public Builder withPort(int port) { this.port = port; return this; } public Builder withTransportProtocol(String transport) { this.transport = transport; return this; } public Builder withHostName(String hostName) { this.hostName = hostName; return this; } public Builder withFormat(String format) { this.format = format; return this; } public Builder withSslContext(String sslContext) { this.sslContext = sslContext; return this; } public Builder setMaxReconnectAttempts(int maxReconnectAttempts) { this.maxReconnectAttempts = maxReconnectAttempts; return this; } public SyslogAuditLog build() { return new SyslogAuditLog(this); } @Override protected Builder self() { return this; } } }
5,079
30.75
102
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/MechanismConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import java.util.ArrayList; import java.util.List; import org.jboss.dmr.ModelNode; /** * Object which holds single instance from mechanism-configurations list. * * @author Josef Cacek */ public class MechanismConfiguration extends AbstractMechanismConfiguration { private final String mechanismName; private final String hostName; private final String protocol; private final String credentialSecurityFactory; private final List<MechanismRealmConfiguration> mechanismRealmConfigurations; private MechanismConfiguration(Builder builder) { super(builder); this.mechanismName = builder.mechanismName; this.hostName = builder.hostName; this.protocol = builder.protocol; this.credentialSecurityFactory = builder.credentialSecurityFactory; this.mechanismRealmConfigurations = new ArrayList<>(builder.mechanismRealmConfigurations); } public String getMechanismName() { return mechanismName; } public String getHostName() { return hostName; } public String getProtocol() { return protocol; } public String getCredentialSecurityFactory() { return credentialSecurityFactory; } public List<MechanismRealmConfiguration> getMechanismRealmConfigurations() { return mechanismRealmConfigurations; } /** * Creates builder to build {@link MechanismConfiguration}. * * @return created builder */ public static Builder builder() { return new Builder(); } @Override public ModelNode toModelNode() { ModelNode node = super.toModelNode(); setIfNotNull(node, "mechanism-name", mechanismName); setIfNotNull(node, "host-name", hostName); setIfNotNull(node, "protocol", protocol); setIfNotNull(node, "credential-security-factory", credentialSecurityFactory); if (!mechanismRealmConfigurations.isEmpty()) { ModelNode confs = node.get("mechanism-realm-configurations"); for (MechanismRealmConfiguration conf:mechanismRealmConfigurations) { confs.add(conf.toModelNode()); } } return node; } /** * Builder to build {@link MechanismConfiguration}. */ public static final class Builder extends AbstractMechanismConfiguration.Builder<Builder> { private String mechanismName; private String hostName; private String protocol; private String credentialSecurityFactory; private List<MechanismRealmConfiguration> mechanismRealmConfigurations = new ArrayList<>(); private Builder() { } public Builder withMechanismName(String mechanismName) { this.mechanismName = mechanismName; return this; } public Builder withHostName(String hostName) { this.hostName = hostName; return this; } public Builder withProtocol(String protocol) { this.protocol = protocol; return this; } public Builder withCredentialSecurityFactory(String credentialSecurityFactory) { this.credentialSecurityFactory = credentialSecurityFactory; return this; } public Builder addMechanismRealmConfiguration(MechanismRealmConfiguration mechanismRealmConfiguration) { this.mechanismRealmConfigurations.add(mechanismRealmConfiguration); return this; } public MechanismConfiguration build() { return new MechanismConfiguration(this); } @Override protected Builder self() { return this; } } }
4,855
32.034014
112
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/JdbcSecurityRealm.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed 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.wildfly.test.security.common.elytron; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * A {@link ConfigurableElement} to define a JDBC SecurityRealm resource. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class JdbcSecurityRealm implements SecurityRealm { private final PathAddress address; private final String name; private final List<ModelNode> principalQueries; private final String hashCharset; JdbcSecurityRealm(final String name, final List<ModelNode> principalQueries, String hashCharset) { this.name = name; this.address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "elytron"), PathElement.pathElement("jdbc-realm", name)); this.principalQueries = principalQueries; this.hashCharset = hashCharset; } @Override public String getName() { return name; } public ModelNode getAddOperation() { ModelNode addOperation = Util.createAddOperation(address); addOperation.get("principal-query").set(principalQueries); addOperation.get("hash-charset").set(hashCharset); return addOperation; } public ModelNode getRemoveOperation() { return Util.createRemoveOperation(address); } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getAddOperation(), client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getRemoveOperation(), client); } public static Builder builder(final String name) { return new Builder(name); } public static class PrincipalQueryBuilder { private final Builder builder; private final String datasource; private final String sql; private Map<String, ModelNode> passwordMappers = new LinkedHashMap<>(); private List<ModelNode> attributeMappers = new ArrayList<>(); PrincipalQueryBuilder(final Builder builder, final String datasource, final String sql) { this.builder = builder; this.datasource = datasource; this.sql = sql; } public PrincipalQueryBuilder withPasswordMapper(final String passwordType, final String algorithm, final int passwordIndex, final int saltIndex, final int iteractionCountIndex) { return withPasswordMapper(passwordType, algorithm, passwordIndex, Encoding.BASE64, saltIndex, Encoding.BASE64, iteractionCountIndex); } public PrincipalQueryBuilder withPasswordMapper(final String passwordType, final String algorithm, final int passwordIndex, final Encoding passwordEncoding, final int saltIndex, final Encoding saltEncoding, final int iteractionCountIndex) { ModelNode passwordMapper = new ModelNode(); if (algorithm != null) { passwordMapper.get("algorithm").set(algorithm); } passwordMapper.get("password-index").set(passwordIndex); if (passwordEncoding == Encoding.HEX) { passwordMapper.get("hash-encoding").set("hex"); } if (saltIndex > 0) { passwordMapper.get("salt-index").set(saltIndex); if (saltEncoding == Encoding.HEX) { passwordMapper.get("salt-encoding").set("hex"); } } if (iteractionCountIndex > 0) { passwordMapper.get("iteration-count-index").set(iteractionCountIndex); } passwordMappers.put(passwordType, passwordMapper); return this; } public PrincipalQueryBuilder withAttributeMapper(final String attributeName, final int attributeIndex) { ModelNode attributeMapper = new ModelNode(); attributeMapper.get("index").set(attributeIndex); attributeMapper.get("to").set(attributeName); attributeMappers.add(attributeMapper); return this; } public Builder build() { ModelNode principalQuery = new ModelNode(); principalQuery.get("data-source").set(datasource); principalQuery.get("sql").set(sql); for (Entry<String, ModelNode> mapper : passwordMappers.entrySet()) { principalQuery.get(mapper.getKey()).set(mapper.getValue()); } if (attributeMappers.size() > 0) { principalQuery.get("attribute-mapping").set(attributeMappers); } return builder.addPrincipalQuery(principalQuery); } } public static class Builder { private final String name; private List<ModelNode> queries = new ArrayList<>(); private String hashCharset; Builder(final String name) { this.name = name; } public PrincipalQueryBuilder withPrincipalQuery(final String datasource, final String sql) { return new PrincipalQueryBuilder(this, datasource, sql); } Builder addPrincipalQuery(final ModelNode principalQuery) { queries.add(principalQuery); return this; } public Builder withHashCharset(String hashCharset) { this.hashCharset = hashCharset; return this; } public SecurityRealm build() { return new JdbcSecurityRealm(name, queries, hashCharset != null ? hashCharset : "UTF-8"); } } public enum Encoding { BASE64, HEX; } }
6,673
33.580311
186
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/AbstractConstantHelper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.Objects; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Helper abstract parent Elytron constant-* resources with one "constant" attribute. * * @author Josef Cacek */ public abstract class AbstractConstantHelper extends AbstractConfigurableElement { private final String constant; protected AbstractConstantHelper(Builder<?> builder) { super(builder); this.constant = Objects.requireNonNull(builder.constant, "Constant has to be provided"); } @Override public void create(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/%s=%s:add(constant=\"%s\")", getConstantElytronType(), name, constant)); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/%s=%s:remove()", getConstantElytronType(), name)); } /** * Returns elytron node name (e.g. for resource /subsystem=elytron/constant-principal-transformer resources it returns * "constant-principal-transformer"). */ protected abstract String getConstantElytronType(); /** * Builder to build {@link AbstractConstantHelper}. */ public abstract static class Builder<T extends Builder<T>> extends AbstractConfigurableElement.Builder<T> { private String constant; protected Builder() { } public T withConstant(String constant) { this.constant = constant; return self(); } } }
2,615
34.835616
127
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/X500AttributePrincipalDecoder.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Elytron x500-attribute-principal-decoder configuration implementation. * * @author Ondrej Kotek */ public class X500AttributePrincipalDecoder extends AbstractConfigurableElement { private final String oid; private final String attributeName; private final Integer maximumSegments; private X500AttributePrincipalDecoder(Builder builder) { super(builder); this.oid = builder.oid; this.attributeName = builder.attributeName; this.maximumSegments = builder.maximumSegments; if ((attributeName == null && oid == null) || (attributeName != null && oid != null)) { throw new IllegalArgumentException("attribute-name xor oid has to be provided"); } } @Override public void create(CLIWrapper cli) throws Exception { // /subsystem=elytron/x500-attribute-principal-decoder=test:add(oid=2.5.4.3,maximum-segments=1) StringBuilder command = new StringBuilder("/subsystem=elytron/x500-attribute-principal-decoder=").append(name) .append(":add("); if (oid != null) { command.append("oid=").append(oid); } else { command.append("attribute-name=").append(attributeName); } if (maximumSegments != null) { command.append(",maximum-segments=").append(maximumSegments); } command.append(")"); cli.sendLine(command.toString()); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/x500-attribute-principal-decoder=%s:remove()", name)); } /** * Creates builder to build {@link X500AttributePrincipalDecoder}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link X500AttributePrincipalDecoder}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String oid; private String attributeName; private Integer maximumSegments; private Builder() { } /** * Uses attribute with given object id to construct principal name. E.g. oid "2.5.4.3" ~ CN (Common Name). * {@link #withAttributeName(String)} can be used instead. * @param oid object identifier * @return builder */ public Builder withOid(String oid) { this.oid = oid; return this; } public Builder withAttributeName(String attributeName) { this.attributeName = attributeName; return this; } public Builder withMaximumSegments(int maximumSegments) { this.maximumSegments = maximumSegments; return this; } public X500AttributePrincipalDecoder build() { return new X500AttributePrincipalDecoder(this); } @Override protected Builder self() { return this; } } }
4,195
33.113821
118
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/UserWithAttributeValues.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.Arrays; import java.util.HashSet; import java.util.Objects; import java.util.Set; /** * Object which holds user configuration (password, values). * * @author Josef Cacek */ public class UserWithAttributeValues { private final String name; private final String password; private final Set<String> values; private UserWithAttributeValues(Builder builder) { this.name = Objects.requireNonNull(builder.name, "Username must be not-null"); this.password = builder.password != null ? builder.password : builder.name; this.values = new HashSet<>(builder.values); } /** * Returns username. */ public String getName() { return name; } /** * Returns password as plain text. */ public String getPassword() { return password; } /** * Set of roles to be assigned to the user. */ public Set<String> getValues() { return values; } /** * Creates builder to build {@link UserWithAttributeValues}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link UserWithAttributeValues}. */ public static final class Builder { private String name; private String password; private final Set<String> values = new HashSet<>(); private Builder() { } public Builder withName(String name) { this.name = name; return this; } public Builder withPassword(String password) { this.password = password; return this; } /** * Add given attribute values to the builder. It doesn't replace existing values, but it adds given valuess to them. */ public Builder withValues(Set<String> values) { if (values != null) { this.values.addAll(values); } return this; } /** * Add given values to the builder. It doesn't replace existing values, but it adds given value to them. */ public Builder withValues(String... values) { if (values != null) { this.values.addAll(Arrays.asList(values)); } return this; } /** * Clears set of already added roles. */ public Builder clearValues() { this.values.clear(); return this; } /** * Builds UserWithRoles instance. * * @return */ public UserWithAttributeValues build() { return new UserWithAttributeValues(this); } } }
3,826
26.934307
124
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/FailoverRealm.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * A {@link ConfigurableElement} to define the failover-realm resource within the Elytron subsystem. * * @author Ondrej Kotek */ public class FailoverRealm implements SecurityRealm { private final PathAddress address; private final String name; private final String delegateRealm; private final String failoverRealm; private final Boolean emitEvents; FailoverRealm(final String name, final Builder builder) { this.name = name; this.address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "elytron"), PathElement.pathElement("failover-realm", name)); this.delegateRealm = builder.delegateRealm; this.failoverRealm = builder.failoverRealm; this.emitEvents = builder.emitEvents; } @Override public String getName() { return name; } public ModelNode getAddOperation() { ModelNode addOperation = Util.createAddOperation(address); if (this.delegateRealm != null) { addOperation.get("delegate-realm").set(this.delegateRealm); } if (this.failoverRealm != null) { addOperation.get("failover-realm").set(this.failoverRealm); } if (this.emitEvents != null) { addOperation.get("emit-events").set(this.emitEvents); } return addOperation; } public ModelNode getRemoveOperation() { return Util.createRemoveOperation(address); } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getAddOperation(), client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getRemoveOperation(), client); } public static Builder builder(final String name) { return new Builder(name); } public static class Builder { private final String name; private String delegateRealm; private String failoverRealm; private Boolean emitEvents; Builder(final String name) { this.name = name; } public Builder withDelegateRealm(final String realm) { this.delegateRealm = realm; return this; } public Builder withFailoverRealm(final String realm) { this.failoverRealm = realm; return this; } public Builder withEmitEvents(final Boolean emitEvents) { this.emitEvents = emitEvents; return this; } public SecurityRealm build() { return new FailoverRealm(name, this); } } }
4,119
31.440945
145
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/UndertowDomainMapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.HashSet; import java.util.Set; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Creates Undertow mapping to Elytron security domain. The Undertow-to-Elytron mapping goes from Undertow * {@code applicationDomain} configuration to Elytron's {@code http-authentication-factory} (which uses a * {@code http-server-mechanism-factor}). The {@code http-authentication-factory} then references Elytron security domain to be * used. * <p> * Configuration of this undertow mapping may contain set of application domains names (referenced as {@code security-domain}s * in {@code jboss-web.xml}) to be mapped to given security domain name. If applicationDomains is not configured for the mapper * (i.e. it's empty), then just one mapping is created with applicationDomain name the same as Elytron security domain name. If * the applicationDomains attribute is not empty, then just the provided names are mapped (i.e. the Elytron domain name is not * used automatically in such case). * </p> * * @author Josef Cacek * @deprecated Configures more than one resource, use {@code UndertowApplicationSecurityDomain} */ @Deprecated public class UndertowDomainMapper extends AbstractConfigurableElement { private final Set<String> applicationDomains; private UndertowDomainMapper(Builder builder) { super(builder); this.applicationDomains = new HashSet<>(builder.applicationDomains); } @Override public void create(CLIWrapper cli) throws Exception { // /subsystem=elytron/provider-http-server-mechanism-factory=test:add() cli.sendLine(String.format("/subsystem=elytron/provider-http-server-mechanism-factory=%s:add()", name)); // /subsystem=elytron/http-authentication-factory=test:add(security-domain=test, // http-server-mechanism-factory=test, // mechanism-configurations=[ // {mechanism-name=DIGEST,mechanism-realm-configurations=[{realm-name=test}]}, // {mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=test}]}, // {mechanism-name=FORM]}]) cli.sendLine(String .format("/subsystem=elytron/http-authentication-factory=%1$s:add(security-domain=%1$s, http-server-mechanism-factory=%1$s," + " mechanism-configurations=[" + " {mechanism-name=DIGEST,mechanism-realm-configurations=[{realm-name=%1$s}]}," + " {mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=%1$s}]}," + " {mechanism-name=EXTERNAL}," + " {mechanism-name=FORM}])", name)); if (applicationDomains.isEmpty()) { // /subsystem=undertow/application-security-domain=test:add(http-authentication-factory=test) cli.sendLine(String.format( "/subsystem=undertow/application-security-domain=%1$s:add(http-authentication-factory=%1$s)", name)); } else { for (String appDomain : applicationDomains) { // /subsystem=undertow/application-security-domain=appdomain:add(http-authentication-factory=test) cli.sendLine( String.format("/subsystem=undertow/application-security-domain=%s:add(http-authentication-factory=%s)", appDomain, name)); } } } @Override public void remove(CLIWrapper cli) throws Exception { if (applicationDomains.isEmpty()) { cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", name)); } else { for (String appDomain : applicationDomains) { cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", appDomain)); } } cli.sendLine(String.format("/subsystem=elytron/http-authentication-factory=%s:remove()", name)); cli.sendLine(String.format("/subsystem=elytron/provider-http-server-mechanism-factory=%s:remove()", name)); } /** * Creates builder to build {@link UndertowDomainMapper}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link UndertowDomainMapper}. The name attribute is used for security domain name. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private Set<String> applicationDomains = new HashSet<>(); private Builder() { } /** * Adds given application domains to the configuration. */ public Builder withApplicationDomains(String... applicationDomains) { if (applicationDomains != null) { for (String domain : applicationDomains) { this.applicationDomains.add(domain); } } return this; } public UndertowDomainMapper build() { return new UndertowDomainMapper(this); } @Override protected Builder self() { return this; } } }
6,270
43.161972
139
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleServerSslContext.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.Arrays; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Elytron server-ssl-context configuration implementation. * * @author Josef Cacek */ public class SimpleServerSslContext extends AbstractConfigurableElement implements ServerSslContext { private final String keyManager; private final String trustManager; private final String securityDomain; private final String[] protocols; private final boolean needClientAuth; private final Boolean authenticationOptional; private SimpleServerSslContext(Builder builder) { super(builder); this.keyManager = builder.keyManager; this.trustManager = builder.trustManager; this.securityDomain = builder.securityDomain; this.protocols = builder.protocols; this.needClientAuth = builder.needClientAuth; this.authenticationOptional = builder.authenticationOptional; } @Override public void create(CLIWrapper cli) throws Exception { // /subsystem=elytron/server-ssl-context=twoWaySSC:add(key-manager=twoWayKM,protocols=["TLSv1.2"], // trust-manager=twoWayTM,security-domain=test,need-client-auth=true) StringBuilder sb = new StringBuilder("/subsystem=elytron/server-ssl-context=").append(name).append(":add("); if (StringUtils.isNotBlank(keyManager)) { sb.append("key-manager=\"").append(keyManager).append("\", "); } if (protocols != null) { sb.append("protocols=[") .append(Arrays.stream(protocols).map(s -> "\"" + s + "\"").collect(Collectors.joining(", "))).append("], "); } if (StringUtils.isNotBlank(trustManager)) { sb.append("trust-manager=\"").append(trustManager).append("\", "); } if (StringUtils.isNotBlank(securityDomain)) { sb.append("security-domain=\"").append(securityDomain).append("\", "); } if (authenticationOptional != null) { sb.append("authentication-optional=").append(authenticationOptional).append(", "); } sb.append("need-client-auth=").append(needClientAuth).append(")"); cli.sendLine(sb.toString()); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/server-ssl-context=%s:remove()", name)); } /** * Creates builder to build {@link SimpleServerSslContext}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleServerSslContext}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String keyManager; private String trustManager; private String securityDomain; private String[] protocols; private boolean needClientAuth; private Boolean authenticationOptional; private Builder() { } public Builder withKeyManagers(String keyManagers) { this.keyManager = keyManagers; return this; } public Builder withTrustManagers(String trustManagers) { this.trustManager = trustManagers; return this; } public Builder withSecurityDomain(String securityDomain) { this.securityDomain = securityDomain; return this; } public Builder withProtocols(String... protocols) { this.protocols = protocols; return this; } public Builder withNeedClientAuth(boolean needClientAuth) { this.needClientAuth = needClientAuth; return this; } public Builder withAuthenticationOptional(boolean authenticationOptional) { this.authenticationOptional = authenticationOptional; return this; } public SimpleServerSslContext build() { return new SimpleServerSslContext(this); } @Override protected Builder self() { return this; } } }
5,304
35.088435
128
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/KeyStore.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Interface representing Elytron key-stores. * * @author Josef Cacek */ public interface KeyStore extends ConfigurableElement { }
1,214
35.818182
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/TrustManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Interface representing Elytron trust-manager. * * @author Josef Cacek */ public interface TrustManager extends ConfigurableElement { }
1,221
36.030303
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/AbstractMechanismConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import org.jboss.dmr.ModelNode; /** * Common parent for mechanism-realm-configuration and mechanism-configurations. * * @author Josef Cacek */ public class AbstractMechanismConfiguration { private final String preRealmPrincipalTransformer; private final String postRealmPrincipalTransformer; private final String finalPrincipalTransformer; private final String realmMapper; protected AbstractMechanismConfiguration(Builder<?> builder) { this.preRealmPrincipalTransformer = builder.preRealmPrincipalTransformer; this.postRealmPrincipalTransformer = builder.postRealmPrincipalTransformer; this.finalPrincipalTransformer = builder.finalPrincipalTransformer; this.realmMapper = builder.realmMapper; } public String getPreRealmPrincipalTransformer() { return preRealmPrincipalTransformer; } public String getPostRealmPrincipalTransformer() { return postRealmPrincipalTransformer; } public String getFinalPrincipalTransformer() { return finalPrincipalTransformer; } public String getRealmMapper() { return realmMapper; } protected ModelNode toModelNode() { final ModelNode node= new ModelNode(); setIfNotNull(node, "pre-realm-principal-transformer", preRealmPrincipalTransformer); setIfNotNull(node, "post-realm-principal-transformer", postRealmPrincipalTransformer); setIfNotNull(node, "final-principal-transformer", finalPrincipalTransformer); setIfNotNull(node, "realm-mapper", realmMapper); return node; } /** * Builder to build {@link AbstractMechanismConfiguration}. */ public abstract static class Builder<T extends Builder<T>> { private String preRealmPrincipalTransformer; private String postRealmPrincipalTransformer; private String finalPrincipalTransformer; private String realmMapper; protected Builder() { } protected abstract T self(); public T withPreRealmPrincipalTransformer(String preRealmPrincipalTransformer) { this.preRealmPrincipalTransformer = preRealmPrincipalTransformer; return self(); } public T withPostRealmPrincipalTransformer(String postRealmPrincipalTransformer) { this.postRealmPrincipalTransformer = postRealmPrincipalTransformer; return self(); } public T withFinalPrincipalTransformer(String finalPrincipalTransformer) { this.finalPrincipalTransformer = finalPrincipalTransformer; return self(); } public T withRealmMapper(String realmMapper) { this.realmMapper = realmMapper; return self(); } } }
3,913
35.240741
94
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/Ocsp.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.apache.commons.lang3.StringUtils.isNotBlank; /** * Helper class for adding "ocsp" attribute. * * @author Jan Stourac <jstourac@redhat.com> */ public class Ocsp implements CliFragment { public static final Ocsp EMPTY = Ocsp.builder().build(); private final String responder; private final String responderKeyStore; private final String responderCertificate; private final boolean preferCrls; private Ocsp(Builder builder) { this.responder = builder.responder; this.responderKeyStore = builder.responderKeyStore; this.responderCertificate = builder.responderCertificate; this.preferCrls = builder.preferCrls; } @Override public String asString() { StringBuilder sb = new StringBuilder(); sb.append("ocsp={ "); if (isNotBlank(responder)) { sb.append(String.format("responder=\"%s\", ", responder)); } if (isNotBlank(responderKeyStore)) { sb.append(String.format("responder-keystore=\"%s\", ", responderKeyStore)); } if (isNotBlank(responderCertificate)) { sb.append(String.format("responder-certificate=\"%s\", ", responderCertificate)); } sb.append(String.format("prefer-crls=\"%s\", ", preferCrls)); sb.append("}, "); return sb.toString(); } /** * Creates builder to build {@link Ocsp}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link Ocsp}. */ public static final class Builder { private String responder; private String responderKeyStore; private String responderCertificate; private boolean preferCrls; private Builder() { } public Builder withResponder(String responder) { this.responder = responder; return this; } public Builder withResponderKeyStore(String responderKeyStore) { this.responderKeyStore = responderKeyStore; return this; } public Builder withResponderCertificate(String responderCertificate) { this.responderCertificate = responderCertificate; return this; } public Builder withPreferCrls(boolean preferCrls) { this.preferCrls = preferCrls; return this; } public Ocsp build() { return new Ocsp(this); } } }
3,603
30.893805
93
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleAuthContext.java
/* * Copyright 2017 Red Hat, Inc. * * Licensed 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.wildfly.test.security.common.elytron; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Elytron authentication context configuration implementation. * * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a> */ public class SimpleAuthContext extends AbstractConfigurableElement { private final String extendsAttr; private final MatchRules matchRules; private SimpleAuthContext(final Builder builder) { super(builder); this.extendsAttr = builder.extendsAttr; this.matchRules = builder.matchRules; } @Override public void create(CLIWrapper cli) throws Exception { final StringBuilder sb = new StringBuilder("/subsystem=elytron/authentication-context=\""); sb.append(name).append("\":add("); if (extendsAttr != null && !extendsAttr.isEmpty()) { sb.append(String.format("extends=\"%s\", ", extendsAttr)); } if (matchRules != null) { sb.append(matchRules.asString()); } sb.append(")"); cli.sendLine(sb.toString()); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/authentication-context=\"%s\":remove", name)); } public static Builder builder() { return new Builder(); } public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String extendsAttr; private MatchRules matchRules; private Builder() { } public Builder withExtends(final String extendsAttr) { this.extendsAttr = extendsAttr; return this; } public Builder withMatchRules(final MatchRules matchRules) { this.matchRules = matchRules; return this; } public SimpleAuthContext build() { return new SimpleAuthContext(this); } @Override protected Builder self() { return this; } } }
2,652
29.494253
101
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ConstantRealmMapper.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed 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.wildfly.test.security.common.elytron; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * A {@link ConfigurableElement} to define a constant realm mapper resource. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class ConstantRealmMapper implements ConfigurableElement { private final PathAddress address; private final String name; private final String realm; ConstantRealmMapper(String name, String realm) { this.name = name; this.address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "elytron"), PathElement.pathElement("constant-realm-mapper", name)); this.realm = realm; } @Override public String getName() { return name; } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode addOperation = Util.createAddOperation(address); addOperation.get("realm-name").set(realm); Utils.applyUpdate(addOperation, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode removeOperation = Util.createRemoveOperation(address); Utils.applyUpdate(removeOperation, client); } public static ConfigurableElement newInstance(final String name, final String realm) { return new ConstantRealmMapper(name, realm); } }
2,346
33.514706
152
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/DistributedRealm.java
/* * Copyright 2020 Red Hat, Inc. * * Licensed 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.wildfly.test.security.common.elytron; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * A {@link ConfigurableElement} to define the distributed-realm resource within the Elytron subsystem. * * @author Ondrej Kotek */ public class DistributedRealm implements SecurityRealm { private final PathAddress address; private final String name; private final String[] realms; private final Boolean ignoreUnavailableRealms; private final Boolean emitEvents; DistributedRealm(final String name, final Builder builder) { this.name = name; this.address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "elytron"), PathElement.pathElement("distributed-realm", name)); this.realms = builder.realms; this.ignoreUnavailableRealms = builder.ignoreUnavailableRealms; this.emitEvents = builder.emitEvents; } @Override public String getName() { return name; } public ModelNode getAddOperation() { ModelNode addOperation = Util.createAddOperation(address); if (realms != null) { ModelNode realmsList = addOperation.get("realms"); for (String realmName : realms) { realmsList.add(realmName); } } if (this.ignoreUnavailableRealms != null) { addOperation.get("ignore-unavailable-realms").set(this.ignoreUnavailableRealms); } if (this.emitEvents != null) { addOperation.get("emit-events").set(this.emitEvents); } return addOperation; } public ModelNode getRemoveOperation() { return Util.createRemoveOperation(address); } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getAddOperation(), client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getRemoveOperation(), client); } public static Builder builder(final String name) { return new Builder(name); } public static class Builder { private final String name; private String[] realms; private Boolean ignoreUnavailableRealms; private Boolean emitEvents; Builder(final String name) { this.name = name; } public Builder withRealms(final String... realms) { this.realms = realms; return this; } public Builder withIgnoreUnavailableRealms(final Boolean ignoreUnavailableRealms) { this.ignoreUnavailableRealms = ignoreUnavailableRealms; return this; } public Builder withEmitEvents(final Boolean emitEvents) { this.emitEvents = emitEvents; return this; } public SecurityRealm build() { return new DistributedRealm(name, this); } } }
3,877
30.024
148
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/CertificateRevocationList.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.apache.commons.lang3.StringUtils.isNotBlank; /** * Helper class for adding "certificate-revocation-list" attribute. * * @author Jan Stourac <jstourac@redhat.com> */ public class CertificateRevocationList implements CliFragment { public static final CertificateRevocationList EMPTY = CertificateRevocationList.builder().build(); private final String path; private final String relativeTo; private CertificateRevocationList(Builder builder) { this.path = builder.path; this.relativeTo = builder.relativeTo; } @Override public String asString() { StringBuilder sb = new StringBuilder(); if (isNotBlank(path)) { sb.append(String.format("{path=\"%s\", ", path)); } if (isNotBlank(relativeTo)) { sb.append(String.format("relative-to=\"%s\", ", relativeTo)); } sb.append("}"); return sb.toString(); } /** * Creates builder to build {@link CertificateRevocationList}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link CertificateRevocationList}. */ public static final class Builder { private String path; private String relativeTo; private Builder() { } public Builder withPath(String path) { this.path = path; return this; } public Builder withRelativeTo(String relativeTo) { this.relativeTo = relativeTo; return this; } public CertificateRevocationList build() { return new CertificateRevocationList(this); } } }
2,817
29.301075
102
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/PermissionMapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * @author Jan Martiska */ public interface PermissionMapper extends ConfigurableElement { enum MappingMode { AND("and"), FIRST("first"), OR("or"), UNLESS("unless"), XOR("xor"); MappingMode(String string) { this.string = string; } private String string; @Override public String toString() { return string; } } }
1,517
29.36
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ClientCertUndertowDomainMapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.Objects; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Creates Undertow mapping to Elytron security domain. The Undertow-to-Elytron mapping goes from Undertow * {@code application-security-domain} configuration to Elytron's {@code http-authentication-factory} * (which uses a {@code http-server-mechanism-factory}) with CLIENT-CERT mechanism set. * The {@code http-authentication-factory} then references Elytron security domain to be used. * * @author Ondrej Kotek */ public class ClientCertUndertowDomainMapper extends AbstractConfigurableElement { private final String securityDomain; private ClientCertUndertowDomainMapper(Builder builder) { super(builder); this.securityDomain = Objects.requireNonNull(builder.securityDomain, "Security domain name has to be provided"); } @Override public void create(CLIWrapper cli) throws Exception { // /subsystem=elytron/provider-http-server-mechanism-factory=test:add() cli.sendLine(String.format("/subsystem=elytron/provider-http-server-mechanism-factory=%s:add()", name)); // /subsystem=elytron/http-authentication-factory=test:add(security-domain=test, // http-server-mechanism-factory=test, // mechanism-configurations=[{mechanism-name=CLIENT-CERT,mechanism-realm-configurations=[{realm-name=test}]}]) cli.sendLine(String.format("/subsystem=elytron/http-authentication-factory=%1$s:add(security-domain=%2$s," + "http-server-mechanism-factory=%1$s," + "mechanism-configurations=[{mechanism-name=CLIENT_CERT,mechanism-realm-configurations=[{realm-name=%1$s}]}])", name, securityDomain)); // /subsystem=undertow/application-security-domain=test:add(http-authentication-factory=test) cli.sendLine(String.format( "/subsystem=undertow/application-security-domain=%1$s:add(http-authentication-factory=%1$s)", name)); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", name)); cli.sendLine(String.format("/subsystem=elytron/http-authentication-factory=%s:remove()", name)); cli.sendLine(String.format("/subsystem=elytron/provider-http-server-mechanism-factory=%s:remove()", name)); } /** * Creates builder to build {@link ClientCertUndertowDomainMapper}. * The name attribute is used for http-authentication-factory and provider-http-server-mechanism-factory names. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link ClientCertUndertowDomainMapper}. * The name attribute is used for http-authentication-factory and provider-http-server-mechanism-factory names. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String securityDomain; private Builder() { } public Builder withSecurityDomain(String securityDomain) { this.securityDomain = securityDomain; return this; } public ClientCertUndertowDomainMapper build() { return new ClientCertUndertowDomainMapper(this); } @Override protected Builder self() { return this; } } }
4,543
41.46729
128
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleSaslAuthenticationFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * Elytron sasl-authentication-factory configuration. * * @author Josef Cacek */ public class SimpleSaslAuthenticationFactory extends AbstractConfigurableElement implements SaslAuthenticationFactory { private final List<MechanismConfiguration> mechanismConfigurations; private final String saslServerFactory; private final String securityDomain; private SimpleSaslAuthenticationFactory(Builder builder) { super(builder); this.mechanismConfigurations = new ArrayList<>(builder.mechanismConfigurations); this.saslServerFactory = Objects.requireNonNull(builder.saslServerFactory,"saslServerFactory must be not-null"); this.securityDomain = Objects.requireNonNull(builder.securityDomain,"securityDomain must be not-null"); } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode op = Util.createAddOperation( PathAddress.pathAddress().append("subsystem", "elytron").append("sasl-authentication-factory", name)); setIfNotNull(op, "sasl-server-factory", saslServerFactory); setIfNotNull(op, "security-domain", securityDomain); if (!mechanismConfigurations.isEmpty()) { ModelNode confs = op.get("mechanism-configurations"); for (MechanismConfiguration conf : mechanismConfigurations) { confs.add(conf.toModelNode()); } } Utils.applyUpdate(op, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(Util.createRemoveOperation( PathAddress.pathAddress().append("subsystem", "elytron").append("sasl-authentication-factory", name)), client); } /** * Creates builder to build {@link SimpleSaslAuthenticationFactory}. * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleSaslAuthenticationFactory}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private List<MechanismConfiguration> mechanismConfigurations = new ArrayList<>(); private String saslServerFactory; private String securityDomain; private Builder() { } public Builder addMechanismConfiguration(MechanismConfiguration mechanismConfiguration) { this.mechanismConfigurations.add(mechanismConfiguration); return this; } public Builder withSaslServerFactory(String saslServerFactory) { this.saslServerFactory = saslServerFactory; return this; } public Builder withSecurityDomain(String securityDomain) { this.securityDomain = securityDomain; return this; } public SimpleSaslAuthenticationFactory build() { return new SimpleSaslAuthenticationFactory(this); } @Override protected Builder self() { return this; } } }
4,673
36.392
120
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SimpleKeyManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; import java.util.Objects; import javax.net.ssl.KeyManagerFactory; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Elytron key-manager configuration implementation. * * @author Josef Cacek */ public class SimpleKeyManager extends AbstractConfigurableElement implements KeyManager { private final String keyStore; private final CredentialReference credentialReference; private final String generateSelfSignedCertificateHost; private SimpleKeyManager(Builder builder) { super(builder); this.keyStore = Objects.requireNonNull(builder.keyStore, "Key-store name has to be provided"); this.credentialReference = defaultIfNull(builder.credentialReference, CredentialReference.EMPTY); this.generateSelfSignedCertificateHost = builder.generateSelfSignedCertificateHost; } @Override public void create(CLIWrapper cli) throws Exception { // /subsystem=elytron/key-manager=httpsKM:add(key-store=httpsKS,algorithm="SunX509",credential-reference={clear-text=secret}) if (generateSelfSignedCertificateHost != null) { cli.sendLine(String.format("/subsystem=elytron/key-manager=%s:add(key-store=\"%s\",algorithm=\"%s\", %s,generate-self-signed-certificate-host=\"%s\")", name, keyStore, KeyManagerFactory.getDefaultAlgorithm(), credentialReference.asString(), generateSelfSignedCertificateHost)); } else { cli.sendLine(String.format("/subsystem=elytron/key-manager=%s:add(key-store=\"%s\",algorithm=\"%s\", %s)", name, keyStore, KeyManagerFactory.getDefaultAlgorithm(), credentialReference.asString())); } } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/key-manager=%s:remove()", name)); } /** * Creates builder to build {@link SimpleKeyManager}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleKeyManager}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String keyStore; private CredentialReference credentialReference; private String generateSelfSignedCertificateHost; private Builder() { } public Builder withKeyStore(String keyStore) { this.keyStore = keyStore; return this; } public Builder withCredentialReference(CredentialReference credentialReference) { this.credentialReference = credentialReference; return this; } public Builder withGenerateSelfSignedCertificateHost(String generateSelfSignedCertificateHost) { this.generateSelfSignedCertificateHost = generateSelfSignedCertificateHost; return this; } public SimpleKeyManager build() { return new SimpleKeyManager(this); } @Override protected Builder self() { return this; } } }
4,267
37.107143
169
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ConcatenatingPrincipalDecoder.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Elytron concatenating-principal-decoder configuration implementation. * * @author Ondrej Kotek */ public class ConcatenatingPrincipalDecoder extends AbstractConfigurableElement { private final String joiner; private final List<String> decoders; private ConcatenatingPrincipalDecoder(Builder builder) { super(builder); this.joiner = Objects.toString(builder.joiner, "."); this.decoders = Objects.requireNonNull(builder.decoders, "Principal decoders has to be provided"); if (this.decoders.size() < 2) { throw new IllegalArgumentException("At least 2 principal decoders have to be provided"); } } @Override public void create(CLIWrapper cli) throws Exception { // /subsystem=elytron/concatenating-principal-decoder=test:add(joiner=".",principal-decoders=[decA, decB])) cli.sendLine(String.format("/subsystem=elytron/concatenating-principal-decoder=%s:add(joiner=\"%s\",principal-decoders=[%s])", name, joiner, String.join(",", decoders))); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/concatenating-principal-decoder=%s:remove()", name)); } /** * Creates builder to build {@link ConcatenatingPrincipalDecoder}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link ConcatenatingPrincipalDecoder}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String joiner; private List<String> decoders; private Builder() { } public Builder withJoiner(String joiner) { this.joiner = joiner; return this; } public Builder withDecoders(String... decoders) { this.decoders = Arrays.asList(decoders); return this; } public ConcatenatingPrincipalDecoder build() { return new ConcatenatingPrincipalDecoder(this); } @Override protected Builder self() { return this; } } }
3,441
33.42
134
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/FileSystemRealm.java
/* * Copyright 2016 Red Hat, Inc. * * Licensed 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.wildfly.test.security.common.elytron; import static org.jboss.as.test.integration.security.common.Utils.createTemporaryFolder; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Configuration for filesystem-realms Elytron resource. * * @author Josef Cacek */ public class FileSystemRealm extends AbstractUserAttributeValuesCapableElement implements SecurityRealm { private final Path path; private final Integer level; private final File tempFolder; private FileSystemRealm(Builder builder) { super(builder); if (builder.path != null) { tempFolder = null; this.path = builder.path; } else { try { tempFolder = createTemporaryFolder("ely-" + getName()); } catch (IOException e) { throw new RuntimeException("Unable to create temporary folder", e); } this.path = Path.builder().withPath(tempFolder.getAbsolutePath()).build(); } level = builder.level; } @Override public void create(CLIWrapper cli) throws Exception { final String levelStr = level == null ? "" : ("level=" + level); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add(%s, %s)", name, path.asString(), levelStr)); for (UserWithAttributeValues user : getUsersWithAttributeValues()) { cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add-identity(identity=%s)", name, user.getName())); cli.sendLine( String.format("/subsystem=elytron/filesystem-realm=%s:set-password(identity=%s, clear={password=\"%s\"})", name, user.getName(), user.getPassword())); if (!user.getValues().isEmpty()) { cli.sendLine(String.format( "/subsystem=elytron/filesystem-realm=%s:add-identity-attribute(identity=%s, name=groups, value=[%s])", name, user.getName(), String.join(",", user.getValues()))); } } } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:remove()", name)); FileUtils.deleteQuietly(tempFolder); } public Path getPath() { return this.path; } /** * Creates builder to build {@link FileSystemRealm}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link FileSystemRealm}. */ public static final class Builder extends AbstractUserAttributeValuesCapableElement.Builder<Builder> { private Path path; private Integer level; private Builder() { } /** @implNote if a {@link Path} is set, the folder will not be automatically deleted after the test case completes. */ public Builder withPath(Path path) { this.path = path; return this; } public Builder withLevel(Integer level) { this.level = level; return this; } public FileSystemRealm build() { return new FileSystemRealm(this); } @Override public Builder self() { return this; } } }
4,060
32.561983
132
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/LdapRealm.java
/* * Copyright 2020 Red Hat, Inc. * * Licensed 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.wildfly.test.security.common.elytron; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; /** * A {@link ConfigurableElement} to define the ldap-realm resource within the Elytron subsystem. * * @author Ondrej Kotek */ public class LdapRealm implements SecurityRealm { private final PathAddress address; private final String name; private final String dirContext; private final Boolean directVerification; private final Boolean allowBlankPassword; private final IdentityMapping identityMapping; LdapRealm(Builder builder) { this.name = builder.name; this.address = PathAddress.pathAddress(PathElement.pathElement("subsystem", "elytron"), PathElement.pathElement("ldap-realm", name)); this.dirContext = builder.dirContext; this.directVerification = builder.directVerification; this.allowBlankPassword = builder.allowBlankPassword; this.identityMapping = builder.identityMapping; } @Override public String getName() { return name; } public ModelNode getAddOperation() { ModelNode addOperation = Util.createAddOperation(address); addOperation.get("ldap-realm"); if (dirContext != null) { addOperation.get("dir-context").set(dirContext); } if (directVerification != null) { addOperation.get("direct-verification").set(directVerification); } if (allowBlankPassword != null) { addOperation.get("allow-blank-password").set(allowBlankPassword); } if (identityMapping != null) { addOperation.get("identity-mapping").set(getIdentityMappingModel().asObject()); } return addOperation; } private ModelNode getIdentityMappingModel() { ModelNode identityMappingModelNode = new ModelNode(); if (!identityMapping.getAttributeMappings().isEmpty()) { List<ModelNode> attributeMappingNodeList = new ArrayList<ModelNode>(); for (AttributeMapping attributeMapping : identityMapping.getAttributeMappings()) { ModelNode node = new ModelNode(); if (attributeMapping.getFrom() != null) { node.add("from", attributeMapping.getFrom()); } if (attributeMapping.getTo() != null) { node.add("to", attributeMapping.getTo()); } if (attributeMapping.getFilter() != null) { node.add("filter", attributeMapping.getFilter()); } if (attributeMapping.getFilterBaseDn() != null) { node.add("filter-base-dn", attributeMapping.getFilterBaseDn()); } if (attributeMapping.getExtractRdn() != null) { node.add("extract-rdn", attributeMapping.getExtractRdn()); } if (attributeMapping.getSearchRecursive() != null) { node.add("search-recursive", attributeMapping.getSearchRecursive()); } if (attributeMapping.getRoleRecursion() != null) { node.add("role-recursion", attributeMapping.getRoleRecursion()); } if (attributeMapping.getRoleRecursionName() != null) { node.add("role-recursion-name", attributeMapping.getRoleRecursionName()); } if (attributeMapping.getReference() != null) { node.add("reference", attributeMapping.getReference()); } attributeMappingNodeList.add(node.asObject()); } ModelNode attributeMappingNode = new ModelNode(); attributeMappingNode.set(attributeMappingNodeList); identityMappingModelNode.add("attribute-mapping", attributeMappingNode); } if (identityMapping.getFilterName() != null) { identityMappingModelNode.add("filter-name", identityMapping.getFilterName()); } if (identityMapping.getIteratorFilter() != null) { identityMappingModelNode.add("iterator-filter", identityMapping.getIteratorFilter()); } if (!identityMapping.getNewIdentityAttributes().isEmpty()) { List<ModelNode> newIdentityAttributesNodeList = new ArrayList<ModelNode>(); for (NewIdentityAttributes newIdentityAttribute : identityMapping.getNewIdentityAttributes()) { ModelNode attributeNode = new ModelNode(); if (newIdentityAttribute.getName() != null) { attributeNode.add("name", newIdentityAttribute.getName()); } ModelNode valuesList = new ModelNode().setEmptyList(); for (String value : newIdentityAttribute.getValues()) { valuesList.add(value); } attributeNode.add("value", valuesList); newIdentityAttributesNodeList.add(attributeNode.asObject()); } ModelNode newIdentityAttributesNode = new ModelNode(); newIdentityAttributesNode.set(newIdentityAttributesNodeList); identityMappingModelNode.add("new-identity-attributes", newIdentityAttributesNode); } if (identityMapping.getNewIdentityParentDn() != null) { identityMappingModelNode.add("new-identity-parent-dn", identityMapping.getNewIdentityParentDn()); } if (identityMapping.getOtpCredentialMapper() != null) { OtpCredentialMapper otpCredentialMapper = identityMapping.getOtpCredentialMapper(); ModelNode node = new ModelNode(); node.add("algorithm-from", otpCredentialMapper.getAlgorithmFrom()); node.add("hash-from", otpCredentialMapper.getHashFrom()); node.add("seed-from", otpCredentialMapper.getSeedFrom()); node.add("sequence-from", otpCredentialMapper.getSequenceFrom()); identityMappingModelNode.add("otp-credential-mapper", node.asObject()); } if (identityMapping.getRdnIdentifier() != null) { identityMappingModelNode.add("rdn-identifier", identityMapping.getRdnIdentifier()); } if (identityMapping.getSearchBaseDn() != null) { identityMappingModelNode.add("search-base-dn", identityMapping.getSearchBaseDn()); } if (identityMapping.getUseRecursiveSearch() != null) { identityMappingModelNode.add("use-recursive-search", identityMapping.getUseRecursiveSearch()); } if (identityMapping.getUserPasswordMapper() != null) { UserPasswordMapper userPasswordMapper = identityMapping.getUserPasswordMapper(); ModelNode node = new ModelNode(); node.add("from", userPasswordMapper.getFrom()); if (userPasswordMapper.getWritable() != null) { node.add("writable", userPasswordMapper.getWritable()); } if (userPasswordMapper.getVerifiable() != null) { node.add("verifiable", userPasswordMapper.getVerifiable()); } identityMappingModelNode.add("user-password-mapper", node.asObject()); } if (identityMapping.getX509CredentialMapper() != null) { X509CredentialMapper x509CredentialMapper = identityMapping.getX509CredentialMapper(); ModelNode node = new ModelNode(); if (x509CredentialMapper.getDigestFrom() != null) { node.add("digest-from", x509CredentialMapper.getDigestFrom()); } if (x509CredentialMapper.getDigestAlgorithm() != null) { node.add("digest-algorithm", x509CredentialMapper.getDigestAlgorithm()); } if (x509CredentialMapper.getCertificateFrom() != null) { node.add("certificate-from", x509CredentialMapper.getCertificateFrom()); } if (x509CredentialMapper.getSerialNumberFrom() != null) { node.add("serial-number-from", x509CredentialMapper.getSerialNumberFrom()); } if (x509CredentialMapper.getSubjectDnFrom() != null) { node.add("subject-dn-from", x509CredentialMapper.getSubjectDnFrom()); } identityMappingModelNode.add("x509-credential-mapper", node.asObject()); } return identityMappingModelNode; } public ModelNode getRemoveOperation() { return Util.createRemoveOperation(address); } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getAddOperation(), client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(getRemoveOperation(), client); } public static Builder builder(final String name) { return new Builder(name); } public static IdentityMappingBuilder identityMappingBuilder() { return new IdentityMappingBuilder(); } public static final class Builder { private final String name; private String dirContext; private Boolean directVerification; private Boolean allowBlankPassword; private IdentityMapping identityMapping; public Builder(String name) { this.name = name; } public Builder withDirContext(String dirContext) { this.dirContext = dirContext; return this; } public Builder withDirectVerification(Boolean directVerification) { this.directVerification = directVerification; return this; } public Builder withAllowBlankPassword(Boolean allowBlankPassword) { this.allowBlankPassword = allowBlankPassword; return this; } public Builder withIdentityMapping(IdentityMapping identityMapping) { this.identityMapping = identityMapping; return this; } public LdapRealm build() { return new LdapRealm(this); } } public static final class IdentityMapping { private final String rdnIdentifier; private final String searchBaseDn; private final Boolean useRecursiveSearch; private final String filterName; private final String iteratorFilter; private final String newIdentityParentDn; private final List<AttributeMapping> attributeMappings; private final UserPasswordMapper userPasswordMapper; private final OtpCredentialMapper otpCredentialMapper; private final X509CredentialMapper x509CredentialMapper; private final List<NewIdentityAttributes> newIdentityAttributes; private IdentityMapping(IdentityMappingBuilder builder) { this.rdnIdentifier = builder.rdnIdentifier; this.searchBaseDn = builder.searchBaseDn; this.useRecursiveSearch = builder.useRecursiveSearch; this.filterName = builder.filterName; this.iteratorFilter = builder.iteratorFilter; this.newIdentityParentDn = builder.newIdentityParentDn; this.attributeMappings = builder.attributeMappings; this.userPasswordMapper = builder.userPasswordMapper; this.otpCredentialMapper = builder.otpCredentialMapper; this.newIdentityAttributes = builder.newIdentityAttributes; this.x509CredentialMapper = builder.x509CredentialMapper; } public String getRdnIdentifier() { return rdnIdentifier; } public String getSearchBaseDn() { return searchBaseDn; } public Boolean getUseRecursiveSearch() { return useRecursiveSearch; } public String getFilterName() { return filterName; } public String getIteratorFilter() { return iteratorFilter; } public String getNewIdentityParentDn() { return newIdentityParentDn; } public List<AttributeMapping> getAttributeMappings() { return attributeMappings; } public UserPasswordMapper getUserPasswordMapper() { return userPasswordMapper; } public OtpCredentialMapper getOtpCredentialMapper() { return otpCredentialMapper; } public X509CredentialMapper getX509CredentialMapper() { return x509CredentialMapper; } public List<NewIdentityAttributes> getNewIdentityAttributes() { return newIdentityAttributes; } } public static final class IdentityMappingBuilder { private String rdnIdentifier; private String searchBaseDn; private Boolean useRecursiveSearch; private String filterName; private String iteratorFilter; private String newIdentityParentDn; private List<AttributeMapping> attributeMappings = new ArrayList<AttributeMapping>(); private UserPasswordMapper userPasswordMapper; private OtpCredentialMapper otpCredentialMapper; private X509CredentialMapper x509CredentialMapper; private List<NewIdentityAttributes> newIdentityAttributes = new ArrayList<NewIdentityAttributes>(); public IdentityMappingBuilder withRdnIdentifier(String rdnIdentifier) { this.rdnIdentifier = rdnIdentifier; return this; } public IdentityMappingBuilder withSearchBaseDn(String searchBaseDn) { this.searchBaseDn = searchBaseDn; return this; } public IdentityMappingBuilder withUseRecursiveSearch(Boolean useRecursiveSearch) { this.useRecursiveSearch = useRecursiveSearch; return this; } public IdentityMappingBuilder withFilterName(String filterName) { this.filterName = filterName; return this; } public IdentityMappingBuilder withIteratorFilter(String iteratorFilter) { this.iteratorFilter = iteratorFilter; return this; } public IdentityMappingBuilder withNewIdentityParentDn(String newIdentityParentDn) { this.newIdentityParentDn = newIdentityParentDn; return this; } public IdentityMappingBuilder withAttributeMappings(AttributeMapping... attributeMappings) { if (attributeMappings != null) { Collections.addAll(this.attributeMappings, attributeMappings); } return this; } public IdentityMappingBuilder withUserPasswordMapper(UserPasswordMapper userPasswordMapper) { this.userPasswordMapper = userPasswordMapper; return this; } public IdentityMappingBuilder withOtpCredentialMapper(OtpCredentialMapper otpCredentialMapper) { this.otpCredentialMapper = otpCredentialMapper; return this; } public IdentityMappingBuilder withX509CredentialMapper(X509CredentialMapper x509CredentialMapper) { this.x509CredentialMapper = x509CredentialMapper; return this; } public IdentityMappingBuilder withNewIdentityAttributes(NewIdentityAttributes... newIdentityAttributes) { if (newIdentityAttributes != null) { Collections.addAll(this.newIdentityAttributes, newIdentityAttributes); } return this; } public IdentityMapping build() { return new IdentityMapping(this); } } public static final class AttributeMapping { private final String from; private final String to; private final String filter; private final String filterBaseDn; private final String extractRdn; private final Boolean searchRecursive; private final Integer roleRecursion; private final String roleRecursionName; private final String reference; private AttributeMapping(AttributeMappingBuilder builder) { this.from = builder.from; this.to = builder.to; this.filter = builder.filter; this.filterBaseDn = builder.filterBaseDn; this.extractRdn = builder.extractRdn; this.searchRecursive = builder.searchRecursive; this.roleRecursion = builder.roleRecursion; this.roleRecursionName = builder.roleRecursionName; this.reference = builder.reference; } public String getFrom() { return from; } public String getTo() { return to; } public String getFilter() { return filter; } public String getFilterBaseDn() { return filterBaseDn; } public String getExtractRdn() { return extractRdn; } public Boolean getSearchRecursive() { return searchRecursive; } public Integer getRoleRecursion() { return roleRecursion; } public String getRoleRecursionName() { return roleRecursionName; } public String getReference() { return reference; } } public static final class AttributeMappingBuilder { private String from; private String to; private String filter; private String filterBaseDn; private String extractRdn; private Boolean searchRecursive; private Integer roleRecursion; private String roleRecursionName; private String reference; public AttributeMappingBuilder withFrom(String from) { this.from = from; return this; } public AttributeMappingBuilder withTo(String to) { this.to = to; return this; } public AttributeMappingBuilder withFilter(String filter) { this.filter = filter; return this; } public AttributeMappingBuilder withFilterBaseDn(String filterBaseDn) { this.filterBaseDn = filterBaseDn; return this; } public AttributeMappingBuilder withExtractRdn(String extractRdn) { this.extractRdn = extractRdn; return this; } public AttributeMappingBuilder withSearchRecursive(Boolean searchRecursive) { this.searchRecursive = searchRecursive; return this; } public AttributeMappingBuilder withRoleRecursion(Integer roleRecursion) { this.roleRecursion = roleRecursion; return this; } public AttributeMappingBuilder withRoleRecursionName(String roleRecursionName) { this.roleRecursionName = roleRecursionName; return this; } public AttributeMappingBuilder withReference(String reference) { this.reference = reference; return this; } public AttributeMapping build() { return new AttributeMapping(this); } } public static final class UserPasswordMapper { private final String from; private final Boolean writable; private final Boolean verifiable; private UserPasswordMapper(UserPasswordMapperBuilder builder) { this.from = builder.from; this.writable = builder.writable; this.verifiable = builder.verifiable; } public String getFrom() { return from; } public Boolean getWritable() { return writable; } public Boolean getVerifiable() { return verifiable; } } public static final class UserPasswordMapperBuilder { private String from; private Boolean writable; private Boolean verifiable; public UserPasswordMapperBuilder withFrom(String from) { this.from = from; return this; } public UserPasswordMapperBuilder withWritable(Boolean writable) { this.writable = writable; return this; } public UserPasswordMapperBuilder withVerifiable(Boolean verifiable) { this.verifiable = verifiable; return this; } public UserPasswordMapper build() { return new UserPasswordMapper(this); } } public static final class OtpCredentialMapper { private final String algorithmFrom; private final String hashFrom; private final String seedFrom; private final String sequenceFrom; private OtpCredentialMapper(OtpCredentialMapperBuilder builder) { this.algorithmFrom = builder.algorithmFrom; this.hashFrom = builder.hashFrom; this.seedFrom = builder.seedFrom; this.sequenceFrom = builder.sequenceFrom; } public String getAlgorithmFrom() { return algorithmFrom; } public String getHashFrom() { return hashFrom; } public String getSeedFrom() { return seedFrom; } public String getSequenceFrom() { return sequenceFrom; } } public static final class OtpCredentialMapperBuilder { private String algorithmFrom; private String hashFrom; private String seedFrom; private String sequenceFrom; public OtpCredentialMapperBuilder withAlgorithmFrom(String algorithmFrom) { this.algorithmFrom = algorithmFrom; return this; } public OtpCredentialMapperBuilder withHashFrom(String hashFrom) { this.hashFrom = hashFrom; return this; } public OtpCredentialMapperBuilder withSeedFrom(String seedFrom) { this.seedFrom = seedFrom; return this; } public OtpCredentialMapperBuilder withSequenceFrom(String sequenceFrom) { this.sequenceFrom = sequenceFrom; return this; } public OtpCredentialMapper build() { return new OtpCredentialMapper(this); } } public static final class X509CredentialMapper { private final String digestFrom; private final String digestAlgorithm; private final String certificateFrom; private final String serialNumberFrom; private final String subjectDnFrom; private X509CredentialMapper(X509CredentialMapperBuilder builder) { this.digestFrom = builder.digestFrom; this.digestAlgorithm = builder.digestAlgorithm; this.certificateFrom = builder.certificateFrom; this.serialNumberFrom = builder.serialNumberFrom; this.subjectDnFrom = builder.subjectDnFrom; } public String getDigestFrom() { return digestFrom; } public String getDigestAlgorithm() { return digestAlgorithm; } public String getCertificateFrom() { return certificateFrom; } public String getSerialNumberFrom() { return serialNumberFrom; } public String getSubjectDnFrom() { return subjectDnFrom; } } public static final class X509CredentialMapperBuilder { private String digestFrom; private String digestAlgorithm; private String certificateFrom; private String serialNumberFrom; private String subjectDnFrom; public X509CredentialMapperBuilder withDigestFrom(String digestFrom) { this.digestFrom = digestFrom; return this; } public X509CredentialMapperBuilder withDigestAlgorithm(String digestAlgorithm) { this.digestAlgorithm = digestAlgorithm; return this; } public X509CredentialMapperBuilder withCertificateFrom(String certificateFrom) { this.certificateFrom = certificateFrom; return this; } public X509CredentialMapperBuilder withSerialNumberFrom(String serialNumberFrom) { this.serialNumberFrom = serialNumberFrom; return this; } public X509CredentialMapperBuilder withSubjectDnFrom(String subjectDnFrom) { this.subjectDnFrom = subjectDnFrom; return this; } public X509CredentialMapper build() { return new X509CredentialMapper(this); } } public static final class NewIdentityAttributes { private final String name; private List<String> values; private NewIdentityAttributes(NewIdentityAttributesBuilder builder) { this.name = builder.name; this.values = builder.values; } public String getName() { return name; } public List<String> getValues() { return values; } } public static final class NewIdentityAttributesBuilder { private String name; private List<String> values = new ArrayList<String>(); public NewIdentityAttributesBuilder withName(String name) { this.name = name; return this; } public NewIdentityAttributesBuilder withValues(String... values) { if (values != null) { Collections.addAll(this.values, values); } return this; } public NewIdentityAttributes build() { return new NewIdentityAttributes(this); } } }
26,746
32.184864
141
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/ServletElytronDomainSetup.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.wildfly.test.security.common.elytron.Utils.applyRemoveAllowReload; import static org.wildfly.test.security.common.elytron.Utils.applyUpdate; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.dmr.ModelNode; /** * Utility methods to create/remove simple security domains * * @author <a href="mailto:jkalina@redhat.com">Jan Kalina</a> */ public class ServletElytronDomainSetup implements ServerSetupTask { private static final String SUBSYSTEM_NAME = "elytron"; private static final String DEFAULT_SECURITY_DOMAIN_NAME = "elytron-tests"; private PathAddress httpAuthenticationAddress; private PathAddress undertowDomainAddress; private final String securityDomainName; private final boolean useAuthenticationFactory; public ServletElytronDomainSetup() { this(DEFAULT_SECURITY_DOMAIN_NAME); } public ServletElytronDomainSetup(final String securityDomainName) { this(securityDomainName, true); } public ServletElytronDomainSetup(final String securityDomainName, final boolean useAuthenticationFactory) { this.securityDomainName = securityDomainName; this.useAuthenticationFactory = useAuthenticationFactory; } protected String getSecurityDomainName() { return securityDomainName; } protected String getUndertowDomainName() { return getSecurityDomainName(); } protected String getHttpAuthenticationName() { return getSecurityDomainName(); } protected String getDeploymentSecurityDomain() { return getSecurityDomainName(); } protected boolean useAuthenticationFactory() { return useAuthenticationFactory; } @Override public void setup(final ManagementClient managementClient, final String containerId) throws Exception { httpAuthenticationAddress = PathAddress.pathAddress() .append(SUBSYSTEM, SUBSYSTEM_NAME) .append("http-authentication-factory", getHttpAuthenticationName()); undertowDomainAddress = PathAddress.pathAddress() .append(SUBSYSTEM, "undertow") .append("application-security-domain", getUndertowDomainName()); final ModelNode compositeOp = new ModelNode(); compositeOp.get(OP).set(ModelDescriptionConstants.COMPOSITE); compositeOp.get(OP_ADDR).setEmptyList(); ModelNode steps = compositeOp.get(STEPS); if (useAuthenticationFactory()) { ModelNode addHttpAuthentication = Util.createAddOperation(httpAuthenticationAddress); addHttpAuthentication.get("security-domain").set(getSecurityDomainName()); addHttpAuthentication.get("http-server-mechanism-factory").set("global"); addHttpAuthentication.get("mechanism-configurations").get(0).get("mechanism-name").set("BASIC"); addHttpAuthentication.get("mechanism-configurations").get(0).get("mechanism-realm-configurations").get(0).get("realm-name").set("TestingRealm"); steps.add(addHttpAuthentication); } ModelNode addUndertowDomain = Util.createAddOperation(undertowDomainAddress); if (useAuthenticationFactory()) { addUndertowDomain.get("http-authentication-factory").set(getHttpAuthenticationName()); } else { addUndertowDomain.get("security-domain").set(getSecurityDomainName()); } steps.add(addUndertowDomain); applyUpdate(managementClient.getControllerClient(), compositeOp, false); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) { applyRemoveAllowReload(managementClient.getControllerClient(), undertowDomainAddress, false); if (useAuthenticationFactory()) { applyRemoveAllowReload(managementClient.getControllerClient(), httpAuthenticationAddress, false); } } }
5,574
40.604478
156
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/CliFragment.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Represents common piece in CLI commands, which can be shared across types. * * @author Josef Cacek */ public interface CliFragment { /** * Generates part of CLI string which uses configuration for this fragment. * * @return part of CLI command */ String asString(); }
1,382
34.461538
79
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/Module.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * A {@link ConfigurableElement} to add a custom module. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class Module extends AbstractConfigurableElement { private final List<String> resources; private final List<String> dependencies; Module(Builder builder) { super(builder); this.resources = builder.resources; this.dependencies = builder.dependencies; } @Override public void create(CLIWrapper cli) throws Exception { StringBuilder moduleAddCommand = new StringBuilder("module add --name=") .append(name); if (resources.size() > 0) { moduleAddCommand.append(" --resources="); Iterator<String> resourcesIterator = resources.iterator(); moduleAddCommand.append(resourcesIterator.next()); while (resourcesIterator.hasNext()) { moduleAddCommand.append(",").append(resourcesIterator.next()); } } if (dependencies.size() > 0) { moduleAddCommand.append(" --dependencies="); Iterator<String> dependenciesIterator = dependencies.iterator(); moduleAddCommand.append(dependenciesIterator.next()); while (dependenciesIterator.hasNext()) { moduleAddCommand.append(",").append(dependenciesIterator.next()); } } cli.sendLine(moduleAddCommand.toString(), true); } @Override public void remove(CLIWrapper cli) throws Exception { String moduleRemove = "module remove --name=" + name; cli.sendLine(moduleRemove, true); } /** * Create a new Builder instance. * * @return a new Builder instance. */ public static Builder builder() { return new Builder(); } /** * Builder to build a module registration. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private List<String> resources = new ArrayList<>(); private List<String> dependencies = new ArrayList<>(); /** * Add a resource to be referenced by the module. * * @param resource a resource to be referenced by the module. * @return this {@link Builder} to allow method chaining. */ public Builder withResource(final String resource) { resources.add(resource); return this; } /** * Add a dependency to be referenced by the module. * * @param dependency a dependency to be referenced by the module. * @return this {@link Builder} to allow method chaining. */ public Builder withDependency(final String dependency) { dependencies.add(dependency); return this; } /** * Build an instance of {@link Module} * * @return an instance of {@link Module} */ public Module build() { return new Module(this); } @Override protected Builder self() { return this; } } }
4,384
30.775362
92
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SaslFilter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Object which holds sasl filter configuration. * * @author Josef Cacek */ public class SaslFilter { private final String predefinedFilter; private final String patternFilter; private final Boolean enabling; private SaslFilter(Builder builder) { this.predefinedFilter = builder.predefinedFilter; this.patternFilter = builder.patternFilter; this.enabling = builder.enabling; } /** * Creates builder to build {@link SaslFilter}. * @return created builder */ public static Builder builder() { return new Builder(); } public String getPredefinedFilter() { return predefinedFilter; } public String getPatternFilter() { return patternFilter; } public Boolean isEnabling() { return enabling; } /** * Builder to build {@link SaslFilter}. */ public static final class Builder { private String predefinedFilter; private String patternFilter; private Boolean enabling; private Builder() { } public Builder withPredefinedFilter(String predefinedFilter) { this.predefinedFilter = predefinedFilter; return this; } public Builder withPatternFilter(String patternFilter) { this.patternFilter = patternFilter; return this; } public Builder withEnabling(Boolean enabling) { this.enabling = enabling; return this; } public SaslFilter build() { return new SaslFilter(this); } } }
2,694
27.368421
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/UndertowSslContext.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; import org.jboss.as.test.integration.management.util.CLIWrapper; /** * Updates Undertow https-listener of the defaul-server to use given (Elytron server-ssl-context) SSL context * instead of SSL context from legacy security-realm. * * @author Ondrej Kotek */ public class UndertowSslContext extends AbstractConfigurableElement { private String httpsListener; private UndertowSslContext(Builder builder) { super(builder); this.httpsListener = builder.httpsListener; } @Override public void create(CLIWrapper cli) throws Exception { cli.sendLine("batch"); cli.sendLine(String.format("/subsystem=undertow/server=default-server/https-listener=%s:write-attribute" + "(name=ssl-context,value=%s)", httpsListener, name)); cli.sendLine("run-batch"); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine("batch"); cli.sendLine(String.format("/subsystem=undertow/server=default-server/https-listener=%s:write-attribute" + "(name=ssl-context,value=%s)", httpsListener, "applicationSSC")); cli.sendLine("run-batch"); } /** * Creates builder to build {@link UndertowSslContext}. The name attribute refers to ssl-context capability name. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link UndertowSslContext}. The name attribute refers to ssl-context capability name. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String httpsListener = "https"; private Builder() { } public Builder withHttpsListener(String httpsListener) { this.httpsListener = httpsListener; return this; } public UndertowSslContext build() { return new UndertowSslContext(this); } @Override protected Builder self() { return this; } } }
3,153
34.044444
117
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/SecurityRealm.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.elytron; /** * Interface representing Elytron Security realm and resources related to it. * * @author Josef Cacek */ public interface SecurityRealm extends ConfigurableElement { }
1,251
36.939394
77
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/elytron/servlet/AttributePrintingServlet.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed 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.wildfly.test.security.common.elytron.servlet; import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.authz.Attributes; import org.wildfly.security.authz.Attributes.Entry; /** * An AttributePrintingServlet returns all attributes in a properties format in the response. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @WebServlet(urlPatterns = { AttributePrintingServlet.SERVLET_PATH }) @ServletSecurity(@HttpConstraint(rolesAllowed = { "*" })) public class AttributePrintingServlet extends HttpServlet { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The default servlet path (used in {@link WebServlet} annotation). */ public static final String SERVLET_PATH = "/printAttributes"; /** * Writes plain-text response with all of the current identities attributes. * */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); final PrintWriter writer = resp.getWriter(); SecurityDomain securityDomain = SecurityDomain.getCurrent(); SecurityIdentity securityIdentity = securityDomain.getCurrentSecurityIdentity(); Attributes attributes = securityIdentity.getAttributes(); for (Entry currentAttribute : attributes.entries()) { writer.print(currentAttribute.getKey()); writer.print("="); for (int i=0; i<currentAttribute.size(); i++) { writer.print(currentAttribute.get(i)); if (i < currentAttribute.size()) { writer.print(","); } } writer.println(); } writer.close(); } }
2,860
36.155844
113
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/other/SimpleSocketBinding.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.other; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import java.util.ArrayList; import java.util.List; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; import org.wildfly.test.security.common.elytron.AbstractConfigurableElement; /** * Socket binding configuration. The socketBindingGroup has to exist - if this attribute is not provided, then it defaults to * "standard-sockets" value. * * @author Josef Cacek */ public class SimpleSocketBinding extends AbstractConfigurableElement { private final String socketBindingGroup; private final List<ClientMapping> clientMappings; private final Boolean fixedPort; private final String interfaceName; private final String multicastAddress; private final Integer multicastPort; private final Integer port; private SimpleSocketBinding(Builder builder) { super(builder); this.socketBindingGroup = builder.socketBindingGroup != null ? builder.socketBindingGroup : "standard-sockets"; this.clientMappings = new ArrayList<>(builder.clientMappings); this.fixedPort = builder.fixedPort; this.interfaceName = builder.interfaceName; this.multicastAddress = builder.multicastAddress; this.multicastPort = builder.multicastPort; this.port = builder.port; } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode op = Util.createAddOperation( PathAddress.pathAddress().append("socket-binding-group", socketBindingGroup).append("socket-binding", name)); if (!clientMappings.isEmpty()) { ModelNode mappings = op.get("client-mappings"); for (ClientMapping mapping : clientMappings) { mappings.add(mapping.toModelNode()); } } setIfNotNull(op, "fixed-port", fixedPort); setIfNotNull(op, "interface", interfaceName); setIfNotNull(op, "multicast-address", multicastAddress); setIfNotNull(op, "multicast-port", multicastPort); setIfNotNull(op, "port", port); Utils.applyUpdate(op, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(Util.createRemoveOperation( PathAddress.pathAddress().append("socket-binding-group", socketBindingGroup).append("socket-binding", name)), client); } /** * Creates builder to build {@link SimpleSocketBinding}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleSocketBinding}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String socketBindingGroup; private List<ClientMapping> clientMappings = new ArrayList<>(); private Boolean fixedPort; private String interfaceName; private String multicastAddress; private Integer multicastPort; private Integer port; private Builder() { } public Builder withSocketBindingGroup(String socketBindingGroup) { this.socketBindingGroup = socketBindingGroup; return this; } public Builder addClientMapping(ClientMapping clientMapping) { this.clientMappings.add(clientMapping); return this; } public Builder withFixedPort(Boolean fixedPort) { this.fixedPort = fixedPort; return this; } public Builder withInterfaceName(String interfaceName) { this.interfaceName = interfaceName; return this; } public Builder withMulticastAddress(String multicastAddress) { this.multicastAddress = multicastAddress; return this; } public Builder withMulticastPort(Integer multicastPort) { this.multicastPort = multicastPort; return this; } public Builder withPort(Integer port) { this.port = port; return this; } public SimpleSocketBinding build() { return new SimpleSocketBinding(this); } @Override protected Builder self() { return this; } } }
5,735
34.627329
125
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/other/SimpleRemotingConnector.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.other; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; import org.wildfly.test.security.common.elytron.AbstractConfigurableElement; /** * Configuration for /subsystem=remoting/connector=*. * * @author Josef Cacek */ public class SimpleRemotingConnector extends AbstractConfigurableElement { private final String authenticationProvider; private final String saslAuthenticationFactory; private final String saslProtocol; private final String securityRealm; private final String serverName; private final String socketBinding; private final String sslContext; private SimpleRemotingConnector(Builder builder) { super(builder); this.authenticationProvider = builder.authenticationProvider; this.saslAuthenticationFactory = builder.saslAuthenticationFactory; this.saslProtocol = builder.saslProtocol; this.securityRealm = builder.securityRealm; this.serverName = builder.serverName; this.socketBinding = builder.socketBinding; this.sslContext = builder.sslContext; } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode op = Util .createAddOperation(PathAddress.pathAddress().append("subsystem", "remoting").append("connector", name)); setIfNotNull(op, "authentication-provider", authenticationProvider); setIfNotNull(op, "sasl-authentication-factory", saslAuthenticationFactory); setIfNotNull(op, "sasl-protocol", saslProtocol); setIfNotNull(op, "security-realm", securityRealm); setIfNotNull(op, "server-name", serverName); setIfNotNull(op, "socket-binding", socketBinding); setIfNotNull(op, "ssl-context", sslContext); Utils.applyUpdate(op, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate( Util.createRemoveOperation(PathAddress.pathAddress().append("subsystem", "remoting").append("connector", name)), client); } /** * Creates builder to build {@link SimpleRemotingConnector}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleRemotingConnector}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String authenticationProvider; private String saslAuthenticationFactory; private String saslProtocol; private String securityRealm; private String serverName; private String socketBinding; private String sslContext; private Builder() { } public Builder withAuthenticationProvider(String authenticationProvider) { this.authenticationProvider = authenticationProvider; return this; } public Builder withSaslAuthenticationFactory(String saslAuthenticationFactory) { this.saslAuthenticationFactory = saslAuthenticationFactory; return this; } public Builder withSaslProtocol(String saslProtocol) { this.saslProtocol = saslProtocol; return this; } public Builder withSecurityRealm(String securityRealm) { this.securityRealm = securityRealm; return this; } public Builder withServerName(String serverName) { this.serverName = serverName; return this; } public Builder withSocketBinding(String socketBinding) { this.socketBinding = socketBinding; return this; } public Builder withSslContext(String sslContext) { this.sslContext = sslContext; return this; } public SimpleRemotingConnector build() { return new SimpleRemotingConnector(this); } @Override protected Builder self() { return this; } } }
5,501
35.197368
128
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/other/ClientMapping.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.other; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import java.util.Objects; import org.jboss.dmr.ModelNode; /** * Single item represantation of client-mappings list attribute in socket-binding configuration. * * @author Josef Cacek */ public class ClientMapping { private final String sourceNetwork; private final String destinationAddress; private final Integer destinationPort; private ClientMapping(Builder builder) { this.sourceNetwork = builder.sourceNetwork; this.destinationAddress = Objects.requireNonNull(builder.destinationAddress, "Destination address has to be provided"); this.destinationPort = builder.destinationPort; } public String getSourceNetwork() { return sourceNetwork; } public String getDestinationAddress() { return destinationAddress; } public Integer getDestinationPort() { return destinationPort; } public ModelNode toModelNode() { final ModelNode node= new ModelNode(); setIfNotNull(node, "source-network", sourceNetwork); setIfNotNull(node, "destination-address", destinationAddress); setIfNotNull(node, "destination-port", destinationPort); return node; } /** * Creates builder to build {@link ClientMapping}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link ClientMapping}. */ public static final class Builder { private String sourceNetwork; private String destinationAddress; private Integer destinationPort; private Builder() { } public Builder withSourceNetwork(String sourceNetwork) { this.sourceNetwork = sourceNetwork; return this; } public Builder withDestinationAddress(String destinationAddress) { this.destinationAddress = destinationAddress; return this; } public Builder withDestinationPort(Integer destinationPort) { this.destinationPort = destinationPort; return this; } public ClientMapping build() { return new ClientMapping(this); } } }
3,366
29.889908
127
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/other/KeyStoreUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.other; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.KeyPair; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; /** * Common methods for keystore generation. * * @author Jan Stourac */ public final class KeyStoreUtils { /** * Generates keystore of JKS type with specified key and cert entries. Thus using this method one can create * both keystore and truststore. * * @param keys array of key-pair entries * @param trustCerts array of trusted certificates entries * @param keystorePassword keystore password * @return generated keystore instance with given entries as a content * @throws KeyStoreException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws IOException */ public static KeyStore generateKeystore(KeyEntry[] keys, CertEntry[] trustCerts, String keystorePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { return generateKeystore(KeyStoreType.JKS, keys, trustCerts, keystorePassword); } /** * Generates keystore of given type with specified key and cert entries. Thus using this method one can create * both keystore and truststore. * * @param keyStoreType type of keystore to be created * @param keys array of key-pair entries * @param trustCerts array of trusted certificates entries * @param keystorePassword keystore password * @return generated keystore instance with given entries as a content * @throws KeyStoreException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws IOException */ public static KeyStore generateKeystore(KeyStoreType keyStoreType, KeyEntry[] keys, CertEntry[] trustCerts, String keystorePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { final KeyStore keystore = KeyStore.getInstance(keyStoreType.toString()); keystore.load(null, null); if (keys != null) { for (KeyEntry key : keys) { keystore.setKeyEntry(key.name, key.keyPair.getPrivate(), keystorePassword.toCharArray(), key .certificates); } } if (trustCerts != null) { for (CertEntry cert : trustCerts) { keystore.setCertificateEntry(cert.name, cert.certificate); } } return keystore; } /** * Saves given keystore on the filesystem. * * @param keyStore keystore to be saved * @param keystorePassword password for keystore * @param keystoreFile destination keystore file on the filesystem * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws KeyStoreException */ public static void saveKeystore(KeyStore keyStore, String keystorePassword, File keystoreFile) throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException { saveKeystore(keyStore, keystorePassword, keystoreFile.getAbsolutePath()); } /** * Saves given keystore on the filesystem. * * @param keyStore keystore to be saved * @param keystorePassword password for keystore * @param keystoreFile destination keystore file on the filesystem * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws KeyStoreException */ public static void saveKeystore(KeyStore keyStore, String keystorePassword, String keystoreFile) throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException { if (keystoreFile == null) { throw new RuntimeException("There has to be defined path to generated keystore file!"); } final OutputStream ksOut = new FileOutputStream(keystoreFile); keyStore.store(ksOut, keystorePassword.toCharArray()); ksOut.close(); } public static enum KeyStoreType { JKS, PKCS12 } public static class KeyEntry { private String name; private KeyPair keyPair; private Certificate[] certificates; public KeyEntry(String name, KeyPair keyPair, Certificate certificate) { this.name = name; this.keyPair = keyPair; this.certificates = new Certificate[]{certificate}; } public KeyEntry(String name, KeyPair keyPair, Certificate[] certificates) { this.name = name; this.keyPair = keyPair; this.certificates = certificates; } } public static class CertEntry { private String name; private Certificate certificate; public CertEntry(String name, Certificate certificate) { this.name = name; this.certificate = certificate; } } }
6,311
37.723926
118
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/other/KeyUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.other; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.time.ZonedDateTime; import javax.security.auth.x500.X500Principal; import org.wildfly.security.x500.cert.X509CertificateBuilder; /** * Common methods for key-pair and X509 certificates generation. * * @author Jan Stourac */ public final class KeyUtils { private static final String SIGNATURE_ALGORITHM = "SHA256withRSA"; // One year in seconds private static final long DEFAULT_CERT_VALIDITY = 365L * 24L * 60L * 60L; private static final String DEFAULT_KEY_ALGORITHM = "RSA"; private static final int DEFAULT_KEY_SIZE = 2048; /** * Generates key-pair with {@link KeyUtils#DEFAULT_KEY_ALGORITHM} algorithm and {@link KeyUtils#DEFAULT_KEY_SIZE} * key size. * * @return generated key-pair * @throws NoSuchAlgorithmException */ public static KeyPair generateKeyPair() throws NoSuchAlgorithmException { return generateKeyPair(DEFAULT_KEY_ALGORITHM, DEFAULT_KEY_SIZE); } /** * Generates key-pair with given algorithm and key size. * * @param algorithm * @param keySize * @return generated key-pair * @throws NoSuchAlgorithmException */ public static KeyPair generateKeyPair(String algorithm, int keySize) throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm); keyPairGenerator.initialize(keySize); return keyPairGenerator.generateKeyPair(); } /** * Generates a self-signed certificate using {@link KeyUtils#SIGNATURE_ALGORITHM}. The certificate * will use a distinguished name of the form {@code CN=name} and will be valid for 1 year. * * @param name common name for the certificate * @param keyPair public and private keys * @return generated certificate * @throws CertificateException */ public static X509Certificate generateX509Certificate(String name, KeyPair keyPair) throws CertificateException { return generateX509Certificate(name, keyPair, DEFAULT_CERT_VALIDITY, SIGNATURE_ALGORITHM); } /** * Generates self-signed certificate for provided key-pair with given validity time and signature algorithm. * * @param name common name for the certificate * @param keyPair public and private keys * @param certValidity how long the certificate should be valid to the future (number of seconds) * @param signatureAlgorithm signature algorithm * @return generated certificate * @throws CertificateException */ public static X509Certificate generateX509Certificate(String name, KeyPair keyPair, long certValidity, String signatureAlgorithm) throws CertificateException { ZonedDateTime from = ZonedDateTime.now(); ZonedDateTime to = ZonedDateTime.now().plusSeconds(certValidity); BigInteger serialNumber = new BigInteger(64, new SecureRandom()); X500Principal owner = new X500Principal("CN=" + name); X509CertificateBuilder certificateBuilder = new X509CertificateBuilder(); return certificateBuilder.setIssuerDn(owner).setSubjectDn(owner).setNotValidBefore(from).setNotValidAfter(to) .setSerialNumber(serialNumber).setPublicKey(keyPair.getPublic()).setSignatureAlgorithmName (signatureAlgorithm).setSigningKey(keyPair.getPrivate()).build(); } }
4,753
42.218182
117
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/common/other/MessagingElytronDomainConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.common.other; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; import org.wildfly.test.security.common.elytron.ConfigurableElement; /** * Elytron configurator for elytron-domain attribute in a messaging subsystem ( * {@code /subsystem=messaging-activemq/server=default:write-attribute(name=elytron-domain, value=...)}). If the server name is * not provided "default" value is used. * * @author Josef Cacek */ public class MessagingElytronDomainConfigurator implements ConfigurableElement { private final String server; private final String elytronDomain; private final PathAddress messagingServerAddress; private String originalDomain; private MessagingElytronDomainConfigurator(Builder builder) { this.server = builder.server != null ? builder.server : "default"; this.elytronDomain = builder.elytronDomain; this.messagingServerAddress = PathAddress.pathAddress().append("subsystem", "messaging-activemq").append("server", server); } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { originalDomain = setElytronDomain(client, elytronDomain); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { setElytronDomain(client, originalDomain); originalDomain = null; } @Override public String getName() { return "/subsystem=messaging-activemq/server=" + server + " elytronDomain=" + elytronDomain; } private String setElytronDomain(ModelControllerClient client, String domainToSet) throws Exception { String origDomainValue = null; ModelNode op = Util.createEmptyOperation("read-attribute", messagingServerAddress); op.get("name").set("elytron-domain"); ModelNode result = client.execute(op); boolean isConfigured = Operations.isSuccessfulOutcome(result); op = null; if (isConfigured) { result = Operations.readResult(result); origDomainValue = result.isDefined() ? result.asString() : null; } op = Util.createEmptyOperation("write-attribute", messagingServerAddress); op.get("name").set("elytron-domain"); op.get("value").set(domainToSet); Utils.applyUpdate(op, client); return origDomainValue; } /** * Creates builder to build {@link MessagingElytronDomainConfigurator}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link MessagingElytronDomainConfigurator}. */ public static final class Builder { private String server; private String elytronDomain; private Builder() { } public Builder withServer(String server) { this.server = server; return this; } public Builder withElytronDomain(String elytronDomain) { this.elytronDomain = elytronDomain; return this; } public MessagingElytronDomainConfigurator build() { return new MessagingElytronDomainConfigurator(this); } } }
4,599
35.8
127
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/servlets/CheckIdentityPermissionServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.servlets; import static jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; import java.io.IOException; import java.io.PrintWriter; import java.security.Permission; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.evidence.PasswordGuessEvidence; /** * Servlet which checks if given identity has given permission in current Elytron security domain. If the {@value #PARAM_USER} * request parameter is not provided then an anonymous identity is used, otherwise the identity is retrieved by calling * {@link SecurityDomain#authenticate(String, org.wildfly.security.evidence.Evidence)} method * with {@value #PARAM_PASSWORD} request parameter used as the Evidence. * <p> * The checked permission is specified by request parameters {@value #PARAM_CLASS}, {@value #PARAM_TARGET} and * {@value #PARAM_ACTION}. * </p> * <p> * Response body in normal cases contains just "true" or "false" String. If authentication to security domain fails, then status * code {@link HttpServletResponse#SC_FORBIDDEN} is used for the response. If the check permission class parameter is missing * then status code {@link HttpServletResponse#SC_BAD_REQUEST} is used for the response. * </p> * * @author Josef Cacek */ @WebServlet(CheckIdentityPermissionServlet.SERVLET_PATH) public class CheckIdentityPermissionServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/checkIdentityPermission"; public static final String PARAM_USER = "user"; public static final String PARAM_PASSWORD = "password"; public static final String PARAM_CLASS = "class"; public static final String PARAM_TARGET = "target"; public static final String PARAM_ACTION = "action"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); SecurityIdentity si = null; final String user = req.getParameter(PARAM_USER); if (user != null) { final String password = req.getParameter(PARAM_PASSWORD); try { si = SecurityDomain.getCurrent().authenticate(user, new PasswordGuessEvidence(password.toCharArray())); } catch (Exception e) { e.printStackTrace(); resp.sendError(SC_FORBIDDEN, e.getMessage()); return; } } else { si = SecurityDomain.getCurrent().getCurrentSecurityIdentity(); } String className = req.getParameter(PARAM_CLASS); if (className == null) { resp.sendError(SC_BAD_REQUEST, "Parameter class has to be provided"); return; } String target = req.getParameter(PARAM_TARGET); String action = req.getParameter(PARAM_ACTION); Permission perm = null; try { if (target == null) { perm = (Permission) Class.forName(className).newInstance(); } else if (action == null) { perm = (Permission) Class.forName(className).getConstructor(String.class).newInstance(target); } else { perm = (Permission) Class.forName(className).getConstructor(String.class, String.class).newInstance(target, action); } } catch (Exception e) { throw new ServletException("Unable to create permission instance", e); } final PrintWriter writer = resp.getWriter(); writer.print(si.implies(perm)); writer.close(); } }
5,247
41.666667
128
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/servlets/ReadCredentialServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.servlets; import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jboss.as.server.CurrentServiceContainer; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceRegistry; import org.wildfly.security.credential.PasswordCredential; import org.wildfly.security.credential.store.CredentialStore; import org.wildfly.security.credential.store.CredentialStoreException; import org.wildfly.security.password.Password; import org.wildfly.security.password.interfaces.ClearPassword; /** * This servlet allows to list credential stores, aliases in them and also the secret values for the aliases. <br/> * It has optional request parameters: * <ul> * <li>{@value #PARAM_CREDENTIAL_STORE} - for configuring name of credential store</li> * <li>{@value #PARAM_ALIAS} - for configuring alias in credential store</li> * <li>{@value #PARAM_SEPARATOR} - for configuring value separator when list of values is returned (default separator is the * line break)</li> * </ul> * * <p> * If request parameter "{@value #PARAM_CREDENTIAL_STORE}" is not provided, list of credential store names is returned. * </p> * <p> * If request parameter "{@value #PARAM_CREDENTIAL_STORE}" is provided and "{@value #PARAM_CREDENTIAL_STORE}" is not provided , * list of aliases in the given credential store names is returned. * </p> * <p> * If both request parameters ("{@value #PARAM_CREDENTIAL_STORE}", "{@value #PARAM_CREDENTIAL_STORE}") are provided , secret * value for given alias is returned. * </p> * * <p> * If name parameter is provided but given name (store or alias) is not found, then {@value HttpServletResponse#SC_NOT_FOUND} is * returned as reponse status code. * </p> * * * @author Josef Cacek */ @WebServlet(urlPatterns = { ReadCredentialServlet.SERVLET_PATH }) public class ReadCredentialServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/readCredential"; public static final String PARAM_CREDENTIAL_STORE = "credentialStore"; public static final String PARAM_ALIAS = "alias"; public static final String PARAM_SEPARATOR = "separator"; public static final String PARAM_SEPARATOR_DEFAULT = "\n"; private static final ServiceName SERVICE_NAME_CRED_STORE = ServiceName.of("org", "wildfly", "security", "credential-store"); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); final PrintWriter writer = resp.getWriter(); final String credentialStore = req.getParameter(PARAM_CREDENTIAL_STORE); final String alias = req.getParameter(PARAM_ALIAS); String separator = req.getParameter(PARAM_SEPARATOR); if (separator == null) { separator = PARAM_SEPARATOR_DEFAULT; } ServiceRegistry registry = CurrentServiceContainer.getServiceContainer(); if (credentialStore == null || credentialStore.length() == 0) { for (ServiceName name : registry.getServiceNames()) { if (SERVICE_NAME_CRED_STORE.equals(name.getParent())) { writer.print(name.getSimpleName()); writer.print(separator); } } return; } ServiceController<?> credStoreService = registry.getService(ServiceName.of(SERVICE_NAME_CRED_STORE, credentialStore)); if (credStoreService == null) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); writer.print(credentialStore + " not found"); return; } CredentialStore cs = (CredentialStore) credStoreService.getValue(); if (alias == null || alias.length() == 0) { try { for (String csAlias : cs.getAliases()) { writer.print(csAlias); writer.print(separator); } } catch (UnsupportedOperationException | CredentialStoreException e) { throw new ServletException("Unable to list aliases", e); } return; } String clearPassword = null; try { if (cs.exists(alias, PasswordCredential.class)) { Password password = cs.retrieve(alias, PasswordCredential.class).getPassword(); if (password instanceof ClearPassword) { clearPassword = new String(((ClearPassword) password).getPassword()); } } } catch (CredentialStoreException | IllegalStateException e) { throw new ServletException("Unable to retrieve password from credential store", e); } if (clearPassword == null) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); writer.print(alias + " password not found in " + credentialStore); } else { writer.print(clearPassword); } } }
6,537
40.910256
128
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/security/servlets/SecuredPrincipalPrintingServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.security.servlets; import java.io.IOException; import java.io.PrintWriter; import java.security.Principal; import jakarta.annotation.security.DeclareRoles; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * A secured servlet that gets request assigned principal ({@link HttpServletRequest#getUserPrincipal()}) and prints its name. * * @author Josef Cacek */ @DeclareRoles({ SecuredPrincipalPrintingServlet.ALLOWED_ROLE }) @ServletSecurity(@HttpConstraint(rolesAllowed = { SecuredPrincipalPrintingServlet.ALLOWED_ROLE })) @WebServlet(SecuredPrincipalPrintingServlet.SERVLET_PATH) public class SecuredPrincipalPrintingServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/principal"; public static final String ALLOWED_ROLE = "JBossAdmin"; /** * Writes principal name. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); Principal userPrincipal = req.getUserPrincipal(); if (userPrincipal != null) { final PrintWriter writer = resp.getWriter(); writer.print(userPrincipal.getName()); writer.close(); } } }
2,672
38.895522
126
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/distribution/validation/AbstractValidationUnitTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.distribution.validation; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.BufferedWriter; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.math.BigDecimal; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.jboss.metadata.parser.util.XMLResourceResolver; import org.w3c.dom.Document; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * Date: 23.06.2011 * * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class AbstractValidationUnitTest { private static final String SCHEMAS_LOCATION = "docs/schema"; private static final String JBOSS_DIST_PROP_NAME = "jboss.dist"; private static final String FUTURE_SCHEMA_PROP_NAME = "jboss.test.xml.validation.future.schemas"; private static final Set<String> EXCLUDED_SCHEMA_FILES = new HashSet<>(); private static final Set<String> FUTURE_SCHEMA_FILES = new HashSet<>(); private static final Map<String, File> JBOSS_SCHEMAS_MAP = new HashMap<>(); private static final Map<String, File> CURRENT_JBOSS_SCHEMAS_MAP = new HashMap<>(); private static final Source[] SCHEMA_SOURCES; private static final Map<String, String> NAMESPACE_MAP = new HashMap<>(); private static final Map<String, String> OUTDATED_NAMESPACES = new HashMap<>(); private static final File JBOSS_DIST_DIR; static { // exclude JBoss Jakarta Enterprise Beans specific files which redefine the javaee namespace // triggering the https://issues.apache.org/jira/browse/XERCESJ-1130 bug EXCLUDED_SCHEMA_FILES.add("jboss-ejb3-2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb3-2_1.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb3-spec-2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb3-spec-2_1.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb3-spec-4_01.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-cache_1_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-cache_2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-container-interceptors_1_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-container-interceptors_2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-delivery-active_1_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-delivery-active_1_1.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-delivery-active_1_2.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-delivery-active_2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-clustering_1_1.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-clustering_2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-iiop_1_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-iiop_1_1.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-iiop_1_2.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-iiop_2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-pool_1_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-pool_2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-resource-adapter-binding_1_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-resource-adapter-binding_2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-security_1_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-security_1_1.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-security_2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-security-role_1_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-security-role_2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-timer-service_2_0.xsd"); EXCLUDED_SCHEMA_FILES.add("jboss-ejb-timer-service_3_0.xsd"); String coreVersion = System.getProperty("version.org.wildfly.core"); if (coreVersion != null) { // We are testing a different version of core than was used in creating our standard configs // See if we are configured to specially handle newer schema versions in that core String excluded = System.getProperty(FUTURE_SCHEMA_PROP_NAME); if (excluded != null) { excluded = excluded.trim(); String[] pairs = excluded.split(","); for (String pair : pairs) { if (pair.length() > 0) { // The format is <core_version>/<schema_file> String[] tuple = pair.split("/"); // We only care about the pair if the <core_version> bit matches the // value of the version.org.wildfly.core system property. This // way if someone sets -Djboss.test.xml.validation.future.schemas // in a CI test setup and then forgets to update the setup when // the relevant core version gets released and integrated, the // setting will no longer be effective and the no longer "future" // xsd will get tested normally. if (tuple.length == 2 && coreVersion.equals(tuple[0])) { FUTURE_SCHEMA_FILES.add(tuple[1]); } } } } } NAMESPACE_MAP.put("http://java.sun.com/xml/ns/javaee/javaee_6.xsd", "schema/javaee_6.xsd"); NAMESPACE_MAP.put("http://www.w3.org/2001/xml.xsd", "schema/xml.xsd"); NAMESPACE_MAP.put("http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd", "schema/ejb-jar_3_1.xsd"); NAMESPACE_MAP.put("http://www.jboss.org/j2ee/schema/jboss-common_7_0.xsd", "jboss-common_7_0.xsd"); String asDir = System.getProperty(JBOSS_DIST_PROP_NAME); if (null == asDir) { JBOSS_DIST_DIR = null; } else { JBOSS_DIST_DIR = new File(asDir); if (!JBOSS_DIST_DIR.exists()) throw new IllegalStateException("Directory set in '" + JBOSS_DIST_PROP_NAME + "' does not exist: " + JBOSS_DIST_DIR.getAbsolutePath()); final File schemaDir = new File(JBOSS_DIST_DIR, SCHEMAS_LOCATION); final File[] xsds = schemaDir.listFiles(new SchemaFilter(EXCLUDED_SCHEMA_FILES.toArray(new String[0]))); for (File xsd : xsds) { JBOSS_SCHEMAS_MAP.put(xsd.getName(), xsd); } Map<String, BigDecimal> mostRecentVersions = new HashMap<>(); Map<String, String> mostRecentNames = new HashMap<>(); Pattern pattern = Pattern.compile("(.*?)_(\\d+)_(\\d+).xsd"); for(Map.Entry<String, File> entry : JBOSS_SCHEMAS_MAP.entrySet()) { if (FUTURE_SCHEMA_FILES.contains(entry.getKey())) { // not "current"; it's future. continue; } final Matcher match = pattern.matcher(entry.getKey()); if(!match.matches()) { continue; } String name = match.group(1); String major = match.group(2); String minor = match.group(3); BigDecimal version = new BigDecimal(major + "." + minor); BigDecimal current = mostRecentVersions.get(name); if(current == null || version.compareTo(current) > 0) { mostRecentVersions.put(name, version); mostRecentNames.put(name, entry.getKey()); } } for (Map.Entry<String, File> entry : JBOSS_SCHEMAS_MAP.entrySet()) { if (FUTURE_SCHEMA_FILES.contains(entry.getKey())) { // not "current" or "outdated"; it's future. continue; } final Matcher match = pattern.matcher(entry.getKey()); if (!match.matches()) { continue; } String name = match.group(1); if (!mostRecentNames.get(name).equals(entry.getKey())) { OUTDATED_NAMESPACES.put(entry.getKey(), mostRecentNames.get(name)); } else { CURRENT_JBOSS_SCHEMAS_MAP.put(entry.getKey(), entry.getValue()); } } } final List<Source> sources = new LinkedList<>(); for (File file : CURRENT_JBOSS_SCHEMAS_MAP.values()) { sources.add(new StreamSource(file)); } SCHEMA_SOURCES = sources.toArray(new Source[0]); } @SuppressWarnings("Convert2Lambda") static final LSResourceResolver DEFAULT_RESOURCE_RESOLVER = new LSResourceResolver() { @Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { final DOMImplementationLS impl; try { impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance().getDOMImplementation("LS"); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new RuntimeException("could not create LS input" ,e); } LSInput input = impl.createLSInput(); final URL url; if (NAMESPACE_MAP.containsKey(systemId)) { url = discoverXsd(NAMESPACE_MAP.get(systemId)); } else { url = discoverXsd(systemId); } try { input.setByteStream(url.openStream()); } catch (IOException e) { throw new RuntimeException(e); } return input; } }; /** * The base directory, e.g. {@literal $user.home/../../build/target/jboss-*}. * <p/> * Executes {@link org.junit.Assert#fail()} if the base directory is null. * * @return the base directory. */ protected static File getBaseDir() { assertNotNull("'" + JBOSS_DIST_PROP_NAME + "' is not set.", JBOSS_DIST_DIR); assertTrue("Directory set in '" + JBOSS_DIST_PROP_NAME + "' does not exist: " + JBOSS_DIST_DIR.getAbsolutePath(), JBOSS_DIST_DIR.exists()); return JBOSS_DIST_DIR; } /** * Attempts to discover the path to the XSD file. * * @param xsdName the xsd file name. * @return the file. */ static URL discoverXsd(final String xsdName) { if (OUTDATED_NAMESPACES.containsKey(xsdName)) { throw new RuntimeException("Default configs are not in line with most recent schemas " + xsdName + " has been superseded by " + OUTDATED_NAMESPACES.get(xsdName)); } final File file = JBOSS_SCHEMAS_MAP.get(xsdName); URL url = null; try { if (file != null) { url = file.toURI().toURL(); } } catch (MalformedURLException e) { throw new IllegalStateException(e); } if (url == null && xsdName != null) { String fileName = xsdName; int index = fileName.lastIndexOf("/"); if(index == -1) { index = fileName.lastIndexOf("\\"); } if(index != -1) { fileName = fileName.substring(index + 1); } // Search final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); url = classLoader.getResource("docs/schema/" + fileName); if (url == null) url = classLoader.getResource("docs/" + fileName); if (url == null) url = classLoader.getResource("schema/" + fileName); if (url == null) url = classLoader.getResource(fileName); if (url == null) { final File schemaDir = new File(JBOSS_DIST_DIR, SCHEMAS_LOCATION); final File schema = new File(schemaDir, fileName); if (schema.exists()) { try { url = schema.toURI().toURL(); } catch (MalformedURLException e) { throw new IllegalStateException(e); } } } } assertNotNull(xsdName + " not found", url); return url; } /** * Simple JBoss XSD filter */ private static class SchemaFilter implements FilenameFilter { private static final Pattern PATTERN = Pattern.compile("(jboss|wildfly)-.*\\.xsd$"); private final String[] exclusions; SchemaFilter(final String[] exclusions) { this.exclusions = exclusions; } @Override public boolean accept(final File dir, final String name) { final boolean accepted = PATTERN.matcher(name).find(); if (accepted) { // check for explicit excluded files for (final String excludedFile : exclusions) { if (excludedFile.equals(name)) { // file is in exclude list, so we don't accept this file return false; } } } return accepted; } } protected static final class ErrorHandlerImpl implements ErrorHandler { private final Path file; ErrorHandlerImpl() { this(null); } ErrorHandlerImpl(final Path file) { this.file = file; } @Override public void error(SAXParseException e) { fail(formatMessage(e)); } @Override public void fatalError(SAXParseException e) { fail(formatMessage(e)); } @Override public void warning(SAXParseException e) { System.out.println(formatMessage(e)); } private String formatMessage(SAXParseException e) { StringBuilder sb = new StringBuilder(); sb.append(e.getLineNumber()).append(':').append(e.getColumnNumber()); if (e.getPublicId() != null) sb.append(" publicId='").append(e.getPublicId()).append('\''); if (e.getSystemId() != null) sb.append(" systemId='").append(e.getSystemId()).append('\''); sb.append(' ').append(e.getLocalizedMessage()); sb.append(" a possible cause may be that a subsystem is not using the most up to date schema."); if (file != null) { try { final List<String> lines = Files.readAllLines(file); final int i = e.getLineNumber() - 1; sb.append(System.lineSeparator()); sb.append("Possible line: ").append(lines.get(i)); } catch (IOException ignore){} } return sb.toString(); } } protected static void jbossXsdsTest() throws Exception { /* The test requires all modules to be loadable. Build a classloader with all modules. */ ClassLoader current = Thread.currentThread().getContextClassLoader(); try (URLClassLoader cl = initClassLoader()) { Thread.currentThread().setContextClassLoader(cl); for (File xsdFile : JBOSS_SCHEMAS_MAP.values()) { validateXsd(xsdFile); } } finally { Thread.currentThread().setContextClassLoader(current); } } private static void validateXsd(final File xsdFile) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(xsdFile); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setErrorHandler(new ErrorHandlerImpl()); schemaFactory.setResourceResolver(new XMLResourceResolver()); Schema schema = schemaFactory.newSchema(getXMLSchemaResource()); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } private static URL getXMLSchemaResource() { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final URL resource = classLoader.getResource("schema/XMLSchema.xsd"); assertNotNull("Can't locate resource schema/XMLSchema.xsd on " + classLoader, resource); return resource; } private static URLClassLoader initClassLoader() throws IOException { String path = System.getProperty("jboss.actual.dist"); Path modules = Paths.get(path, "modules/system/layers/base"); List<URL> urls = new ArrayList<>(); Files.walkFileTree(modules, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.toString().endsWith(".jar")) { urls.add(file.toFile().toURI().toURL()); } return FileVisitResult.CONTINUE; } }); URL[] arr = new URL[urls.size()]; urls.toArray(arr); return new URLClassLoader(arr); } protected void parseXml(String xmlName) throws SAXException, IOException { final File xmlFile = getXmlFile(xmlName); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setErrorHandler(new ErrorHandlerImpl(xmlFile.toPath())); schemaFactory.setResourceResolver(DEFAULT_RESOURCE_RESOLVER); Schema schema = schemaFactory.newSchema(SCHEMA_SOURCES); Validator validator = schema.newValidator(); validator.setErrorHandler(new ErrorHandlerImpl(xmlFile.toPath())); validator.setFeature("http://apache.org/xml/features/validation/schema", true); validator.setResourceResolver(DEFAULT_RESOURCE_RESOLVER); validator.validate(new StreamSource(xmlFile)); //noinspection ResultOfMethodCallIgnored xmlFile.delete(); } private File getXmlFile(String xmlName) throws IOException { // Copy the input file to tmp, replacing system prop expressions on non-string fields // so they don't cause validation failures // TODO we should just pass an IS to Validator final File tmp = File.createTempFile(getClass().getSimpleName(), "xml"); tmp.deleteOnExit(); File target = new File(getBaseDir(), xmlName); try (BufferedWriter writer= Files.newBufferedWriter(tmp.toPath(), StandardCharsets.UTF_8)) { List<String> lines = Files.readAllLines(target.toPath(), StandardCharsets.UTF_8); for (String line : lines) { writer.write(fixExpressions(line)); writer.newLine(); } } return tmp; } private static String fixExpressions(String line) { String result = line.replace("${jboss.management.native.port:9999}", "9999"); result = result.replace("${jboss.management.http.port:9990}", "9990"); result = result.replace("${jboss.management.https.port:9993}", "9993"); result = result.replace("${jboss.domain.primary.protocol:remote}", "remote"); result = result.replace("${jboss.domain.primary.protocol:remote+http}", "remote+http"); result = result.replace("${jboss.domain.primary.port:9999}", "9999"); result = result.replace("${jboss.domain.primary.port:9990}", "9990"); result = result.replace("${jboss.mail.server.host:localhost}", "localhost"); result = result.replace("${jboss.mail.server.port:25}", "25"); result = result.replace("${jboss.messaging.group.port:9876}", "9876"); result = result.replace("${jboss.socket.binding.port-offset:0}", "0"); result = result.replace("${jboss.http.port:8080}", "8080"); result = result.replace("${jboss.https.port:8443}", "8443"); result = result.replace("${jboss.remoting.port:4447}", "4447"); result = result.replace("${jboss.ajp.port:8009}", "8009"); result = result.replace("${jboss.mcmp.port:8090}", "8090"); result = result.replace("${jboss.deployment.scanner.rollback.on.failure:false}", "false"); result = result.replace("${wildfly.datasources.statistics-enabled:${wildfly.statistics-enabled:false}}", "false"); result = result.replace("${wildfly.ejb.statistics-enabled:${wildfly.statistics-enabled:false}}", "false"); result = result.replace("${wildfly.messaging-activemq.statistics-enabled:${wildfly.statistics-enabled:false}}", "false"); result = result.replace("${wildfly.transactions.statistics-enabled:${wildfly.statistics-enabled:false}}", "false"); result = result.replace("${wildfly.undertow.statistics-enabled:${wildfly.statistics-enabled:false}}", "false"); result = result.replace("${wildfly.webservices.statistics-enabled:${wildfly.statistics-enabled:false}}", "false"); result = result.replace("${env.MP_HEALTH_EMPTY_LIVENESS_CHECKS_STATUS:UP}", "UP"); result = result.replace("${env.MP_HEALTH_EMPTY_READINESS_CHECKS_STATUS:UP}", "UP"); result = result.replace("${env.MP_HEALTH_EMPTY_STARTUP_CHECKS_STATUS:UP}", "UP"); result = result.replace("${jboss.messaging.connector.host:localhost}", "localhost"); result = result.replace("${jboss.messaging.connector.port:61616}", "61616"); return result; } }
23,688
45.177388
174
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/undertow/common/TestConstants.java
/* * Copyright 2018 Red Hat, Inc. * * Licensed 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.wildfly.test.undertow.common; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class TestConstants { /** * The Undertow JASPI authentication module class name. */ public static final String JASPI_AUTH_MODULE = "org.wildfly.extension.undertow.security.jaspi.modules.HTTPSchemeServerAuthModule"; }
958
33.25
134
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/undertow/common/UndertowApplicationSecurityDomain.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.undertow.common; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.dmr.ModelNode; import org.wildfly.test.security.common.elytron.AbstractConfigurableElement; import org.wildfly.test.security.common.elytron.ConfigurableElement; /** * A {@link ConfigurableElement} to add an application-security-domain resource to the Undertow subsystem. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class UndertowApplicationSecurityDomain extends AbstractConfigurableElement { private final PathAddress address; private final String securityDomain; private final String httpAuthenticationFactory; private final boolean enableJacc; private final boolean enableJaspi; private final boolean integratedJaspi; UndertowApplicationSecurityDomain(Builder builder) { super(builder); this.address = PathAddress.pathAddress().append("subsystem", "undertow").append("application-security-domain", name); this.securityDomain = builder.securityDomain; this.httpAuthenticationFactory = builder.httpAuthenticationFactory; this.enableJacc = builder.enableJacc; this.enableJaspi = builder.enableJaspi; this.integratedJaspi = builder.integratedJaspi; } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode add = Util.createAddOperation(address); setIfNotNull(add, "security-domain", securityDomain); setIfNotNull(add, "http-authentication-factory", httpAuthenticationFactory); if (enableJacc) { add.get("enable-jacc").set(enableJacc); } add.get("enable-jaspi").set(enableJaspi); add.get("integrated-jaspi").set(integratedJaspi); Utils.applyUpdate(add, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { Utils.applyUpdate(Util.createRemoveOperation(address), client); } /** * Create a new Builder instance. * * @return a new Builder instance. */ public static Builder builder() { return new Builder(); } /** * Builder to build an application-security-domain resource in the Undertow subsystem */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String securityDomain; private String httpAuthenticationFactory; private boolean enableJacc = false; private boolean enableJaspi = true; private boolean integratedJaspi = true; /** * Set the security domain to be mapped from this application-security-domain. * * @param securityDomain the security domain to be mapped from this application-security-domain. * @return this {@link Builder} to allow method chaining. */ public Builder withSecurityDomain(final String securityDomain) { this.securityDomain = securityDomain; return this; } /** * Set the http-authentication-factory to be mapped from this application security-domain. * * @param httpAuthenticationFactory the http-authentication-factory to be mapped from this application security-domain. * @return this {@link Builder} to allow method chaining. */ public Builder httpAuthenticationFactory(final String httpAuthenticationFactory) { this.httpAuthenticationFactory = httpAuthenticationFactory; return this; } /** * Set if Jakarta Authorization should be enabled for this application-security-domain. * * @param enableJacc if Jakarta Authorization should be enabled for this application-security-domain. * @return this {@link Builder} to allow method chaining. */ public Builder withEnableJacc(final boolean enableJacc) { this.enableJacc = enableJacc; return this; } /** * Set if JASPI should be enabled for this application-security-domain. * * @param enableJaspi if JASPI should be enabled for this application-security-domain. * @return this {@link Builder} to allow method chaining. */ public Builder withEnableJaspi(final boolean enableJaspi) { this.enableJaspi = enableJaspi; return this; } /** * Set if JASPI should operate in integrated mode or ad-hoc mode. * * @param integratedJaspi if JASPI should operate in integrated mode or ad-hoc mode. * @return this {@link Builder} to allow method chaining. */ public Builder withIntegratedJaspi(final boolean integratedJaspi) { this.integratedJaspi = integratedJaspi; return this; } /** * Build a new UndertowApplicationSecurityDomain {@link ConfigurableElement} * * @return a new UndertowApplicationSecurityDomain {@link ConfigurableElement} */ public UndertowApplicationSecurityDomain build() { return new UndertowApplicationSecurityDomain(this); } @Override protected Builder self() { return this; } } }
6,724
37.428571
127
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/undertow/common/elytron/HttpsListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.undertow.common.elytron; import org.wildfly.test.security.common.elytron.ConfigurableElement; /** * Interface representing Undertow https-listener. * * @author Jan Stourac */ public interface HttpsListener extends ConfigurableElement { }
1,292
38.181818
70
java
null
wildfly-main/testsuite/shared/src/main/java/org/wildfly/test/undertow/common/elytron/SimpleHttpsListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.undertow.common.elytron; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.wildfly.test.security.common.elytron.AbstractConfigurableElement; /** * Undertow https-listener configuration implementation. * * @author Jan Stourac */ public class SimpleHttpsListener extends AbstractConfigurableElement implements HttpsListener { private final String socketBinding; private final String sslContext; private final String securityRealm; private SimpleHttpsListener(Builder builder) { super(builder); this.socketBinding = builder.socketBinding; this.sslContext = builder.sslContext; this.securityRealm = builder.securityRealm; } @Override public void create(CLIWrapper cli) throws Exception { if (sslContext != null) { // /subsystem=undertow/server=default-server/https-listener=https-test:add(socket-binding=https-test, // ssl-context=sslContext) cli.sendLine(String.format("/subsystem=undertow/server=default-server/https-listener=%s:add" + "(socket-binding=%s,ssl-context=%s)", name, socketBinding, sslContext)); } else { // /subsystem=undertow/server=default-server/https-listener=https-test:add(socket-binding=https-test, // security-realm=secRealm) cli.sendLine(String.format("/subsystem=undertow/server=default-server/https-listener=%s:add" + "(socket-binding=%s,security-realm=%s)", name, socketBinding, securityRealm)); } } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine(String.format("/subsystem=undertow/server=default-server/https-listener=%s:remove()", name)); } /** * Creates builder to build {@link SimpleHttpsListener}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link SimpleHttpsListener}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String socketBinding; private String sslContext; private String securityRealm; private Builder() { } public Builder withSocketBinding(String socketBinding) { this.socketBinding = socketBinding; return this; } public Builder withSslContext(String sslContext) { this.sslContext = sslContext; return this; } public Builder withSecurityRealm(String securityRealm) { this.securityRealm = securityRealm; return this; } public SimpleHttpsListener build() { if (socketBinding == null) { throw new RuntimeException("socket-binding is required when creating https-listener"); } if ((sslContext == null && securityRealm == null) || (sslContext != null && securityRealm != null)) { throw new RuntimeException("exactly one of ssl-context and security-realm must be defined when " + "creating https-listener"); } return new SimpleHttpsListener(this); } @Override protected Builder self() { return this; } } }
4,397
35.957983
114
java
null
wildfly-main/testsuite/scripts/src/test/java/org/wildfly/test/common/ServerConfigurator.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed 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.wildfly.test.common; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class ServerConfigurator { public static final Set<Path> PATHS = new LinkedHashSet<>(16); private static final AtomicBoolean CONFIGURED = new AtomicBoolean(false); public static void configure() throws IOException, InterruptedException { if (CONFIGURED.compareAndSet(false, true)) { // Always add the default path PATHS.add(ServerHelper.JBOSS_HOME); final String serverName = System.getProperty("server.output.dir.prefix"); // Create special characters in paths to test with assuming the -Dserver.name was not used if (serverName == null || serverName.isEmpty()) { PATHS.add(copy("wildfly core")); PATHS.add(copy("wildfly (core)")); } } } private static Path copy(final String targetName) { final Path source = ServerHelper.JBOSS_HOME; try { final Path target = source.getParent().resolve(targetName); deleteDirectory(target); copyDirectory(source, target); return target; } catch (IOException e) { throw new UncheckedIOException(e); } } private static void copyDirectory(final Path source, final Path target) throws IOException { Files.walkFileTree(source, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { final Path targetDir = target.resolve(source.relativize(dir)); Files.copy(dir, targetDir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { final Path targetFile = target.resolve(source.relativize(file)); Files.copy(file, targetFile); return FileVisitResult.CONTINUE; } }); } private static void deleteDirectory(final Path dir) throws IOException { if (Files.exists(dir) && Files.isDirectory(dir)) { Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } } }
3,841
37.42
122
java
null
wildfly-main/testsuite/scripts/src/test/java/org/wildfly/test/common/ServerHelper.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed 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.wildfly.test.common; import static org.jboss.as.controller.client.helpers.ClientConstants.CONTROLLER_PROCESS_STATE_STARTING; import static org.jboss.as.controller.client.helpers.ClientConstants.CONTROLLER_PROCESS_STATE_STOPPING; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.BooleanSupplier; import java.util.function.Supplier; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.OperationMessageHandler; import org.jboss.as.controller.client.OperationResponse; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.client.helpers.domain.DomainClient; import org.jboss.as.controller.client.helpers.domain.ServerIdentity; import org.jboss.as.controller.client.helpers.domain.ServerStatus; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.dmr.ModelNode; import org.junit.Assert; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class ServerHelper { public static final ModelNode EMPTY_ADDRESS = new ModelNode().setEmptyList(); public static final int TIMEOUT = TimeoutUtil.adjust(Integer.parseInt(System.getProperty("jboss.test.start.timeout", "15"))); public static final Path JBOSS_HOME; public static final String[] DEFAULT_SERVER_JAVA_OPTS = { "-Djboss.management.http.port=" + TestSuiteEnvironment.getServerPort(), "-Djboss.bind.address.management=" + TestSuiteEnvironment.getServerAddress(), }; static { EMPTY_ADDRESS.protect(); final String jbossHome = System.getProperty("jboss.home"); if (isNullOrEmpty(jbossHome)) { throw new RuntimeException("Failed to configure environment. No jboss.home system property or JBOSS_HOME " + "environment variable set."); } JBOSS_HOME = Paths.get(jbossHome).toAbsolutePath(); } /** * Shuts down a standalone server. * * @throws IOException if an error occurs communicating with the server */ public static void shutdownStandalone(final ModelControllerClient client) throws IOException { final ModelNode op = Operations.createOperation("shutdown"); op.get("timeout").set(0); final ModelNode response = client.execute(op); if (!Operations.isSuccessfulOutcome(response)) { Assert.fail("Failed to shutdown server: " + Operations.getFailureDescription(response).asString()); } } /** * Checks to see if a standalone server is running. * * @param client the client used to communicate with the server * * @return {@code true} if the server is running, otherwise {@code false} */ public static boolean isStandaloneRunning(final ModelControllerClient client) { try { final ModelNode response = client.execute(Operations.createReadAttributeOperation(EMPTY_ADDRESS, "server-state")); if (Operations.isSuccessfulOutcome(response)) { final String state = Operations.readResult(response).asString(); return !CONTROLLER_PROCESS_STATE_STARTING.equals(state) && !CONTROLLER_PROCESS_STATE_STOPPING.equals(state); } } catch (RuntimeException | IOException ignore) { } return false; } /** * Waits the given amount of time in seconds for a standalone server to start. * <p> * If the {@code process} is not {@code null} and a timeout occurs the process will be * {@linkplain Process#destroy() destroyed}. * </p> * * @param process the Java process can be {@code null} if no process is available * * @throws InterruptedException if interrupted while waiting for the server to start * @throws RuntimeException if the process has died */ public static void waitForStandalone(final Process process, final Supplier<String> failureDescription) throws InterruptedException, IOException { try (ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient()) { waitForStart(process, failureDescription, () -> ServerHelper.isStandaloneRunning(client)); } } /** * Checks to see if a domain server is running. * * @param client the client used to communicate with the server * * @return {@code true} if the server, and it's auto-start servers, are running, otherwise {@code false} */ public static boolean isDomainRunning(final ModelControllerClient client) { return isDomainRunning(client, false); } /** * Checks to see if a domain server is running. * * @param client the client used to communicate with the server * @param forShutdown if this is checking for a shutdown * * @return {@code true} if the server, and it's auto-start servers, are running, otherwise {@code false} */ public static boolean isDomainRunning(final ModelControllerClient client, final boolean forShutdown) { final DomainClient domainClient = (client instanceof DomainClient ? (DomainClient) client : DomainClient.Factory.create(client)); try { // Check for admin-only final ModelNode hostAddress = determineHostAddress(domainClient); final Operations.CompositeOperationBuilder builder = Operations.CompositeOperationBuilder.create() .addStep(Operations.createReadAttributeOperation(hostAddress, "running-mode")) .addStep(Operations.createReadAttributeOperation(hostAddress, "host-state")); ModelNode response = domainClient.execute(builder.build()); if (Operations.isSuccessfulOutcome(response)) { response = Operations.readResult(response); if ("ADMIN_ONLY".equals(Operations.readResult(response.get("step-1")).asString())) { if (Operations.isSuccessfulOutcome(response.get("step-2"))) { final String state = Operations.readResult(response).asString(); return !CONTROLLER_PROCESS_STATE_STARTING.equals(state) && !CONTROLLER_PROCESS_STATE_STOPPING.equals(state); } } } final Map<ServerIdentity, ServerStatus> servers = new HashMap<>(); final Map<ServerIdentity, ServerStatus> statuses = domainClient.getServerStatuses(); for (Map.Entry<ServerIdentity, ServerStatus> entry : statuses.entrySet()) { final ServerStatus status = entry.getValue(); switch (status) { case DISABLED: case STARTED: { servers.put(entry.getKey(), status); break; } } } if (forShutdown) { return statuses.isEmpty(); } return statuses.size() == servers.size(); } catch (IllegalStateException | IOException ignore) { } return false; } /** * Shuts down a domain server. * * @throws IOException if an error occurs communicating with the server */ public static void shutdownDomain(final DomainClient client) throws IOException { // Now shutdown the host final ModelNode address = ServerHelper.determineHostAddress(client); final ModelNode shutdownOp = Operations.createOperation("shutdown", address); final ModelNode response = client.execute(shutdownOp); if (!Operations.isSuccessfulOutcome(response)) { Assert.fail("Failed to stop servers: " + response); } } /** * Waits the given amount of time in seconds for a domain server to start. * <p> * If the {@code process} is not {@code null} and a timeout occurs the process will be * {@linkplain Process#destroy() destroyed}. * </p> * * @param process the Java process can be {@code null} if no process is available * * @throws InterruptedException if interrupted while waiting for the server to start * @throws RuntimeException if the process has died */ public static void waitForDomain(final Process process, final Supplier<String> failureDescription) throws InterruptedException, IOException { try (DomainClient client = DomainClient.Factory.create(TestSuiteEnvironment.getModelControllerClient())) { waitForStart(process, failureDescription, () -> ServerHelper.isDomainRunning(client)); } } public static void waitForManagedServer(final DomainClient client, final String serverName, final Supplier<String> failureDescription) throws InterruptedException { waitForStart(null, failureDescription, () -> { // Wait for the server to start ServerStatus serverStatus = null; final Map<ServerIdentity, ServerStatus> statuses = client.getServerStatuses(); for (Map.Entry<ServerIdentity, ServerStatus> entry : statuses.entrySet()) { if (serverName.equals(entry.getKey().getServerName())) { serverStatus = entry.getValue(); break; } } return serverStatus == ServerStatus.STARTED; }); } public static List<JsonObject> readLogFileFromModel(final String logFileName, final String... addressPrefix) throws IOException { final Collection<String> addr = new ArrayList<>(); if (addressPrefix != null) { Collections.addAll(addr, addressPrefix); } addr.add("subsystem"); addr.add("logging"); addr.add("log-file"); addr.add(logFileName); final ModelNode address = Operations.createAddress(addr); final ModelNode op = Operations.createReadAttributeOperation(address, "stream"); try (ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient()) { final OperationResponse response = client.executeOperation(Operation.Factory.create(op), OperationMessageHandler.logging); final ModelNode result = response.getResponseNode(); if (Operations.isSuccessfulOutcome(result)) { final OperationResponse.StreamEntry entry = response.getInputStream(Operations.readResult(result).asString()); if (entry == null) { throw new RuntimeException(String.format("Failed to find entry with UUID %s for log file %s", Operations.readResult(result).asString(), logFileName)); } final List<JsonObject> lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(entry.getStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { try (JsonReader jsonReader = Json.createReader(new StringReader(line))) { lines.add(jsonReader.readObject()); } } } return lines; } throw new RuntimeException(String.format("Failed to read log file %s: %s", logFileName, Operations.getFailureDescription(result).asString())); } } /** * Attempts to determine the address for a domain server. * * @param client the client used to communicate with the server * * @return the host address * * @throws IOException if an error occurs determining the host name */ public static ModelNode determineHostAddress(final ModelControllerClient client) throws IOException { return Operations.createAddress("host", determineHostName(client)); } /** * Attempts to determine the name for a domain server. * * @param client the client used to communicate with the server * * @return the host name * * @throws IOException if an error occurs determining the host name */ public static String determineHostName(final ModelControllerClient client) throws IOException { final ModelNode op = Operations.createReadAttributeOperation(EMPTY_ADDRESS, "local-host-name"); ModelNode response = client.execute(op); if (Operations.isSuccessfulOutcome(response)) { return Operations.readResult(response).asString(); } throw new IOException("Failed to determine host name: " + Operations.readResult(response).asString()); } private static boolean isNullOrEmpty(final String value) { return value == null || value.trim().isEmpty(); } private static void waitForStart(final Process process, final Supplier<String> failureDescription, final BooleanSupplier check) throws InterruptedException { long timeout = ServerHelper.TIMEOUT * 1000; final long sleep = 100L; while (timeout > 0) { long before = System.currentTimeMillis(); if (check.getAsBoolean()) break; timeout -= (System.currentTimeMillis() - before); if (process != null && !process.isAlive()) { Assert.fail(failureDescription.get()); } TimeUnit.MILLISECONDS.sleep(sleep); timeout -= sleep; } if (timeout <= 0) { if (process != null) { process.destroy(); } Assert.fail(String.format("The server did not start within %s seconds: %s", ServerHelper.TIMEOUT, failureDescription.get())); } } }
14,947
44.024096
168
java
null
wildfly-main/testsuite/scripts/src/test/java/org/wildfly/test/scripts/WsConsumeScriptTestCase.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed 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.wildfly.test.scripts; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class WsConsumeScriptTestCase extends ScriptTestCase { public WsConsumeScriptTestCase() { super("wsconsume"); } }
961
30.032258
75
java
null
wildfly-main/testsuite/scripts/src/test/java/org/wildfly/test/scripts/ScriptProcess.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed 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.wildfly.test.scripts; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Function; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.logging.Logger; /** * Represents a script. Note that this is not thread-safe. * * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class ScriptProcess extends Process implements AutoCloseable { private static final Logger LOGGER = Logger.getLogger(ScriptProcess.class); private static final Path PROC_DIR; private static final Function<String, String> WINDOWS_ARG_FORMATTER = s -> "\"" + s + "\""; static { PROC_DIR = Paths.get(System.getProperty("jboss.test.proc.dir")); try { Files.createDirectories(PROC_DIR); } catch (IOException e) { throw new UncheckedIOException("Failed to create the log directory", e); } } private final Path containerHome; private final Path script; private final Shell shell; private final long timeout; private final Collection<String> prefixCmds; private Process delegate; private Path stdoutLog; private String lastExecutedCmd; ScriptProcess(final Path containerHome, final String scriptBaseName, final Shell shell, final long timeout) { this.containerHome = containerHome; final String scriptName = scriptBaseName + shell.getExtension(); this.shell = shell; this.script = containerHome.resolve("bin").resolve(scriptName); this.timeout = timeout; this.prefixCmds = Arrays.asList(shell.getPrefix()); lastExecutedCmd = ""; } void start(final Map<String, String> env, final String... arguments) throws IOException, TimeoutException, InterruptedException { start(null, env, arguments); } @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) void start(final Function<ModelControllerClient, Boolean> check, final Map<String, String> env, final String... arguments) throws IOException, TimeoutException, InterruptedException { if (delegate != null) { throw new IllegalStateException("This process has already been started and has not exited."); } final Collection<String> args = Arrays.asList(arguments); lastExecutedCmd = getCommandString(args); if (LOGGER.isDebugEnabled()) { LOGGER.debugf("Attempting to start: %s", lastExecutedCmd); } final String baseFileName = script.getFileName().toString().replace('.', '-'); stdoutLog = Files.createTempFile(PROC_DIR, baseFileName, "-out.txt"); final ProcessBuilder builder = new ProcessBuilder(getCommand(args)) .directory(containerHome.toFile()) .redirectErrorStream(true) .redirectOutput(stdoutLog.toFile()); builder.environment().put("JBOSS_HOME", containerHome.toString()); // The Windows scripts should not pause at the requiring user input if (TestSuiteEnvironment.isWindows()) { builder.environment().put("NOPAUSE", "true"); } // Add any other environment variables if (env != null && !env.isEmpty()) { builder.environment().putAll(env); } final Process process = builder.start(); if (check != null) { waitFor(process, check); } this.delegate = process; } @SuppressWarnings("unused") Path getScript() { return script; } List<String> getStdout() throws IOException { if (stdoutLog == null) { return Collections.emptyList(); } return Files.readAllLines(stdoutLog, StandardCharsets.UTF_8); } String getErrorMessage(final String msg) { final StringBuilder errorMessage = new StringBuilder(msg) .append(System.lineSeparator()) .append("Command Executed:") .append(System.lineSeparator()) .append(lastExecutedCmd) .append(System.lineSeparator()) .append("Environment:") .append(System.lineSeparator()) .append("Output:") .append(System.lineSeparator()); try { for (String line : getStdout()) { errorMessage.append(line) .append(System.lineSeparator()); } } catch (IOException ignore) { } return errorMessage.toString(); } Path getContainerHome() { return containerHome; } Shell getShell() { return shell; } private List<String> getCommand(final Collection<String> arguments) { final List<String> cmd = new ArrayList<>(prefixCmds); cmd.add(script.toString()); if (TestSuiteEnvironment.isWindows()) { for (String arg : arguments) { cmd.add(WINDOWS_ARG_FORMATTER.apply(arg)); } } else { cmd.addAll(arguments); } return cmd; } @Override public void close() { destroy(delegate); delegate = null; } @Override public OutputStream getOutputStream() { checkStatus(); return delegate.getOutputStream(); } @Override public InputStream getInputStream() { checkStatus(); return delegate.getInputStream(); } @Override public InputStream getErrorStream() { checkStatus(); return delegate.getErrorStream(); } @Override public int waitFor() throws InterruptedException { checkStatus(); return delegate.waitFor(); } @Override public boolean waitFor(final long timeout, final TimeUnit unit) throws InterruptedException { checkStatus(); return delegate.waitFor(timeout, unit); } @Override public int exitValue() { checkStatus(); return delegate.exitValue(); } @Override public void destroy() { checkStatus(); delegate.destroy(); } @Override public Process destroyForcibly() { checkStatus(); return delegate.destroyForcibly(); } @Override public boolean isAlive() { checkStatus(); return delegate.isAlive(); } @Override public String toString() { return getCommandString(Collections.emptyList()); } private String getCommandString(final Collection<String> arguments) { final List<String> cmd = getCommand(arguments); final StringBuilder result = new StringBuilder(); final Iterator<String> iter = cmd.iterator(); while (iter.hasNext()) { result.append(iter.next()); if (iter.hasNext()) { result.append(' '); } } return result.toString(); } private void checkStatus() { if (delegate == null) { throw new IllegalStateException("The script has not yet been started."); } } private void waitFor(final Process process, final Function<ModelControllerClient, Boolean> check) throws TimeoutException, InterruptedException { @SuppressWarnings("Convert2Lambda") final Callable<Boolean> callable = new Callable<Boolean>() { @Override public Boolean call() throws InterruptedException, IOException { long timeout = (ScriptProcess.this.timeout * 1000); final long sleep = 100L; try (ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient()) { while (timeout > 0) { if (!process.isAlive()) { return false; } long before = System.currentTimeMillis(); if (check.apply(client)) { return true; } timeout -= (System.currentTimeMillis() - before); TimeUnit.MILLISECONDS.sleep(sleep); timeout -= sleep; } } return false; } }; final ExecutorService service = Executors.newSingleThreadExecutor(); try { final Future<Boolean> future = service.submit(callable); if (!future.get()) { destroy(process); throw new TimeoutException(getErrorMessage(String.format("The %s did not start within %d seconds.", script.getFileName(), this.timeout))); } } catch (ExecutionException e) { throw new RuntimeException(getErrorMessage(String.format("Failed to determine if the %s server is running.", script.getFileName())), e); } finally { service.shutdownNow(); } } private void destroy(final Process process) { if (process != null && process.isAlive()) { final Process destroyed = process.destroyForcibly(); try { if (destroyed.isAlive() && !destroyed.waitFor(timeout, TimeUnit.SECONDS)) { LOGGER.errorf("The process was not destroyed within %d seconds.", timeout); } } catch (InterruptedException e) { LOGGER.error("The process was interrupted while waiting to be destroyed.", e); } } } }
10,917
33.660317
154
java
null
wildfly-main/testsuite/scripts/src/test/java/org/wildfly/test/scripts/ScriptTestCase.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed 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.wildfly.test.scripts; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.junit.After; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.wildfly.test.common.ServerConfigurator; import org.wildfly.test.common.ServerHelper; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public abstract class ScriptTestCase { static final Map<String, String> MAVEN_JAVA_OPTS = new LinkedHashMap<>(); private final String scriptBaseName; private final boolean testCommonConfOnly; private ExecutorService service; ScriptTestCase(final String scriptBaseName) { this(scriptBaseName, false); } ScriptTestCase(final String scriptBaseName, final boolean testCommonConfOnly) { this.scriptBaseName = scriptBaseName; this.testCommonConfOnly = testCommonConfOnly; } @BeforeClass public static void configureEnvironment() throws Exception { final String localRepo = System.getProperty("maven.repo.local"); if (localRepo != null) { MAVEN_JAVA_OPTS.put("JAVA_OPTS", "-Dmaven.repo.local=" + localRepo); } ServerConfigurator.configure(); } @Before public void setup() { service = Executors.newCachedThreadPool(); } @After public void cleanup() { service.shutdownNow(); } @Test public void testBatchScript() throws Exception { Assume.assumeTrue(Shell.BATCH.isSupported()); executeTests(Shell.BATCH); } @Test public void testPowerShellScript() throws Exception { Assume.assumeTrue(TestSuiteEnvironment.isWindows() && Shell.POWERSHELL.isSupported()); executeTests(Shell.POWERSHELL); } @Test public void testBashScript() throws Exception { Assume.assumeTrue(!TestSuiteEnvironment.isWindows() && Shell.BASH.isSupported()); executeTests(Shell.BASH); } @Test public void testDashScript() throws Exception { Assume.assumeTrue(!TestSuiteEnvironment.isWindows() && Shell.DASH.isSupported()); executeTests(Shell.DASH); } @Test public void testKshScript() throws Exception { Assume.assumeTrue(!TestSuiteEnvironment.isWindows() && Shell.KSH.isSupported()); executeTests(Shell.KSH); } void testScript(final ScriptProcess script) throws InterruptedException, TimeoutException, IOException { // Just test the help, there's not much more we should do here unless we start a standalone server script.start(MAVEN_JAVA_OPTS, "-h"); Assert.assertNotNull("The process is null and may have failed to start.", script); validateProcess(script); // Simply check for the "usage" boolean missing = true; for (String line : script.getStdout()) { if (line.startsWith("usage:")) { missing = false; break; } } if (missing) { Assert.fail(script.getErrorMessage("Expected the \"usage:\" to be present")); } } void validateProcess(final ScriptProcess script) throws InterruptedException { if (script.waitFor(ServerHelper.TIMEOUT, TimeUnit.SECONDS)) { // The script has exited, validate the exit code is valid final int exitValue = script.exitValue(); if (exitValue != 0) { Assert.fail(script.getErrorMessage(String.format("Expected an exit value 0f 0 got %d", exitValue))); } } else { Assert.fail(script.getErrorMessage("The script process did not exit within " + ServerHelper.TIMEOUT + " seconds.")); } } private void executeTests(final Shell shell) throws InterruptedException, IOException, TimeoutException { for (Path path : ServerConfigurator.PATHS) { try (ScriptProcess script = new ScriptProcess(path, scriptBaseName, shell, ServerHelper.TIMEOUT)) { if (!testCommonConfOnly) { testScript(script); script.close(); } testCommonConf(script, shell); } } } private void testCommonConf(final ScriptProcess script, final Shell shell) throws InterruptedException, IOException, TimeoutException { testCommonConf(script, true, shell); testCommonConf(script, false, shell); } private void testCommonConf(final ScriptProcess script, final boolean useEnvVar, final Shell shell) throws InterruptedException, IOException, TimeoutException { final Map<String, String> env = new HashMap<>(); final Path confFile; if (useEnvVar) { confFile = Paths.get(TestSuiteEnvironment.getTmpDir(), "test-common" + shell.getConfExtension()); env.put("COMMON_CONF", confFile.toString()); } else { confFile = script.getContainerHome().resolve("bin").resolve("common" + shell.getConfExtension()); } // Create the common conf file which will simply echo some text and then exit the script final String text = "Test from common configuration to " + confFile.getFileName().toString(); try (BufferedWriter writer = Files.newBufferedWriter(confFile, StandardCharsets.UTF_8)) { if (shell == Shell.POWERSHELL) { writer.write("Write-Output \""); writer.write(text); writer.write('"'); writer.newLine(); writer.write("break"); } else { writer.write("echo \""); writer.write(text); writer.write('"'); writer.newLine(); writer.write("exit"); } writer.newLine(); } try { script.start(env); if (!script.waitFor(ServerHelper.TIMEOUT, TimeUnit.SECONDS)) { Assert.fail(script.getErrorMessage("Failed to exit script from " + confFile)); } // Batch scripts print the quotes around the text final String expectedText = (shell == Shell.BATCH ? "\"" + text + "\"" : text); final List<String> lines = script.getStdout(); Assert.assertEquals(script.getErrorMessage("There should only be one line logged before the script exited"), 1, lines.size()); Assert.assertEquals(expectedText, lines.get(0)); } finally { script.close(); Files.delete(confFile); } } }
7,790
36.1
164
java
null
wildfly-main/testsuite/scripts/src/test/java/org/wildfly/test/scripts/Shell.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed 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.wildfly.test.scripts; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.BooleanSupplier; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.wildfly.test.common.ServerHelper; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public enum Shell { BASH(".sh", ".conf", () -> isShellSupported("bash", "-c", "echo", "test")), BATCH(".bat", ".conf.bat", TestSuiteEnvironment::isWindows), DASH(".sh", ".conf", () -> isShellSupported("dash", "-c", "echo", "test"), "dash"), KSH(".sh", ".conf", () -> isShellSupported("ksh", "-c", "echo", "test"), "ksh"), POWERSHELL(".ps1", ".conf.ps1", () -> isShellSupported("powershell", "-Help"), "powershell", "-ExecutionPolicy", "Unrestricted", "-NonInteractive", "-File"), ; private final String extension; private final String confExtension; private final BooleanSupplier supported; private final String[] prefix; Shell(final String extension, final String confExtension, final BooleanSupplier supported, final String... prefix) { this.extension = extension; this.confExtension = confExtension; this.supported = supported; this.prefix = prefix; } public String[] getPrefix() { return prefix; } public String getExtension() { return extension; } public String getConfExtension() { return confExtension; } public boolean isSupported() { return supported.getAsBoolean(); } private static boolean isShellSupported(final String name, final String... args) { final List<String> cmd = new ArrayList<>(); cmd.add(name); if (args != null && args.length > 0) { cmd.addAll(Arrays.asList(args)); } try { final Path stdout = Files.createTempFile(name + "-supported", ".log"); final ProcessBuilder builder = new ProcessBuilder(cmd) .redirectErrorStream(true) .redirectOutput(stdout.toFile()); Process process = null; try { process = builder.start(); if (!process.waitFor(ServerHelper.TIMEOUT, TimeUnit.SECONDS)) { return false; } return process.exitValue() == 0; } catch (IOException e) { return false; } catch (InterruptedException e) { throw new RuntimeException(e); } finally { if (process != null) { process.destroyForcibly(); } Files.deleteIfExists(stdout); } } catch (IOException e) { throw new UncheckedIOException(e); } } }
3,745
32.747748
120
java
null
wildfly-main/testsuite/scripts/src/test/java/org/wildfly/test/scripts/AppClientScriptTestCase.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed 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.wildfly.test.scripts; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeoutException; import org.junit.Assert; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class AppClientScriptTestCase extends ScriptTestCase { public AppClientScriptTestCase() { super("appclient"); } @Override void testScript(final ScriptProcess script) throws InterruptedException, TimeoutException, IOException { script.start(MAVEN_JAVA_OPTS, "-v"); Assert.assertNotNull("The process is null and may have failed to start.", script); validateProcess(script); final List<String> lines = script.getStdout(); int count = 2; for (String stdout : lines) { if (stdout.startsWith("Picked up")) { count += 1; } } final int expectedLines = (script.getShell() == Shell.BATCH ? 3 : count ); Assert.assertEquals(script.getErrorMessage(String.format("Expected %d lines.", expectedLines)), expectedLines, lines.size()); } }
1,837
31.821429
118
java
null
wildfly-main/testsuite/scripts/src/test/java/org/wildfly/test/scripts/WsProduceScriptTestCase.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed 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.wildfly.test.scripts; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class WsProduceScriptTestCase extends ScriptTestCase { public WsProduceScriptTestCase() { super("wsconsume"); } }
961
30.032258
75
java
null
wildfly-main/testsuite/scripts/src/test/java/org/wildfly/test/scripts/JconsoleScriptTestCase.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed 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.wildfly.test.scripts; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class JconsoleScriptTestCase extends ScriptTestCase { public JconsoleScriptTestCase() { super("jconsole", true); } }
964
30.129032
75
java
null
wildfly-main/testsuite/scripts/src/test/java/org/wildfly/test/scripts/JdrScriptTestCase.java
/* * JBoss, Home of Professional Open Source. * * Copyright 2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed 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.wildfly.test.scripts; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class JdrScriptTestCase extends ScriptTestCase { public JdrScriptTestCase() { super("jdr"); } }
943
29.451613
75
java
null
wildfly-main/testsuite/layers/src/test/java/org/jboss/as/test/layers/base/LayersTestCase.java
/* * * * JBoss, Home of Professional Open Source. * * Copyright 2023 Red Hat, Inc., and individual contributors * * as indicated by the @author tags. * * * * Licensed 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.jboss.as.test.layers.base; import org.jboss.as.test.shared.LayersTestBase; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; public class LayersTestCase extends LayersTestBase { @Override public void test() throws Exception { // For WildFly Preview testing, ignore this test. The testing in the layers-expansion // testsuite module covers this. // In this module the test-standalone-reference installation will be // provisioned with a lot of MP, etc modules, as that's what wildfly-preview FP does. // But the test-all-layers installation will not include the expansion layers as // testing those is out of scope for this module. AssumeTestGroupUtil.assumeNotWildFlyPreview(); super.test(); } }
1,555
36.95122
93
java
null
wildfly-main/testsuite/integration/microprofile-tck/lra/src/test/java/org/wildfly/extension/microprofile/lra/test/LRAMpTckApplicationArchiveProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.lra.test; import io.narayana.lra.LRAConstants; import io.narayana.lra.arquillian.spi.NarayanaLRARecovery; import org.eclipse.microprofile.lra.tck.service.spi.LRARecoveryService; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.test.spi.TestClass; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import java.io.File; /** * @author Martin Stefanko */ public class LRAMpTckApplicationArchiveProcessor implements ApplicationArchiveProcessor { @Override public void process(Archive<?> archive, TestClass testClass) { if (archive instanceof WebArchive) { JavaArchive extensionsJar = ShrinkWrap.create(JavaArchive.class, "extension.jar"); extensionsJar.addClasses(NarayanaLRARecovery.class, LRAConstants.class); extensionsJar.addAsServiceProvider(LRARecoveryService.class, NarayanaLRARecovery.class); extensionsJar.addAsManifestResource(new StringAsset("<beans xmlns=\"https://jakarta.ee/xml/ns/jakartaee\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_4_0.xsd\"\n" + " version=\"4.0\" bean-discovery-mode=\"all\">\n" + "</beans>"), "beans.xml"); WebArchive war = (WebArchive) archive; war.addAsLibraries(extensionsJar); final File archiveDir = new File("target/archives"); archiveDir.mkdirs(); File moduleFile = new File(archiveDir, "test-lra-extension.war"); war.as(ZipExporter.class).exportTo(moduleFile, true); } } }
3,057
44.641791
137
java
null
wildfly-main/testsuite/integration/microprofile-tck/lra/src/test/java/org/wildfly/extension/microprofile/lra/test/WildFlyArquillianExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.lra.test; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.core.spi.LoadableExtension; public class WildFlyArquillianExtension implements LoadableExtension { @Override public void register(ExtensionBuilder extensionBuilder) { extensionBuilder.service(ApplicationArchiveProcessor.class, LRAMpTckApplicationArchiveProcessor.class); } }
1,496
43.029412
111
java
null
wildfly-main/testsuite/integration/microprofile-tck/telemetry/src/test/java/io/smallrye/opentelemetry/ExceptionMapper.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package io.smallrye.opentelemetry; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.ext.Provider; /** * Temporal fix to catch exceptions thrown in Jakarta RESTful Web Services endpoints, see https://issues.jboss.org/browse/RESTEASY-1758 * * @author Pavol Loffay */ @Provider public class ExceptionMapper implements jakarta.ws.rs.ext.ExceptionMapper<RuntimeException> { @Override public Response toResponse(RuntimeException exception) { return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } }
1,603
38.121951
135
java
null
wildfly-main/testsuite/integration/microprofile-tck/telemetry/src/test/java/io/smallrye/opentelemetry/arquillian/DeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package io.smallrye.opentelemetry.arquillian; import java.io.File; import io.smallrye.opentelemetry.ExceptionMapper; import jakarta.ws.rs.ext.Providers; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.test.spi.TestClass; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; /** * @author Pavol Loffay */ public class DeploymentProcessor implements ApplicationArchiveProcessor { @Override public void process(Archive<?> archive, TestClass testClass) { if (archive instanceof WebArchive) { JavaArchive extensionsJar = ShrinkWrap.create(JavaArchive.class, "extension.jar"); extensionsJar.addClass(ExceptionMapper.class); extensionsJar.addAsServiceProvider(Providers.class, ExceptionMapper.class); WebArchive war = WebArchive.class.cast(archive); war.addAsLibraries(extensionsJar); final File archiveDir = new File("target/archives"); archiveDir.mkdirs(); File moduleFile = new File(archiveDir, "testapp.war"); war.as(ZipExporter.class).exportTo(moduleFile, true); } } }
2,394
39.59322
94
java
null
wildfly-main/testsuite/integration/microprofile-tck/telemetry/src/test/java/io/smallrye/opentelemetry/arquillian/ArquillianExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package io.smallrye.opentelemetry.arquillian; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.core.spi.LoadableExtension; /** * @author Pavol Loffay */ public class ArquillianExtension implements LoadableExtension { @Override public void register(ExtensionBuilder extensionBuilder) { extensionBuilder.service(ApplicationArchiveProcessor.class, DeploymentProcessor.class); } }
1,514
38.868421
93
java
null
wildfly-main/testsuite/integration/microprofile-tck/config/src/test/java/org/wildfly/extension/microprofile/config/test/DeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.test; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.hamcrest.internal.ReflectiveTypeFinder; import org.hamcrest.number.IsCloseTo; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.test.spi.TestClass; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; public class DeploymentProcessor implements ApplicationArchiveProcessor { @Override public void process(Archive<?> archive, TestClass testClass) { if (archive instanceof WebArchive) { JavaArchive extensionsJar = ShrinkWrap.create(JavaArchive.class, "extension.jar"); extensionsJar.addPackage(Matchers.class.getPackage()); extensionsJar.addPackage(IsEqual.class.getPackage()); extensionsJar.addPackage(IsCloseTo.class.getPackage()); extensionsJar.addPackage(ReflectiveTypeFinder.class.getPackage()); extensionsJar.addPackage(junit.framework.Assert.class.getPackage()); extensionsJar.addPackage(org.junit.Assert.class.getPackage()); WebArchive war = WebArchive.class.cast(archive); war.addAsLibraries(extensionsJar); } } }
2,419
44.660377
94
java
null
wildfly-main/testsuite/integration/microprofile-tck/config/src/test/java/org/wildfly/extension/microprofile/config/test/WildFlyArquillianExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.test; import org.jboss.arquillian.container.spi.client.container.DeploymentExceptionTransformer; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.core.spi.LoadableExtension; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2019 Red Hat inc. */ public class WildFlyArquillianExtension implements LoadableExtension { @Override public void register(ExtensionBuilder extensionBuilder) { extensionBuilder.service(ApplicationArchiveProcessor.class, DeploymentProcessor.class); extensionBuilder.service(DeploymentExceptionTransformer.class, WildFlyDeploymentExceptionTransformer.class); } }
1,777
45.789474
116
java
null
wildfly-main/testsuite/integration/microprofile-tck/config/src/test/java/org/wildfly/extension/microprofile/config/test/WildFlyDeploymentExceptionTransformer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.config.test; import jakarta.enterprise.inject.spi.DeploymentException; import org.jboss.arquillian.container.spi.client.container.DeploymentExceptionTransformer; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2020 Red Hat inc. */ public class WildFlyDeploymentExceptionTransformer implements DeploymentExceptionTransformer { public Throwable transform(Throwable throwable) { // Due to https://issues.redhat.com/browse/WFARQ-59 if the deployment fails, WildFly Arquillian // returns a DeploymentException without a cause. In that case (throwable == null), we create a new DeploymentException // so that the test will properly get a DeploymentException (the actual cause of the deployment failure is lost though). if (throwable == null) { return new DeploymentException("Deployment on WildFly was unsuccessful. Look at the WildFly server logs to have more information on the actual cause of the deployment failure"); } return throwable; } }
2,096
47.767442
189
java
null
wildfly-main/testsuite/integration/microprofile-tck/reactive-messaging/src/test/java/org/wildfly/test/integration/mp/tck/reactive/messaging/WildFlyArquillianExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.mp.tck.reactive.messaging; import org.jboss.arquillian.container.spi.client.container.DeploymentExceptionTransformer; import org.jboss.arquillian.core.spi.LoadableExtension; import org.jboss.as.arquillian.container.ExceptionTransformer; /** * @author <a href="mailto:kabir.khan@jboss.com">Kabir Khan</a> */ public class WildFlyArquillianExtension implements LoadableExtension { @Override public void register(ExtensionBuilder extensionBuilder) { extensionBuilder.override(DeploymentExceptionTransformer.class, ExceptionTransformer.class, WildFlyDeploymentExceptionTransformer.class); } }
1,673
43.052632
145
java
null
wildfly-main/testsuite/integration/microprofile-tck/reactive-messaging/src/test/java/org/wildfly/test/integration/mp/tck/reactive/messaging/WildFlyDeploymentExceptionTransformer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.mp.tck.reactive.messaging; import jakarta.enterprise.inject.spi.DefinitionException; import jakarta.enterprise.inject.spi.DeploymentException; import org.jboss.arquillian.container.spi.client.container.DeploymentExceptionTransformer; /** * Workaround for https://issues.redhat.com/browse/WFARQ-59 and https://issues.redhat.com/browse/WFARQ-36. * The TCK wrongly assumes that deployment exceptions will always result in a thrown exception of a specific type. * This class checks the exception thrown to make sure the root cause on the server is what is expected. * * @author <a href="mailto:kabir.khan@jboss.com">Kabir Khan</a> */ public class WildFlyDeploymentExceptionTransformer implements DeploymentExceptionTransformer { // Trim of the prefix so it matches both javax. and jakarta. private final String DEFINITION_EXCEPTION = ".enterprise.inject.spi.DefinitionException"; @Override public Throwable transform(Throwable throwable) { if (throwable instanceof org.jboss.arquillian.container.spi.client.container.DeploymentException) { // This ends up running on the client, and the arq DeploymentException does not actually // have the cause populated. However, the message contains a summary of what happened on the server, // and will look something like: // // Cannot deploy test.war: {"WFLYCTL0062: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-1" => {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"test.war\".WeldStartService" => "Failed to start service // Caused by: org.jboss.weld.exceptions.DeploymentException: Unknown connector for dummy-source-2. // Caused by: java.lang.IllegalArgumentException: Unknown connector for dummy-source-2."}}}} // // For other tests this looks like //Cannot deploy test.war: {"WFLYCTL0062: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-1" => {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"test.war\".WeldStartService" => "Failed to start service // Caused by: org.jboss.weld.exceptions.DeploymentException: SRMSG00081: Invalid method annotated with @Incoming: org.eclipse.microprofile.reactive.messaging.tck.signatures.invalid.IncomingReturningNonVoid#invalid. The signature is not supported as the produced result would be ignored. The method must return `void`, found java.lang.String. // Caused by: javax.enterprise.inject.spi.DefinitionException: SRMSG00081: Invalid method annotated with @Incoming: org.eclipse.microprofile.reactive.messaging.tck.signatures.invalid.IncomingReturningNonVoid#invalid. The signature is not supported as the produced result would be ignored. The method must return `void`, found java.lang.String."}}}} // So we parse the string looking for the relevant parts here. The Weld DeploymentException extends // the javax.enterprise.inject.spi.DeploymentException wanted by the test, so it has happened if // we can find it in the exception message. String msg = throwable.getMessage(); if ((msg.contains("SRMSG00081") || msg.contains("SRMSG00080")) && msg.contains(DEFINITION_EXCEPTION)) { return new DefinitionException(msg); } if (msg.contains("WFLYCTL0080") && msg.contains("org.jboss.weld.exceptions.DeploymentException")) { return new DeploymentException(msg); } } return null; } }
4,669
66.681159
363
java
null
wildfly-main/testsuite/integration/microprofile-tck/reactive-messaging/src/test/java/org/wildfly/test/integration/mp/tck/reactive/messaging/WildFlyArchiveExtender.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.mp.tck.reactive.messaging; import org.eclipse.microprofile.reactive.messaging.tck.ArchiveExtender; import org.eclipse.microprofile.reactive.messaging.tck.TckBase; import org.jboss.shrinkwrap.api.spec.JavaArchive; /** * @author <a href="mailto:kabir.khan@jboss.com">Kabir Khan</a> */ public class WildFlyArchiveExtender implements ArchiveExtender { @Override public void extend(JavaArchive archive) { archive.addClass(TckBase.class); } }
1,522
39.078947
71
java
null
wildfly-main/testsuite/integration/microprofile-tck/health/src/test/java/org/wildfly/extension/microprofile/health/test/DeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.health.test; import org.apache.http.HttpRequest; import org.apache.http.auth.Credentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpUriRequest; import org.eclipse.microprofile.health.tck.TCKBase; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.test.spi.TestClass; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; public class DeploymentProcessor implements ApplicationArchiveProcessor { @Override public void process(Archive<?> archive, TestClass testClass) { if (archive instanceof WebArchive) { JavaArchive extensionsJar = ShrinkWrap.create(JavaArchive.class, "extension.jar"); extensionsJar.addPackage(TCKBase.class.getPackage()); extensionsJar.addPackage(Credentials.class.getPackage()); extensionsJar.addPackage(CredentialsProvider.class.getPackage()); extensionsJar.addPackage(HttpUriRequest.class.getPackage()); extensionsJar.addPackage(HttpRequest.class.getPackage()); WebArchive war = WebArchive.class.cast(archive); war.addAsLibraries(extensionsJar); } } }
2,422
43.87037
94
java
null
wildfly-main/testsuite/integration/microprofile-tck/health/src/test/java/org/wildfly/extension/microprofile/health/test/WildFlyURIProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.health.test; import java.lang.annotation.Annotation; import java.net.URI; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. * @author Rostislav Svoboda (c) 2018 Red Hat inc. */ public class WildFlyURIProvider implements ResourceProvider { @Override public Object lookup(ArquillianResource arquillianResource, Annotation... annotations) { return URI.create("http://localhost:9990"); } @Override public boolean canProvide(Class<?> type) { return type.isAssignableFrom(URI.class); } }
1,759
36.446809
92
java
null
wildfly-main/testsuite/integration/microprofile-tck/health/src/test/java/org/wildfly/extension/microprofile/health/test/WildFlyArquillianExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.health.test; import org.jboss.arquillian.container.test.impl.enricher.resource.URIResourceProvider; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.core.spi.LoadableExtension; import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2017 Red Hat inc. */ public class WildFlyArquillianExtension implements LoadableExtension { @Override public void register(ExtensionBuilder extensionBuilder) { extensionBuilder.override(ResourceProvider.class, URIResourceProvider.class, WildFlyURIProvider.class); extensionBuilder.service(ApplicationArchiveProcessor.class, DeploymentProcessor.class); } }
1,842
45.075
111
java
null
wildfly-main/testsuite/integration/microprofile-tck/jwt/src/test/java/org/wildfly/extension/microprofile/jwt/test/DeploymentProcessor.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed 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.wildfly.extension.microprofile.jwt.test; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.test.spi.TestClass; import org.jboss.shrinkwrap.api.Archive; //import org.jboss.shrinkwrap.api.ShrinkWrap; //import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; //import org.testng.Assert; /** * Class to handle additional processing needed for deployments. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class DeploymentProcessor implements ApplicationArchiveProcessor { @Override public void process(Archive<?> archive, TestClass testClass) { if (archive instanceof WebArchive) { //JavaArchive extensionsJar = ShrinkWrap.create(JavaArchive.class, "extension.jar"); //extensionsJar.addPackage(Assert.class.getPackage()); WebArchive war = WebArchive.class.cast(archive); if (war.contains("META-INF/microprofile-config.properties") == false) { war.addAsManifestResource("META-INF/microprofile-config-local.properties", "microprofile-config.properties"); } war.addAsWebInfResource("WEB-INF/web.xml", "web.xml"); war.addAsWebInfResource("WEB-INF/jboss-web.xml", "jboss-web.xml"); //war.addAsLibraries(extensionsJar); } System.out.printf("Final Srchive: %s\n", archive.toString(true)); } }
2,100
39.403846
125
java
null
wildfly-main/testsuite/integration/microprofile-tck/jwt/src/test/java/org/wildfly/extension/microprofile/jwt/test/WildFlyArquillianExtension.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed 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.wildfly.extension.microprofile.jwt.test; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.core.spi.LoadableExtension; /** * Extension to register the {@link DeploymentProcessor} * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class WildFlyArquillianExtension implements LoadableExtension { @Override public void register(ExtensionBuilder extensionBuilder) { extensionBuilder.service(ApplicationArchiveProcessor.class, DeploymentProcessor.class); } }
1,197
34.235294
95
java
null
wildfly-main/testsuite/integration/microprofile-tck/reactive-streams-operators/src/test/java/org/wildfly/test/integration/mp/tck/reactive/streams/operators/WildFlyArquillianExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.mp.tck.reactive.streams.operators; import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender; import org.jboss.arquillian.core.spi.LoadableExtension; /** * @author <a href="mailto:kabir.khan@jboss.com">Kabir Khan</a> */ public class WildFlyArquillianExtension implements LoadableExtension { @Override public void register(ExtensionBuilder extensionBuilder) { extensionBuilder.service(AuxiliaryArchiveAppender.class, JCommanderAuxilliaryArchiveAppender.class); } }
1,581
41.756757
108
java
null
wildfly-main/testsuite/integration/microprofile-tck/reactive-streams-operators/src/test/java/org/wildfly/test/integration/mp/tck/reactive/streams/operators/JCommanderAuxilliaryArchiveAppender.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.mp.tck.reactive.streams.operators; import org.jboss.arquillian.container.test.spi.client.deployment.CachedAuxilliaryArchiveAppender; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import com.beust.jcommander.ParameterException; /** * @author <a href="mailto:kabir.khan@jboss.com">Kabir Khan</a> */ public class JCommanderAuxilliaryArchiveAppender extends CachedAuxilliaryArchiveAppender { @Override protected Archive<?> buildArchive() { return ShrinkWrap .create(JavaArchive.class, "wildfly-jcommander.jar") .addClass(ParameterException.class); } }
1,755
39.837209
97
java
null
wildfly-main/testsuite/integration/microprofile-tck/fault-tolerance/src/test/java/org/wildfly/extension/microprofile/faulttolerance/tck/FaultToleranceApplicationArchiveProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.faulttolerance.tck; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import java.lang.reflect.ReflectPermission; import java.util.PropertyPermission; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.test.spi.TestClass; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.container.ClassContainer; import org.jboss.shrinkwrap.api.container.LibraryContainer; import org.jboss.shrinkwrap.api.container.ManifestContainer; import org.jboss.shrinkwrap.api.spec.JavaArchive; /** * Adapted from SmallRye Fault Tolerance project. * * @author Radoslav Husar */ public class FaultToleranceApplicationArchiveProcessor implements ApplicationArchiveProcessor { @Override public void process(Archive<?> applicationArchive, TestClass testClass) { if (!(applicationArchive instanceof ClassContainer)) { return; } ClassContainer<?> classContainer = (ClassContainer<?>) applicationArchive; if (applicationArchive instanceof LibraryContainer) { JavaArchive additionalBeanArchive = ShrinkWrap.create(JavaArchive.class); additionalBeanArchive.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); ((LibraryContainer<?>) applicationArchive).addAsLibrary(additionalBeanArchive); } else { classContainer.addAsResource(EmptyAsset.INSTANCE, "META-INF/beans.xml"); } if (!applicationArchive.contains("META-INF/beans.xml")) { applicationArchive.add(EmptyAsset.INSTANCE, "META-INF/beans.xml"); } // Run the TCK with security manager if (applicationArchive instanceof ManifestContainer) { ManifestContainer<?> mc = (ManifestContainer<?>) applicationArchive; mc.addAsManifestResource(createPermissionsXmlAsset( // Permissions required by test instrumentation - arquillian-core.jar and arquillian-testng.jar new ReflectPermission("suppressAccessChecks"), new PropertyPermission("*", "read"), new RuntimePermission("accessDeclaredMembers"), // Permissions required by test instrumentation - awaitility.jar new RuntimePermission("setDefaultUncaughtExceptionHandler"), new RuntimePermission("modifyThread") ), "permissions.xml"); } } }
3,676
44.395062
115
java
null
wildfly-main/testsuite/integration/microprofile-tck/fault-tolerance/src/test/java/org/wildfly/extension/microprofile/faulttolerance/tck/WildFlyDeploymentExceptionTransformer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.faulttolerance.tck; import org.eclipse.microprofile.faulttolerance.exceptions.FaultToleranceDefinitionException; import org.jboss.arquillian.container.spi.client.container.DeploymentExceptionTransformer; /** * Temporary workaround for https://issues.jboss.org/browse/WFARQ-59 where the exception is an instance of DeploymentException * but its cause is null. * * @author Radoslav Husar */ public class WildFlyDeploymentExceptionTransformer implements DeploymentExceptionTransformer { @Override public Throwable transform(Throwable throwable) { if (throwable == null) { return new FaultToleranceDefinitionException(); } else { return throwable; } } }
1,783
40.488372
126
java
null
wildfly-main/testsuite/integration/microprofile-tck/fault-tolerance/src/test/java/org/wildfly/extension/microprofile/faulttolerance/tck/FaultToleranceTCKExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.faulttolerance.tck; import org.jboss.arquillian.container.spi.client.container.DeploymentExceptionTransformer; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.core.spi.LoadableExtension; /** * @author Radoslav Husar */ public class FaultToleranceTCKExtension implements LoadableExtension { @Override public void register(ExtensionBuilder builder) { builder.service(DeploymentExceptionTransformer.class, WildFlyDeploymentExceptionTransformer.class); builder.service(ApplicationArchiveProcessor.class, FaultToleranceApplicationArchiveProcessor.class); } }
1,727
43.307692
108
java
null
wildfly-main/testsuite/integration/microprofile-tck/openapi/src/test/java/org/wildfly/extension/microprofile/openapi/tck/DeploymentProcessor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.openapi.tck; import org.hamcrest.Matchers; import org.hamcrest.core.IsEqual; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.test.spi.TestClass; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; public class DeploymentProcessor implements ApplicationArchiveProcessor { @Override public void process(Archive<?> archive, TestClass testClass) { if (archive instanceof WebArchive) { JavaArchive extensionsJar = ShrinkWrap.create(JavaArchive.class, "extension.jar"); extensionsJar.addPackage(Matchers.class.getPackage()); extensionsJar.addPackage(IsEqual.class.getPackage()); WebArchive war = WebArchive.class.cast(archive); war.addAsLibraries(extensionsJar); } } }
2,027
42.148936
94
java
null
wildfly-main/testsuite/integration/microprofile-tck/openapi/src/test/java/org/wildfly/extension/microprofile/openapi/tck/WildFlyArquillianExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.microprofile.openapi.tck; import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; import org.jboss.arquillian.core.spi.LoadableExtension; /** * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2019 Red Hat inc. */ public class WildFlyArquillianExtension implements LoadableExtension { @Override public void register(ExtensionBuilder extensionBuilder) { extensionBuilder.service(ApplicationArchiveProcessor.class, DeploymentProcessor.class); } }
1,569
42.611111
95
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/TestIdentityStore.java
/* * Copyright 2018 Red Hat, Inc. * * Licensed 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.wildfly.test.integration.elytron.securityapi; import static java.util.Arrays.asList; import static jakarta.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT; import java.util.HashSet; import jakarta.enterprise.context.ApplicationScoped; import jakarta.security.enterprise.credential.Credential; import jakarta.security.enterprise.credential.UsernamePasswordCredential; import jakarta.security.enterprise.identitystore.CredentialValidationResult; import jakarta.security.enterprise.identitystore.IdentityStore; /** * A simple {@link IdentityStore} for testing. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @ApplicationScoped public class TestIdentityStore implements IdentityStore { static final String USERNAME = "user1"; static final String PASSWORD = "password1"; @Override public CredentialValidationResult validate(Credential credential) { if (credential instanceof UsernamePasswordCredential) { UsernamePasswordCredential upc = (UsernamePasswordCredential) credential; if (USERNAME.equals(upc.getCaller()) && PASSWORD.equals(upc.getPasswordAsString())) { return new CredentialValidationResult("user1", new HashSet<String>(asList("Role1", "Role2"))); } } return INVALID_RESULT; } }
1,963
35.37037
110
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/SecurityAPITestCase.java
/* * Copyright 2018 Red Hat, Inc. * * Licensed 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.wildfly.test.integration.elytron.securityapi; import static org.apache.http.HttpStatus.SC_OK; import static org.apache.http.HttpStatus.SC_UNAUTHORIZED; import static org.junit.Assert.assertEquals; import static org.wildfly.test.integration.elytron.securityapi.TestAuthenticationMechanism.MESSAGE; import static org.wildfly.test.integration.elytron.securityapi.TestAuthenticationMechanism.MESSAGE_HEADER; import static org.wildfly.test.integration.elytron.securityapi.TestAuthenticationMechanism.PASSWORD_HEADER; import static org.wildfly.test.integration.elytron.securityapi.TestAuthenticationMechanism.USERNAME_HEADER; import static org.wildfly.test.integration.elytron.securityapi.TestIdentityStore.PASSWORD; import static org.wildfly.test.integration.elytron.securityapi.TestIdentityStore.USERNAME; import static org.jboss.as.test.shared.PermissionUtils.createPermissionsXmlAsset; import java.net.URI; import java.net.URL; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.security.permission.ElytronPermission; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain; /** * Test case to test the EE Security API with WildFly Elytron. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({ SecurityAPITestCase.ServerSetup.class }) public class SecurityAPITestCase { @ArquillianResource protected URL url; private final boolean ejbSupported = !Boolean.getBoolean("ts.layers") && !Boolean.getBoolean("ts.bootable"); @Deployment protected static WebArchive createDeployment() { final Package testPackage = SecurityAPITestCase.class.getPackage(); return ShrinkWrap.create(WebArchive.class, SecurityAPITestCase.class.getSimpleName() + ".war") .addClasses(SecurityAPITestCase.class, AbstractElytronSetupTask.class, ServerSetup.class) .addClasses(TestAuthenticationMechanism.class, TestIdentityStore.class) .addClasses(TestServlet.class) .addClasses(WhoAmI.class, WhoAmIBean.class) .addAsWebInfResource(Utils.getJBossWebXmlAsset("SecurityAPI"), "jboss-web.xml") .addAsWebInfResource(testPackage, "jboss-ejb3.xml", "jboss-ejb3.xml") .addAsWebInfResource(testPackage, "beans.xml", "beans.xml") .addAsManifestResource(createPermissionsXmlAsset(new ElytronPermission("getSecurityDomain")), "permissions.xml"); } @Test public void testCalls() throws Exception { HttpGet request = new HttpGet(new URI(url.toExternalForm() + "/test")); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { // Verify that we are not challenged. try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode); assertEquals("Unexpected content of HTTP response.", "null", EntityUtils.toString(response.getEntity())); } request = new HttpGet(new URI(url.toExternalForm() + "/test?challenge=true")); // Now verify that we are challenged. try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode); assertEquals("Unexpected challenge header", MESSAGE, response.getFirstHeader(MESSAGE_HEADER).getValue()); } request = new HttpGet(new URI(url.toExternalForm() + "/test")); // Verify a bad username and password results in a challenge. request.addHeader(USERNAME_HEADER, "evil"); request.addHeader(PASSWORD_HEADER, "password"); try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode); assertEquals("Unexpected challenge header", MESSAGE, response.getFirstHeader(MESSAGE_HEADER).getValue()); } // Verify a good username and password establishes an identity with the HttpServletRequest request = new HttpGet(new URI(url.toExternalForm() + "/test")); request.addHeader(USERNAME_HEADER, USERNAME); request.addHeader(PASSWORD_HEADER, PASSWORD); try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode); assertEquals("Unexpected content of HTTP response.", USERNAME, EntityUtils.toString(response.getEntity())); } // Verify a good username and password establishes an identity with the SecurityDomain request = new HttpGet(new URI(url.toExternalForm() + "/test?source=SecurityDomain")); request.addHeader(USERNAME_HEADER, USERNAME); request.addHeader(PASSWORD_HEADER, PASSWORD); try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode); assertEquals("Unexpected content of HTTP response.", USERNAME, EntityUtils.toString(response.getEntity())); } // Verify a good username and password establishes an identity with the SecurityContext request = new HttpGet(new URI(url.toExternalForm() + "/test?source=SecurityContext")); request.addHeader(USERNAME_HEADER, USERNAME); request.addHeader(PASSWORD_HEADER, PASSWORD); try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode); assertEquals("Unexpected content of HTTP response.", USERNAME, EntityUtils.toString(response.getEntity())); } if (ejbSupported) { // Verify a good username and password establishes an identity with the Jakarta Enterprise Beans SessionContext request = new HttpGet(new URI(url.toExternalForm() + "/test?ejb=true")); request.addHeader(USERNAME_HEADER, USERNAME); request.addHeader(PASSWORD_HEADER, PASSWORD); try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode); assertEquals("Unexpected content of HTTP response.", USERNAME, EntityUtils.toString(response.getEntity())); } // Verify a good username and password establishes an identity with the SecurityDomain within an Jakarta Enterprise Beans request = new HttpGet(new URI(url.toExternalForm() + "/test?ejb=true&source=SecurityDomain")); request.addHeader(USERNAME_HEADER, USERNAME); request.addHeader(PASSWORD_HEADER, PASSWORD); try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode); assertEquals("Unexpected content of HTTP response.", USERNAME, EntityUtils.toString(response.getEntity())); } // Verify a good username and password establishes an identity with the SecurityContext within an Jakarta Enterprise Beans request = new HttpGet(new URI(url.toExternalForm() + "/test?ejb=true&source=SecurityContext")); request.addHeader(USERNAME_HEADER, USERNAME); request.addHeader(PASSWORD_HEADER, PASSWORD); try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode); assertEquals("Unexpected content of HTTP response.", USERNAME, EntityUtils.toString(response.getEntity())); } } } } static class ServerSetup extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { ConfigurableElement[] elements = new ConfigurableElement[1]; // 1 - Map the application-security-domain elements[0] = UndertowApplicationSecurityDomain.builder() .withName("SecurityAPI") .withSecurityDomain("ApplicationDomain") .withIntegratedJaspi(false) .build(); return elements; } } }
10,824
53.949239
138
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/TestIdentityStoreCustomWrapper.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed 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.wildfly.test.integration.elytron.securityapi; import static jakarta.security.enterprise.identitystore.CredentialValidationResult.Status.VALID; import jakarta.enterprise.context.ApplicationScoped; import jakarta.security.enterprise.credential.Credential; import jakarta.security.enterprise.identitystore.CredentialValidationResult; /** * A thin wrapper for {@link TestIdentityStore} which returns a {@link TestCustomPrincipal custom princpal} in place of * a {@link jakarta.security.enterprise.CallerPrincipal}. * * @author <a href="mailto:carodrig@redhat.com">Cameron Rodriguez</a> */ @ApplicationScoped public class TestIdentityStoreCustomWrapper extends TestIdentityStore { @Override public CredentialValidationResult validate(Credential credential) { CredentialValidationResult cvr = super.validate(credential); if (cvr.getStatus() != VALID) return cvr; return new CredentialValidationResult( new TestCustomPrincipal(cvr.getCallerPrincipal()), cvr.getCallerGroups() ); } }
1,668
37.813953
119
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/EESecurityInjectionEnabledJakartaTestCase.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed 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.wildfly.test.integration.elytron.securityapi; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicHeader; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain; import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain; /** * Validates that the {@code ee-security} subsystem is enabled when a deployment implements Jakarta Security (ex. * implementing an {@link jakarta.security.enterprise.identitystore.IdentityStore IdentityStore}). Returns a custom * principal to client via {@link jakarta.security.enterprise.SecurityContext}. * * @author <a href="mailto:carodrig@redhat.com">Cameron Rodriguez</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({ EESecurityInjectionEnabledJakartaTestCase.ServerSetup.class }) public class EESecurityInjectionEnabledJakartaTestCase extends EESecurityInjectionEnabledAbstractTestCase { @ArquillianResource private Deployer deployer; private static final String WEB_APP_NAME = "WFLY-17541-Jakarta"; @Deployment(name = WEB_APP_NAME, managed = false, testable = false) public static WebArchive warDeployment() { Class<EESecurityInjectionEnabledJakartaTestCase> testClass = EESecurityInjectionEnabledJakartaTestCase.class; return ShrinkWrap.create(WebArchive.class,testClass.getSimpleName() + ".war") .addClasses(testClass, EESecurityInjectionEnabledAbstractTestCase.class) .addClasses(ServerSetup.class, EESecurityInjectionEnabledAbstractTestCase.ServerSetup.class, AbstractElytronSetupTask.class) .addClasses(TestInjectServlet.class) .addClasses(TestAuthenticationMechanism.class, TestIdentityStoreCustomWrapper.class, TestIdentityStore.class) .addAsWebInfResource(Utils.getJBossWebXmlAsset(TEST_APP_DOMAIN), "jboss-web.xml") .addAsWebInfResource(testClass.getPackage(), "WFLY-17541-jakarta-web.xml", "web.xml") .addAsWebInfResource(testClass.getPackage(), "WFLY-17541-index.xml", "index.xml") .addAsManifestResource(new StringAsset("Dependencies: " + MODULE_NAME + "\n"), "MANIFEST.MF"); } @Override Header[] setRequestAuthHeader() { return new BasicHeader[] { new BasicHeader("X-USERNAME", "user1"), new BasicHeader("X-PASSWORD", "password1") }; } @Test @InSequence(1) public void deployApplication() { deployer.deploy(WEB_APP_NAME); } @Test @InSequence(2) public void testUnsuccessfulAuthentication(@ArquillianResource URL webAppURL) throws IOException, URISyntaxException { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpGet request = new HttpGet(webAppURL.toURI() + "/inject"); HttpResponse response = httpClient.execute(request); assertEquals(401, response.getStatusLine().getStatusCode()); // Check that the challenge message was sent Header authHeader = response.getFirstHeader(TestAuthenticationMechanism.MESSAGE_HEADER); assertNotNull(authHeader); assertEquals(TestAuthenticationMechanism.MESSAGE, authHeader.getValue()); } } @Override @Test @InSequence(3) public void testCustomPrincipalWithInject(@ArquillianResource URL webAppURL) throws IOException, URISyntaxException { super.testCustomPrincipalWithInject(webAppURL); } @Test @InSequence(4) public void undeployApplication() { deployer.undeploy(WEB_APP_NAME); } static class ServerSetup extends EESecurityInjectionEnabledAbstractTestCase.ServerSetup { @Override protected ConfigurableElement[] getConfigurableElements() { ConfigurableElement[] elements = new ConfigurableElement[3]; // Add module with custom principal and principal transformer elements[0] = module; // Create security domain with default permission mapper elements[1] = SimpleSecurityDomain.builder() .withName(TEST_SECURITY_DOMAIN) .withPermissionMapper(DEFAULT_PERMISSION_MAPPER) .build(); // Add security domain to Undertow configuration elements[2] = UndertowApplicationSecurityDomain.builder() .withName(TEST_APP_DOMAIN) .withSecurityDomain(TEST_SECURITY_DOMAIN) .withIntegratedJaspi(false) .build(); return elements; } } }
6,350
43.104167
125
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/TestCustomPrincipalTransformer.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed 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.wildfly.test.integration.elytron.securityapi; import java.security.Principal; import org.wildfly.extension.elytron.capabilities.PrincipalTransformer; /** * A simple {@link PrincipalTransformer} that also converts into a {@link TestCustomPrincipal custom principal}. * * @author <a href="mailto:carodrig@redhat.com">Cameron Rodriguez</a> */ public class TestCustomPrincipalTransformer implements PrincipalTransformer { @Override public Principal apply(Principal principal) { return new TestCustomPrincipal(principal); } }
1,157
32.085714
112
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/TestServlet.java
/* * Copyright 2018 Red Hat, Inc. * * Licensed 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.wildfly.test.integration.elytron.securityapi; import java.io.IOException; import java.io.PrintWriter; import java.security.Principal; import jakarta.ejb.EJB; import jakarta.inject.Inject; import jakarta.security.enterprise.SecurityContext; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.wildfly.security.auth.server.SecurityDomain; /** * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @WebServlet(urlPatterns="/test") public class TestServlet extends HttpServlet { @Inject private SecurityContext securityContext; @EJB private WhoAmI whoami; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doGet"); final PrintWriter writer = resp.getWriter(); final String sourceParam = req.getParameter("source"); final boolean ejb = Boolean.valueOf(req.getParameter("ejb")); final String source = sourceParam != null ? sourceParam : ""; // Default Action final Principal principal; switch (source) { case "SecurityContext": principal = ejb ? whoami.getCallerPrincipalSecurityContext() : securityContext.getCallerPrincipal(); break; case "SecurityDomain": principal = ejb ? whoami.getCallerPrincipalSecurityDomain() : SecurityDomain.getCurrent().getCurrentSecurityIdentity().getPrincipal(); break; default: principal = ejb ? whoami.getCallerPrincipalSessionContext() : req.getUserPrincipal(); } writer.print(principal == null ? "null" : principal.getName()); } }
2,505
33.805556
150
java