Removing upload scripts feature (#11117)

Closes #9865

Co-authored-by: Michal Hajas <mhajas@redhat.com>

Co-authored-by: Michal Hajas <mhajas@redhat.com>
This commit is contained in:
Pedro Igor 2022-04-20 09:25:16 -03:00 committed by GitHub
parent 3aa3db16ea
commit 2cb5d8d972
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
123 changed files with 897 additions and 33420 deletions

View file

@ -66,7 +66,9 @@ public final class DeployedScriptPolicyFactory extends JSPolicyProviderFactory {
representation.setId(policy.getId()); representation.setId(policy.getId());
representation.setName(policy.getName()); representation.setName(policy.getName());
representation.setDescription(metadata.getDescription()); if (policy.getDescription() == null) {
representation.setDescription(metadata.getDescription());
}
representation.setType(getId()); representation.setType(getId());
representation.setCode(metadata.getCode()); representation.setCode(metadata.getCode());
@ -81,8 +83,10 @@ public final class DeployedScriptPolicyFactory extends JSPolicyProviderFactory {
@Override @Override
public void onCreate(Policy policy, JSPolicyRepresentation representation, AuthorizationProvider authorization) { public void onCreate(Policy policy, JSPolicyRepresentation representation, AuthorizationProvider authorization) {
representation.setDescription(metadata.getDescription()); if (representation.getDescription() == null) {
policy.setDescription(metadata.getDescription()); representation.setDescription(metadata.getDescription());
policy.setDescription(metadata.getDescription());
}
super.onCreate(policy, representation, authorization); super.onCreate(policy, representation, authorization);
} }

View file

@ -57,17 +57,19 @@ public class JSPolicyProviderFactory implements PolicyProviderFactory<JSPolicyRe
@Override @Override
public void onCreate(Policy policy, JSPolicyRepresentation representation, AuthorizationProvider authorization) { public void onCreate(Policy policy, JSPolicyRepresentation representation, AuthorizationProvider authorization) {
updatePolicy(policy, representation.getCode(), authorization); throwCanNotUpdatePolicy(authorization);
} }
@Override @Override
public void onUpdate(Policy policy, JSPolicyRepresentation representation, AuthorizationProvider authorization) { public void onUpdate(Policy policy, JSPolicyRepresentation representation, AuthorizationProvider authorization) {
updatePolicy(policy, representation.getCode(), authorization); policy.setDecisionStrategy(representation.getDecisionStrategy());
policy.setDescription(policy.getDescription());
policy.setLogic(policy.getLogic());
} }
@Override @Override
public void onImport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorization) { public void onImport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorization) {
updatePolicy(policy, representation.getConfig().get("code"), authorization); throwCanNotUpdatePolicy(authorization);
} }
@Override @Override
@ -99,7 +101,7 @@ public class JSPolicyProviderFactory implements PolicyProviderFactory<JSPolicyRe
@Override @Override
public boolean isInternal() { public boolean isInternal() {
return !Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS); return true;
} }
private EvaluatableScriptAdapter getEvaluatableScript(final AuthorizationProvider authz, final Policy policy) { private EvaluatableScriptAdapter getEvaluatableScript(final AuthorizationProvider authz, final Policy policy) {
@ -119,15 +121,13 @@ public class JSPolicyProviderFactory implements PolicyProviderFactory<JSPolicyRe
return scripting.createScript(realm.getId(), ScriptModel.TEXT_JAVASCRIPT, scriptName, scriptCode, scriptDescription); return scripting.createScript(realm.getId(), ScriptModel.TEXT_JAVASCRIPT, scriptName, scriptCode, scriptDescription);
} }
private void updatePolicy(Policy policy, String code, AuthorizationProvider authorization) {
scriptCache.remove(policy.getId());
if (!Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS) && !authorization.getKeycloakSession().getAttributeOrDefault("ALLOW_CREATE_POLICY", false) && !isDeployed()) {
throw new RuntimeException("Script upload is disabled");
}
policy.putConfig("code", code);
}
protected boolean isDeployed() { protected boolean isDeployed() {
return false; return false;
} }
private void throwCanNotUpdatePolicy(AuthorizationProvider authorization) {
if (!authorization.getKeycloakSession().getAttributeOrDefault("ALLOW_CREATE_POLICY", false) && !isDeployed()) {
throw new RuntimeException("Script upload is disabled");
}
}
} }

View file

@ -147,11 +147,11 @@ public class UMAPolicyProviderFactory implements PolicyProviderFactory<UmaPermis
} else { } else {
RepresentationToModel.toModel(rep, authorization, associatedPolicy); RepresentationToModel.toModel(rep, authorization, associatedPolicy);
} }
} else if ("js".equals(associatedRep.getType())) { } else if (associatedRep instanceof JSPolicyRepresentation) {
JSPolicyRepresentation rep = JSPolicyRepresentation.class.cast(associatedRep); JSPolicyRepresentation rep = JSPolicyRepresentation.class.cast(associatedRep);
if (representation.getCondition() != null) { if (representation.getCondition() != null) {
rep.setCode(representation.getCondition()); rep.setType(representation.getCondition());
RepresentationToModel.toModel(rep, authorization, associatedPolicy); RepresentationToModel.toModel(rep, authorization, associatedPolicy);
} else { } else {
policyStore.delete(associatedPolicy.getId()); policyStore.delete(associatedPolicy.getId());
@ -291,7 +291,7 @@ public class UMAPolicyProviderFactory implements PolicyProviderFactory<UmaPermis
boolean createPolicy = true; boolean createPolicy = true;
for (Policy associatedPolicy : associatedPolicies) { for (Policy associatedPolicy : associatedPolicies) {
if ("js".equals(associatedPolicy.getType())) { if (associatedPolicy.getType().startsWith("script-")) {
createPolicy = false; createPolicy = false;
} }
} }
@ -329,9 +329,9 @@ public class UMAPolicyProviderFactory implements PolicyProviderFactory<UmaPermis
representation.addRole(role.getName()); representation.addRole(role.getName());
} }
} }
} else if ("js".equals(associatedRep.getType())) { } else if (associatedRep instanceof JSPolicyRepresentation) {
JSPolicyRepresentation rep = JSPolicyRepresentation.class.cast(associatedRep); JSPolicyRepresentation rep = JSPolicyRepresentation.class.cast(associatedRep);
representation.setCondition(rep.getCode()); representation.setCondition(rep.getType());
} else if ("group".equals(associatedRep.getType())) { } else if ("group".equals(associatedRep.getType())) {
GroupPolicyRepresentation rep = GroupPolicyRepresentation.class.cast(associatedRep); GroupPolicyRepresentation rep = GroupPolicyRepresentation.class.cast(associatedRep);
@ -394,7 +394,7 @@ public class UMAPolicyProviderFactory implements PolicyProviderFactory<UmaPermis
JSPolicyRepresentation rep = new JSPolicyRepresentation(); JSPolicyRepresentation rep = new JSPolicyRepresentation();
rep.setName(KeycloakModelUtils.generateId()); rep.setName(KeycloakModelUtils.generateId());
rep.setCode(condition); rep.setType(condition);
Policy associatedPolicy = policyStore.create(policy.getResourceServer(), rep); Policy associatedPolicy = policyStore.create(policy.getResourceServer(), rep);

View file

@ -70,11 +70,6 @@ public class Profile {
disabledFeatures.add(f); disabledFeatures.add(f);
} else if (DEPRECATED.equals(type)) { } else if (DEPRECATED.equals(type)) {
logger.warnf("Deprecated feature enabled: " + f.name().toLowerCase()); logger.warnf("Deprecated feature enabled: " + f.name().toLowerCase());
if (Feature.UPLOAD_SCRIPTS.equals(f)) {
previewFeatures.add(Feature.SCRIPTS);
disabledFeatures.remove(Feature.SCRIPTS);
logger.warnf("Preview feature enabled: " + Feature.SCRIPTS.name().toLowerCase());
}
} }
break; break;
case PREVIEW: case PREVIEW:
@ -159,7 +154,6 @@ public class Profile {
OPENSHIFT_INTEGRATION("Extension to enable securing OpenShift", Type.PREVIEW), OPENSHIFT_INTEGRATION("Extension to enable securing OpenShift", Type.PREVIEW),
SCRIPTS("Write custom authenticators using JavaScript", Type.PREVIEW), SCRIPTS("Write custom authenticators using JavaScript", Type.PREVIEW),
TOKEN_EXCHANGE("Token Exchange Service", Type.PREVIEW), TOKEN_EXCHANGE("Token Exchange Service", Type.PREVIEW),
UPLOAD_SCRIPTS("Ability to upload custom JavaScript through Admin REST API", DEPRECATED),
WEB_AUTHN("W3C Web Authentication (WebAuthn)", Type.DEFAULT), WEB_AUTHN("W3C Web Authentication (WebAuthn)", Type.DEFAULT),
CLIENT_POLICIES("Client configuration policies", Type.DEFAULT), CLIENT_POLICIES("Client configuration policies", Type.DEFAULT),
CIBA("OpenID Connect Client Initiated Backchannel Authentication (CIBA)", Type.DEFAULT), CIBA("OpenID Connect Client Initiated Backchannel Authentication (CIBA)", Type.DEFAULT),

View file

@ -1,5 +1,7 @@
package org.keycloak.common; package org.keycloak.common;
import static org.junit.Assert.assertTrue;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -22,9 +24,8 @@ public class ProfileTest {
@Test @Test
public void checkDefaultsKeycloak() { public void checkDefaultsKeycloak() {
Assert.assertEquals("community", Profile.getName()); Assert.assertEquals("community", Profile.getName());
assertEquals(Profile.getDisabledFeatures(), Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ, Profile.Feature.DYNAMIC_SCOPES, Profile.Feature.ADMIN2, Profile.Feature.DOCKER, Profile.Feature.RECOVERY_CODES, Profile.Feature.SCRIPTS, Profile.Feature.TOKEN_EXCHANGE, Profile.Feature.OPENSHIFT_INTEGRATION, Profile.Feature.UPLOAD_SCRIPTS, Profile.Feature.MAP_STORAGE, Profile.Feature.DECLARATIVE_USER_PROFILE, Feature.CLIENT_SECRET_ROTATION); assertEquals(Profile.getDisabledFeatures(), Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ, Profile.Feature.DYNAMIC_SCOPES, Profile.Feature.ADMIN2, Profile.Feature.DOCKER, Profile.Feature.RECOVERY_CODES, Profile.Feature.SCRIPTS, Profile.Feature.TOKEN_EXCHANGE, Profile.Feature.OPENSHIFT_INTEGRATION, Profile.Feature.MAP_STORAGE, Profile.Feature.DECLARATIVE_USER_PROFILE, Feature.CLIENT_SECRET_ROTATION);
assertEquals(Profile.getPreviewFeatures(), Profile.Feature.ADMIN2, Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ, Profile.Feature.RECOVERY_CODES, Profile.Feature.SCRIPTS, Profile.Feature.TOKEN_EXCHANGE, Profile.Feature.OPENSHIFT_INTEGRATION, Profile.Feature.DECLARATIVE_USER_PROFILE, Feature.CLIENT_SECRET_ROTATION); assertEquals(Profile.getPreviewFeatures(), Profile.Feature.ADMIN2, Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ, Profile.Feature.RECOVERY_CODES, Profile.Feature.SCRIPTS, Profile.Feature.TOKEN_EXCHANGE, Profile.Feature.OPENSHIFT_INTEGRATION, Profile.Feature.DECLARATIVE_USER_PROFILE, Feature.CLIENT_SECRET_ROTATION);
assertEquals(Profile.getDeprecatedFeatures(), Profile.Feature.UPLOAD_SCRIPTS);
} }
@Test @Test
@ -35,9 +36,8 @@ public class ProfileTest {
Profile.init(); Profile.init();
Assert.assertEquals("product", Profile.getName()); Assert.assertEquals("product", Profile.getName());
assertEquals(Profile.getDisabledFeatures(), Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ, Profile.Feature.DYNAMIC_SCOPES, Profile.Feature.ADMIN2, Profile.Feature.DOCKER, Profile.Feature.RECOVERY_CODES, Profile.Feature.SCRIPTS, Profile.Feature.TOKEN_EXCHANGE, Profile.Feature.OPENSHIFT_INTEGRATION, Profile.Feature.UPLOAD_SCRIPTS, Profile.Feature.MAP_STORAGE, Profile.Feature.DECLARATIVE_USER_PROFILE, Feature.CLIENT_SECRET_ROTATION); assertEquals(Profile.getDisabledFeatures(), Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ, Profile.Feature.DYNAMIC_SCOPES, Profile.Feature.ADMIN2, Profile.Feature.DOCKER, Profile.Feature.RECOVERY_CODES, Profile.Feature.SCRIPTS, Profile.Feature.TOKEN_EXCHANGE, Profile.Feature.OPENSHIFT_INTEGRATION, Profile.Feature.MAP_STORAGE, Profile.Feature.DECLARATIVE_USER_PROFILE, Feature.CLIENT_SECRET_ROTATION);
assertEquals(Profile.getPreviewFeatures(), Profile.Feature.ADMIN2, Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ, Profile.Feature.RECOVERY_CODES, Profile.Feature.SCRIPTS, Profile.Feature.TOKEN_EXCHANGE, Profile.Feature.OPENSHIFT_INTEGRATION, Profile.Feature.DECLARATIVE_USER_PROFILE, Feature.CLIENT_SECRET_ROTATION); assertEquals(Profile.getPreviewFeatures(), Profile.Feature.ADMIN2, Profile.Feature.ADMIN_FINE_GRAINED_AUTHZ, Profile.Feature.RECOVERY_CODES, Profile.Feature.SCRIPTS, Profile.Feature.TOKEN_EXCHANGE, Profile.Feature.OPENSHIFT_INTEGRATION, Profile.Feature.DECLARATIVE_USER_PROFILE, Feature.CLIENT_SECRET_ROTATION);
assertEquals(Profile.getDeprecatedFeatures(), Profile.Feature.UPLOAD_SCRIPTS);
System.setProperty("keycloak.profile", "community"); System.setProperty("keycloak.profile", "community");
Version.NAME = backUpName; Version.NAME = backUpName;
@ -49,8 +49,7 @@ public class ProfileTest {
Assert.assertEquals("community", Profile.getName()); Assert.assertEquals("community", Profile.getName());
Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.DOCKER)); Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.DOCKER));
Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.OPENSHIFT_INTEGRATION)); Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.OPENSHIFT_INTEGRATION));
Assert.assertTrue(Profile.isFeatureEnabled(Profile.Feature.IMPERSONATION)); assertTrue(Profile.isFeatureEnabled(Profile.Feature.IMPERSONATION));
Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS));
System.setProperty("keycloak.profile", "preview"); System.setProperty("keycloak.profile", "preview");
System.setProperty("keycloak.profile.feature.docker", "enabled"); System.setProperty("keycloak.profile.feature.docker", "enabled");
@ -60,10 +59,9 @@ public class ProfileTest {
Profile.init(); Profile.init();
Assert.assertEquals("preview", Profile.getName()); Assert.assertEquals("preview", Profile.getName());
Assert.assertTrue(Profile.isFeatureEnabled(Profile.Feature.DOCKER)); assertTrue(Profile.isFeatureEnabled(Profile.Feature.DOCKER));
Assert.assertTrue(Profile.isFeatureEnabled(Profile.Feature.OPENSHIFT_INTEGRATION)); assertTrue(Profile.isFeatureEnabled(Profile.Feature.OPENSHIFT_INTEGRATION));
Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.IMPERSONATION)); Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.IMPERSONATION));
Assert.assertTrue(Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS));
System.getProperties().remove("keycloak.profile"); System.getProperties().remove("keycloak.profile");
System.getProperties().remove("keycloak.profile.feature.docker"); System.getProperties().remove("keycloak.profile.feature.docker");
@ -77,8 +75,7 @@ public class ProfileTest {
public void configWithPropertiesFile() throws IOException { public void configWithPropertiesFile() throws IOException {
Assert.assertEquals("community", Profile.getName()); Assert.assertEquals("community", Profile.getName());
Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.DOCKER)); Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.DOCKER));
Assert.assertTrue(Profile.isFeatureEnabled(Profile.Feature.IMPERSONATION)); assertTrue(Profile.isFeatureEnabled(Profile.Feature.IMPERSONATION));
Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS));
File d = temporaryFolder.newFolder(); File d = temporaryFolder.newFolder();
File f = new File(d, "profile.properties"); File f = new File(d, "profile.properties");
@ -97,10 +94,9 @@ public class ProfileTest {
Profile.init(); Profile.init();
Assert.assertEquals("preview", Profile.getName()); Assert.assertEquals("preview", Profile.getName());
Assert.assertTrue(Profile.isFeatureEnabled(Profile.Feature.DOCKER)); assertTrue(Profile.isFeatureEnabled(Profile.Feature.DOCKER));
Assert.assertTrue(Profile.isFeatureEnabled(Profile.Feature.OPENSHIFT_INTEGRATION)); assertTrue(Profile.isFeatureEnabled(Profile.Feature.OPENSHIFT_INTEGRATION));
Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.IMPERSONATION)); Assert.assertFalse(Profile.isFeatureEnabled(Profile.Feature.IMPERSONATION));
Assert.assertTrue(Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS));
System.getProperties().remove("jboss.server.config.dir"); System.getProperties().remove("jboss.server.config.dir");

View file

@ -31,6 +31,7 @@ public class ConfigPropertyRepresentation {
protected Object defaultValue; protected Object defaultValue;
protected List<String> options; protected List<String> options;
protected boolean secret; protected boolean secret;
private boolean readOnly;
public String getName() { public String getName() {
return name; return name;
@ -87,4 +88,12 @@ public class ConfigPropertyRepresentation {
public void setSecret(boolean secret) { public void setSecret(boolean secret) {
this.secret = secret; this.secret = secret;
} }
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public boolean isReadOnly() {
return readOnly;
}
} }

View file

@ -2475,6 +2475,10 @@ public class RepresentationToModel {
PolicyProviderFactory provider = authorization.getProviderFactory(model.getType()); PolicyProviderFactory provider = authorization.getProviderFactory(model.getType());
if (provider == null) {
throw new RuntimeException("Could find policy provider with type [" + model.getType() + "]");
}
if (representation instanceof PolicyRepresentation) { if (representation instanceof PolicyRepresentation) {
provider.onImport(model, PolicyRepresentation.class.cast(representation), authorization); provider.onImport(model, PolicyRepresentation.class.cast(representation), authorization);
} else if (representation.getId() == null) { } else if (representation.getId() == null) {

View file

@ -27,4 +27,14 @@ public interface ConfiguredProvider {
String getHelpText(); String getHelpText();
List<ProviderConfigProperty> getConfigProperties(); List<ProviderConfigProperty> getConfigProperties();
/**
* Returns a default configuration for this provider.
*
* @param <C> the type of the configuration
* @return the default configuration
*/
default <C> C getConfig() {
return null;
}
} }

View file

@ -70,6 +70,7 @@ public class ProviderConfigProperty {
protected Object defaultValue; protected Object defaultValue;
protected List<String> options; protected List<String> options;
protected boolean secret; protected boolean secret;
private boolean readOnly;
public ProviderConfigProperty() { public ProviderConfigProperty() {
} }
@ -189,4 +190,11 @@ public class ProviderConfigProperty {
this.secret = secret; this.secret = secret;
} }
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public boolean isReadOnly() {
return readOnly;
}
} }

View file

@ -16,9 +16,9 @@
*/ */
package org.keycloak.authentication.authenticators.browser; package org.keycloak.authentication.authenticators.browser;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import org.keycloak.Config; import org.keycloak.Config;
import org.keycloak.authentication.AuthenticationFlowContext; import org.keycloak.authentication.AuthenticationFlowContext;
@ -37,6 +37,12 @@ public final class DeployedScriptAuthenticatorFactory extends ScriptBasedAuthent
private ScriptProviderMetadata metadata; private ScriptProviderMetadata metadata;
private AuthenticatorConfigModel model; private AuthenticatorConfigModel model;
private List<ProviderConfigProperty> configProperties; private List<ProviderConfigProperty> configProperties;
private Authenticator authenticator = new ScriptBasedAuthenticator() {
@Override
protected AuthenticatorConfigModel getAuthenticatorConfig(AuthenticationFlowContext context) {
return model;
}
};
public DeployedScriptAuthenticatorFactory(ScriptProviderMetadata metadata) { public DeployedScriptAuthenticatorFactory(ScriptProviderMetadata metadata) {
this.metadata = metadata; this.metadata = metadata;
@ -48,12 +54,7 @@ public final class DeployedScriptAuthenticatorFactory extends ScriptBasedAuthent
@Override @Override
public Authenticator create(KeycloakSession session) { public Authenticator create(KeycloakSession session) {
return new ScriptBasedAuthenticator() { return authenticator;
@Override
protected AuthenticatorConfigModel getAuthenticatorConfig(AuthenticationFlowContext context) {
return model;
}
};
} }
@Override @Override
@ -61,11 +62,6 @@ public final class DeployedScriptAuthenticatorFactory extends ScriptBasedAuthent
return metadata.getId(); return metadata.getId();
} }
@Override
public boolean isConfigurable() {
return false;
}
@Override @Override
public boolean isUserSetupAllowed() { public boolean isUserSetupAllowed() {
return false; return false;
@ -97,6 +93,11 @@ public final class DeployedScriptAuthenticatorFactory extends ScriptBasedAuthent
return configProperties; return configProperties;
} }
@Override
public AuthenticatorConfigModel getConfig() {
return model;
}
public void setMetadata(ScriptProviderMetadata metadata) { public void setMetadata(ScriptProviderMetadata metadata) {
this.metadata = metadata; this.metadata = metadata;
} }
@ -109,12 +110,20 @@ public final class DeployedScriptAuthenticatorFactory extends ScriptBasedAuthent
AuthenticatorConfigModel model = new AuthenticatorConfigModel(); AuthenticatorConfigModel model = new AuthenticatorConfigModel();
model.setId(metadata.getId()); model.setId(metadata.getId());
model.setAlias(metadata.getName()); model.setAlias(sanitizeString(metadata.getName()));
model.setConfig(new HashMap<>());
model.getConfig().put("scriptName", metadata.getName()); Map<String, String> config = new HashMap<>();
model.getConfig().put("scriptCode", metadata.getCode());
model.getConfig().put("scriptDescription", metadata.getDescription()); model.setConfig(config);
config.put("scriptName", metadata.getName());
config.put("scriptCode", metadata.getCode());
config.put("scriptDescription", metadata.getDescription());
return model; return model;
} }
private String sanitizeString(String value) {
return value.replace('/', '-').replace('.', '-');
}
} }

View file

@ -16,19 +16,16 @@
*/ */
package org.keycloak.authentication.authenticators.browser; package org.keycloak.authentication.authenticators.browser;
import org.jboss.logging.Logger;
import org.keycloak.Config; import org.keycloak.Config;
import org.keycloak.authentication.Authenticator; import org.keycloak.authentication.Authenticator;
import org.keycloak.authentication.AuthenticatorFactory; import org.keycloak.authentication.AuthenticatorFactory;
import org.keycloak.common.Profile; import org.keycloak.common.Profile;
import org.keycloak.common.util.StreamUtil;
import org.keycloak.models.AuthenticationExecutionModel; import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.provider.EnvironmentDependentProviderFactory; import org.keycloak.provider.EnvironmentDependentProviderFactory;
import org.keycloak.provider.ProviderConfigProperty; import org.keycloak.provider.ProviderConfigProperty;
import java.io.IOException;
import java.util.List; import java.util.List;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
@ -45,8 +42,6 @@ import static org.keycloak.provider.ProviderConfigProperty.STRING_TYPE;
*/ */
public class ScriptBasedAuthenticatorFactory implements AuthenticatorFactory, EnvironmentDependentProviderFactory { public class ScriptBasedAuthenticatorFactory implements AuthenticatorFactory, EnvironmentDependentProviderFactory {
private static final Logger LOGGER = Logger.getLogger(ScriptBasedAuthenticatorFactory.class);
public static final String PROVIDER_ID = "auth-script-based"; public static final String PROVIDER_ID = "auth-script-based";
static final AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = { static final AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = {
@ -136,15 +131,9 @@ public class ScriptBasedAuthenticatorFactory implements AuthenticatorFactory, En
ProviderConfigProperty script = new ProviderConfigProperty(); ProviderConfigProperty script = new ProviderConfigProperty();
script.setType(SCRIPT_TYPE); script.setType(SCRIPT_TYPE);
script.setName(SCRIPT_CODE); script.setName(SCRIPT_CODE);
script.setReadOnly(true);
script.setLabel("Script Source"); script.setLabel("Script Source");
String scriptTemplate = "//enter your script code here";
try {
scriptTemplate = StreamUtil.readString(getClass().getResourceAsStream("/scripts/authenticator-template.js"));
} catch (IOException ioe) {
LOGGER.warn(ioe);
}
script.setDefaultValue(scriptTemplate);
script.setHelpText("The script used to authenticate. Scripts must at least define a function with the name 'authenticate(context)' that accepts a context (AuthenticationFlowContext) parameter.\n" + script.setHelpText("The script used to authenticate. Scripts must at least define a function with the name 'authenticate(context)' that accepts a context (AuthenticationFlowContext) parameter.\n" +
"This authenticator exposes the following additional variables: 'script', 'realm', 'user', 'session', 'authenticationSession', 'httpRequest', 'LOG'"); "This authenticator exposes the following additional variables: 'script', 'realm', 'user', 'session', 'authenticationSession', 'httpRequest', 'LOG'");
@ -153,6 +142,6 @@ public class ScriptBasedAuthenticatorFactory implements AuthenticatorFactory, En
@Override @Override
public boolean isSupported() { public boolean isSupported() {
return Profile.isFeatureEnabled(Profile.Feature.SCRIPTS) && Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS); return Profile.isFeatureEnabled(Profile.Feature.SCRIPTS);
} }
} }

View file

@ -81,7 +81,9 @@ public class PolicyTypeService extends PolicyService {
throw new RuntimeException("Failed to deserialize JSON using policy provider for type [" + type + "].", e); throw new RuntimeException("Failed to deserialize JSON using policy provider for type [" + type + "].", e);
} }
representation.setType(type); if (!"js".equals(type) || representation.getType() == null) {
representation.setType(type);
}
return representation; return representation;
} }

View file

@ -173,12 +173,6 @@ public class UserManagedPermissionService {
if (!resourceScopes.containsAll(scopes)) { if (!resourceScopes.containsAll(scopes)) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Some of the scopes [" + scopes + "] are not valid for resource [" + resourceId + "]", Response.Status.BAD_REQUEST); throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Some of the scopes [" + scopes + "] are not valid for resource [" + resourceId + "]", Response.Status.BAD_REQUEST);
} }
if (representation.getCondition() != null) {
if (!Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS)) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Script upload not supported", Status.BAD_REQUEST);
}
}
} }
} }

View file

@ -120,7 +120,7 @@ public class ScriptBasedOIDCProtocolMapper extends AbstractOIDCProtocolMapper im
@Override @Override
public boolean isSupported() { public boolean isSupported() {
return Profile.isFeatureEnabled(Profile.Feature.SCRIPTS) && Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS); return Profile.isFeatureEnabled(Profile.Feature.SCRIPTS);
} }
@Override @Override
@ -201,9 +201,8 @@ public class ScriptBasedOIDCProtocolMapper extends AbstractOIDCProtocolMapper im
ProtocolMapperModel mapper = OIDCAttributeMapperHelper.createClaimMapper(name, userAttribute, ProtocolMapperModel mapper = OIDCAttributeMapperHelper.createClaimMapper(name, userAttribute,
tokenClaimName, claimType, tokenClaimName, claimType,
accessToken, idToken, accessToken, idToken,
PROVIDER_ID); script);
mapper.getConfig().put(SCRIPT, script);
mapper.getConfig().put(ProtocolMapperUtils.MULTIVALUED, String.valueOf(multiValued)); mapper.getConfig().put(ProtocolMapperUtils.MULTIVALUED, String.valueOf(multiValued));
return mapper; return mapper;

View file

@ -37,9 +37,11 @@ import org.keycloak.models.AuthenticatorConfigModel;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredActionProviderModel; import org.keycloak.models.RequiredActionProviderModel;
import org.keycloak.models.utils.Base32;
import org.keycloak.models.utils.DefaultAuthenticationFlows; import org.keycloak.models.utils.DefaultAuthenticationFlows;
import org.keycloak.models.utils.ModelToRepresentation; import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.models.utils.RepresentationToModel; import org.keycloak.models.utils.RepresentationToModel;
import org.keycloak.provider.ConfiguredProvider;
import org.keycloak.provider.ProviderConfigProperty; import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.provider.ProviderFactory; import org.keycloak.provider.ProviderFactory;
import org.keycloak.representations.idm.AuthenticationExecutionInfoRepresentation; import org.keycloak.representations.idm.AuthenticationExecutionInfoRepresentation;
@ -497,6 +499,19 @@ public class AuthenticationManagementResource {
execution = realm.addAuthenticatorExecution(execution); execution = realm.addAuthenticatorExecution(execution);
if (f instanceof ConfiguredProvider) {
ConfiguredProvider internalProviderFactory = (ConfiguredProvider) f;
AuthenticatorConfigModel config = internalProviderFactory.getConfig();
if (config != null) {
// creates a default configuration if the factory defines one
// useful for internal providers that already provide a built-in configuration
AuthenticatorConfigRepresentation configRepresentation = ModelToRepresentation.toRepresentation(
config);
newExecutionConfig(execution.getId(), configRepresentation).close();
}
}
data.put("id", execution.getId()); data.put("id", execution.getId());
adminEvent.operation(OperationType.CREATE).resource(ResourceType.AUTH_EXECUTION).resourcePath(session.getContext().getUri()).representation(data).success(); adminEvent.operation(OperationType.CREATE).resource(ResourceType.AUTH_EXECUTION).resourcePath(session.getContext().getUri()).representation(data).success();
@ -589,7 +604,15 @@ public class AuthenticationManagementResource {
} }
rep.setRequirement(execution.getRequirement().name()); rep.setRequirement(execution.getRequirement().name());
rep.setProviderId(execution.getAuthenticator());
providerId = execution.getAuthenticator();
// encode the provider id in case the provider is a script deployed to the server to make sure it can be used as path parameters without break the URL syntax
if (providerId.startsWith("script-")) {
providerId = Base32.encode(providerId.getBytes());
}
rep.setProviderId(providerId);
rep.setAuthenticationConfig(execution.getAuthenticatorConfig()); rep.setAuthenticationConfig(execution.getAuthenticatorConfig());
result.add(rep); result.add(rep);
} }
@ -1117,9 +1140,16 @@ public class AuthenticationManagementResource {
auth.realm().requireViewRealm(); auth.realm().requireViewRealm();
ConfigurableAuthenticatorFactory factory = CredentialHelper.getConfigurableAuthenticatorFactory(session, providerId); ConfigurableAuthenticatorFactory factory = CredentialHelper.getConfigurableAuthenticatorFactory(session, providerId);
if (factory == null) {
providerId = new String(Base32.decode(providerId));
factory = CredentialHelper.getConfigurableAuthenticatorFactory(session, providerId);
}
if (factory == null) { if (factory == null) {
throw new NotFoundException("Could not find authenticator provider"); throw new NotFoundException("Could not find authenticator provider");
} }
AuthenticatorConfigInfoRepresentation rep = new AuthenticatorConfigInfoRepresentation(); AuthenticatorConfigInfoRepresentation rep = new AuthenticatorConfigInfoRepresentation();
rep.setProviderId(providerId); rep.setProviderId(providerId);
rep.setName(factory.getDisplayType()); rep.setName(factory.getDisplayType());

View file

@ -20,7 +20,6 @@ org.keycloak.authentication.authenticators.browser.UsernamePasswordFormFactory
org.keycloak.authentication.authenticators.browser.UsernameFormFactory org.keycloak.authentication.authenticators.browser.UsernameFormFactory
org.keycloak.authentication.authenticators.browser.PasswordFormFactory org.keycloak.authentication.authenticators.browser.PasswordFormFactory
org.keycloak.authentication.authenticators.browser.OTPFormAuthenticatorFactory org.keycloak.authentication.authenticators.browser.OTPFormAuthenticatorFactory
org.keycloak.authentication.authenticators.browser.ScriptBasedAuthenticatorFactory
org.keycloak.authentication.authenticators.browser.SpnegoAuthenticatorFactory org.keycloak.authentication.authenticators.browser.SpnegoAuthenticatorFactory
org.keycloak.authentication.authenticators.browser.IdentityProviderAuthenticatorFactory org.keycloak.authentication.authenticators.browser.IdentityProviderAuthenticatorFactory
org.keycloak.authentication.authenticators.conditional.ConditionalRoleAuthenticatorFactory org.keycloak.authentication.authenticators.conditional.ConditionalRoleAuthenticatorFactory

View file

@ -41,7 +41,6 @@ org.keycloak.protocol.oidc.mappers.UserClientRoleMappingMapper
org.keycloak.protocol.oidc.mappers.UserRealmRoleMappingMapper org.keycloak.protocol.oidc.mappers.UserRealmRoleMappingMapper
org.keycloak.protocol.oidc.mappers.SHA256PairwiseSubMapper org.keycloak.protocol.oidc.mappers.SHA256PairwiseSubMapper
org.keycloak.protocol.docker.mapper.AllowAllDockerProtocolMapper org.keycloak.protocol.docker.mapper.AllowAllDockerProtocolMapper
org.keycloak.protocol.oidc.mappers.ScriptBasedOIDCProtocolMapper
org.keycloak.protocol.saml.mappers.SAMLAudienceProtocolMapper org.keycloak.protocol.saml.mappers.SAMLAudienceProtocolMapper
org.keycloak.protocol.saml.mappers.SAMLAudienceResolveProtocolMapper org.keycloak.protocol.saml.mappers.SAMLAudienceResolveProtocolMapper
org.keycloak.protocol.oidc.mappers.ClaimsParameterTokenMapper org.keycloak.protocol.oidc.mappers.ClaimsParameterTokenMapper

View file

@ -150,6 +150,25 @@
</artifactItems> </artifactItems>
</configuration> </configuration>
</execution> </execution>
<execution>
<id>deploy-testsuite-providers-deployment</id>
<phase>process-resources</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.keycloak.testsuite</groupId>
<artifactId>integration-arquillian-testsuite-providers-deployment</artifactId>
<version>${project.version}</version>
<type>jar</type>
<overWrite>false</overWrite>
<outputDirectory>${auth.server.home}/standalone/deployments</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>

View file

@ -201,6 +201,14 @@
<overWrite>false</overWrite> <overWrite>false</overWrite>
<outputDirectory>${auth.server.home}/providers</outputDirectory> <outputDirectory>${auth.server.home}/providers</outputDirectory>
</artifactItem> </artifactItem>
<artifactItem>
<groupId>org.keycloak.testsuite</groupId>
<artifactId>integration-arquillian-testsuite-providers-deployment</artifactId>
<version>${project.version}</version>
<type>jar</type>
<overWrite>false</overWrite>
<outputDirectory>${auth.server.home}/providers</outputDirectory>
</artifactItem>
</artifactItems> </artifactItems>
</configuration> </configuration>
</execution> </execution>

View file

@ -31,6 +31,7 @@
<modules> <modules>
<module>testsuite-providers</module> <module>testsuite-providers</module>
<module>testsuite-providers-deployment</module>
</modules> </modules>
</project> </project>

View file

@ -0,0 +1,33 @@
<?xml version="1.0"?>
<!--
~ Copyright 2016 Red Hat, Inc. and/or its affiliates
~ and other 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.
-->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.keycloak.testsuite</groupId>
<artifactId>integration-arquillian-servers-auth-server-services</artifactId>
<version>999-SNAPSHOT</version>
</parent>
<artifactId>integration-arquillian-testsuite-providers-deployment</artifactId>
<name>Auth Server Services - Testsuite Providers Deployment</name>
</project>

View file

@ -0,0 +1,144 @@
{
"authenticators": [
{
"fileName": "scripts/auth-example.js"
},
{
"fileName": "scripts/auth-session.js"
}
],
"mappers": [
{
"fileName": "scripts/test-script-mapper1.js"
},
{
"fileName": "scripts/test-script-mapper2.js"
},
{
"fileName": "scripts/test-script-mapper3.js"
},
{
"fileName": "scripts/test-bad-script-mapper3.js"
}
],
"policies": [
{
"name": "Default Policy",
"fileName": "scripts/default-policy.js",
"description": "A policy that grants access only for users within this realm"
},
{
"name": "Only Owner Policy",
"fileName": "scripts/only-owner-policy.js",
"description": "Defines that only the resource owner is allowed to do something"
},
{
"name": "Only From a Specific Client Address",
"fileName": "scripts/only-from-specific-address-policy.js",
"description": "Defines that only clients from a specific address can do something"
},
{
"name": "Only From @keycloak.org or Admin",
"fileName": "scripts/only-from-specific-domain-or-admin-policy.js",
"description": "Defines that only users from @keycloak.org"
},
{
"name": "Claim A Policy",
"fileName": "scripts/add-claim-a-policy.js"
},
{
"name": "Policy Claim B",
"fileName": "scripts/add-claim-b-policy.js"
},
{
"name": "Policy Claim C",
"fileName": "scripts/add-claim-c-policy.js"
},
{
"name": "Deny Policy",
"fileName": "scripts/always-deny-policy.js"
},
{
"name": "Deny Policy With Claim",
"fileName": "scripts/always-deny-with-claim-policy.js"
},
{
"fileName": "scripts/withdraw-limit-policy.js"
},
{
"fileName": "scripts/resource-visibility-attribute-policy.js"
},
{
"fileName": "scripts/allow-group-name-in-role-policy.js"
},
{
"fileName": "scripts/allow-user-in-group-name-a-policy.js"
},
{
"fileName": "scripts/allow-user-in-group-path-a-policy.js"
},
{
"fileName": "scripts/allow-user-in-group-path-b-policy.js"
},
{
"fileName": "scripts/allow-alice-in-group-child-e-policy.js"
},
{
"fileName": "scripts/allow-alice-in-group-path-a-policy.js"
},
{
"fileName": "scripts/allow-alice-in-group-path-a-no-parent-policy.js"
},
{
"fileName": "scripts/allow-alice-in-group-path-e-policy.js"
},
{
"fileName": "scripts/allow-alice-in-group-name-e-policy.js"
},
{
"fileName": "scripts/allow-marta-in-role-a-policy.js"
},
{
"fileName": "scripts/allow-marta-in-role-b-policy.js"
},
{
"fileName": "scripts/allow-trinity-in-client-roles-policy.js"
},
{
"fileName": "scripts/allow-trinity-in-client-role-b-policy.js"
},
{
"fileName": "scripts/allow-child-group-in-role-policy.js"
},
{
"fileName": "scripts/allow-user-realm-roles-policy.js"
},
{
"fileName": "scripts/allow-user-client-roles-policy.js"
},
{
"fileName": "scripts/allow-user-from-groups-policy.js"
},
{
"fileName": "scripts/allow-user-with-attributes.js"
},
{
"fileName": "scripts/allow-resources-with-attributes.js"
},
{
"fileName": "scripts/check-readonly-context-policy.js"
},
{
"fileName": "scripts/allow-group-in-role-policy.js"
},
{
"fileName": "scripts/deny-from-specific-address-policy.js"
},
{
"fileName": "scripts/allow-value-from-request-claim.js"
},
{
"fileName": "scripts/enforce-withdraw-limit-policy.js"
}
]
}

View file

@ -0,0 +1 @@
$evaluation.getPermission().addClaim('claim-a', 'claim-a');$evaluation.getPermission().addClaim('claim-a', 'claim-a1');$evaluation.grant();

View file

@ -0,0 +1 @@
$evaluation.getPermission().addClaim('claim-b', 'claim-b');$evaluation.grant();

View file

@ -0,0 +1 @@
$evaluation.getPermission().addClaim('claim-c', 'claim-c');$evaluation.grant();

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInGroup('alice', '/Group A/Group B/Group E')) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInGroup('alice', 'Group E')) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (!realm.isUserInGroup('alice', '/Group A', false)) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInGroup('alice', '/Group A')) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInGroup('alice', '/Group E')) {
$evaluation.grant();
}

View file

@ -0,0 +1,6 @@
var realm = $evaluation.getRealm();
if (realm.isGroupInRole('/Group A/Group D', 'role-b')) {
$evaluation.grant();
}

View file

@ -0,0 +1,6 @@
var realm = $evaluation.getRealm();
if (realm.isGroupInRole('/Group A/Group D', 'role-a')) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInGroup('marta', 'Group C')) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInRealmRole('marta', 'role-a')) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInRealmRole('marta', 'role-b')) {
$evaluation.grant();
}

View file

@ -0,0 +1,9 @@
var permission = $evaluation.getPermission();
var resource = permission.getResource();
var attributes = resource.getAttributes();
if (attributes.size() == 2 && attributes.containsKey('a1') && attributes.containsKey('a2') && attributes.get('a1').size() == 2 && attributes.get('a2').get(0).equals('3') && resource.getAttribute('a1').size() == 2 && resource.getSingleAttribute('a2').equals('3')) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInRealmRole('trinity', 'client-role-b')) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInClientRole('trinity', 'role-mapping-client', 'client-role-a')) {
$evaluation.grant();
}

View file

@ -0,0 +1,6 @@
var realm = $evaluation.getRealm();
var roles = realm.getUserClientRoles('trinity', 'role-mapping-client');
if (roles.size() == 1 && roles.contains('client-role-a')) {
$evaluation.grant();
}

View file

@ -0,0 +1,6 @@
var realm = $evaluation.getRealm();
var groups = realm.getUserGroups('jdoe');
if (groups.size() == 2 && groups.contains('/Group A/Group B') && groups.contains('/Group A/Group D')) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInGroup('marta', 'Group A')) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInGroup('marta', '/Group A')) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var realm = $evaluation.getRealm();
if (realm.isUserInGroup('marta', '/Group A/Group B')) {
$evaluation.grant();
}

View file

@ -0,0 +1,7 @@
var realm = $evaluation.getRealm();
var roles = realm.getUserRealmRoles('marta');
if (roles.size() == 2 && roles.contains('uma_authorization') && roles.contains('role-a')) {
$evaluation.grant();
}

View file

@ -0,0 +1,6 @@
var realm = $evaluation.getRealm();
var attributes = realm.getUserAttributes('jdoe');
if (attributes.size() == 6 && attributes.containsKey('a1') && attributes.containsKey('a2') && attributes.get('a1').size() == 2 && attributes.get('a2').get(0).equals('3')) {
$evaluation.grant();
}

View file

@ -0,0 +1,7 @@
var context = $evaluation.getContext();
var attributes = context.getAttributes();
var claim = attributes.getValue('request-claim');
if (claim && claim.asString(0) == 'expected-value') {
$evaluation.grant();
}

View file

@ -0,0 +1,2 @@
$evaluation.getPermission().addClaim('deny-policy', 'deny-policy');
$evaluation.deny();

View file

@ -0,0 +1,10 @@
AuthenticationFlowError = Java.type("org.keycloak.authentication.AuthenticationFlowError");
function authenticate(context) {
LOG.info(script.name + " --> trace auth for: " + user.username);
if (user.username === "fail") {
context.failure(AuthenticationFlowError.INVALID_USER);
return;
}
context.success();
}

View file

@ -0,0 +1,21 @@
AuthenticationFlowError = Java.type("org.keycloak.authentication.AuthenticationFlowError");
function authenticate(context) {
if (authenticationSession.getRealm().getName() != "test") {
context.failure(AuthenticationFlowError.INVALID_CLIENT_SESSION);
return;
}
if (authenticationSession.getClient().getClientId() != "test-app") {
context.failure(AuthenticationFlowError.UNKNOWN_CLIENT);
return;
}
if (authenticationSession.getProtocol() != "openid-connect") {
context.failure(AuthenticationFlowError.INVALID_CLIENT_SESSION);
return;
}
context.success();
}

View file

@ -0,0 +1,5 @@
var contextAttributes = $evaluation.getContext().getAttributes();
if (contextAttributes.containsValue('kc.client.network.ip_address', '127.3.3.3') || contextAttributes.containsValue('kc.client.network.ip_address', '0:0:0:0:0:ffff:7f03:303')) {
$evaluation.grant();
}

View file

@ -0,0 +1,7 @@
var context = $evaluation.getContext();
var attributes = context.getAttributes();
var withdrawalAmount = attributes.getValue('withdrawal.amount');
if (withdrawalAmount && withdrawalAmount.asDouble(0) <= 100) {
$evaluation.grant();
}

View file

@ -0,0 +1,5 @@
var contextAttributes = $evaluation.getContext().getAttributes();
if (contextAttributes.containsValue('kc.client.network.ip_address', '127.0.0.1') || contextAttributes.containsValue('kc.client.network.ip_address', '0:0:0:0:0:0:0:1')) {
$evaluation.grant();
}

View file

@ -0,0 +1,8 @@
var context = $evaluation.getContext();
var identity = context.getIdentity();
var attributes = identity.getAttributes();
var email = attributes.getValue('email').asString(0);
if (identity.hasRealmRole('admin') || email.endsWith('@keycloak.org')) {
$evaluation.grant();
}

View file

@ -0,0 +1,9 @@
var permission = $evaluation.getPermission();
var identity = $evaluation.getContext().getIdentity();
var resource = permission.getResource();
if (resource) {
if (resource.getOwner().equals(identity.getId())) {
$evaluation.grant();
}
}

View file

@ -0,0 +1,13 @@
var createPermission = $evaluation.getPermission();
var resource = createPermission.getResource();
if (resource) {
var attributes = resource.getAttributes();
var visibility = attributes.get('visibility');
if (visibility && "private".equals(visibility.get(0))) {
$evaluation.deny();
} else {
$evaluation.grant();
}
}

View file

@ -0,0 +1,7 @@
var context = $evaluation.getContext();
var attributes = context.getAttributes();
var withdrawValue = attributes.getValue('my.bank.account.withdraw.value');
if (withdrawValue && withdrawValue.asDouble(0) <= 100) {
$evaluation.grant();
}

View file

@ -57,6 +57,12 @@
<groupId>org.wildfly.core</groupId> <groupId>org.wildfly.core</groupId>
<artifactId>wildfly-controller</artifactId> <artifactId>wildfly-controller</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.keycloak.testsuite</groupId>
<artifactId>integration-arquillian-testsuite-providers-deployment</artifactId>
<version>${project.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View file

@ -17,6 +17,8 @@
package org.keycloak.testsuite.arquillian.undertow; package org.keycloak.testsuite.arquillian.undertow;
import static org.keycloak.testsuite.KeycloakServer.registerScriptProviders;
import io.undertow.Undertow; import io.undertow.Undertow;
import io.undertow.server.HttpHandler; import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.PathHandler; import io.undertow.server.handlers.PathHandler;
@ -45,7 +47,7 @@ import org.jboss.shrinkwrap.descriptor.api.Descriptor;
import org.jboss.shrinkwrap.undertow.api.UndertowWebArchive; import org.jboss.shrinkwrap.undertow.api.UndertowWebArchive;
import org.keycloak.common.util.reflections.Reflections; import org.keycloak.common.util.reflections.Reflections;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.services.DefaultKeycloakSessionFactory;
import org.keycloak.services.managers.ApplianceBootstrap; import org.keycloak.services.managers.ApplianceBootstrap;
import org.keycloak.services.resources.KeycloakApplication; import org.keycloak.services.resources.KeycloakApplication;
import org.keycloak.testsuite.JsonConfigProviderFactory; import org.keycloak.testsuite.JsonConfigProviderFactory;
@ -74,7 +76,7 @@ public class KeycloakOnUndertow implements DeployableContainer<KeycloakOnUnderto
private KeycloakUndertowJaxrsServer undertow; private KeycloakUndertowJaxrsServer undertow;
private KeycloakOnUndertowConfiguration configuration; private KeycloakOnUndertowConfiguration configuration;
private KeycloakSessionFactory sessionFactory; private DefaultKeycloakSessionFactory sessionFactory;
Map<String, String> deployedArchivesToContextPath = new ConcurrentHashMap<>(); Map<String, String> deployedArchivesToContextPath = new ConcurrentHashMap<>();
@ -221,7 +223,9 @@ public class KeycloakOnUndertow implements DeployableContainer<KeycloakOnUnderto
DeploymentInfo di = createAuthServerDeploymentInfo(); DeploymentInfo di = createAuthServerDeploymentInfo();
undertow.deploy(di); undertow.deploy(di);
sessionFactory = KeycloakApplication.getSessionFactory(); sessionFactory = (DefaultKeycloakSessionFactory) KeycloakApplication.getSessionFactory();
registerScriptProviders(sessionFactory);
setupDevConfig(); setupDevConfig();

View file

@ -86,12 +86,9 @@
"policies" : [ { "policies" : [ {
"name" : "Default Policy", "name" : "Default Policy",
"description" : "A policy that grants access only for users within this realm", "description" : "A policy that grants access only for users within this realm",
"type" : "js", "type": "script-scripts/default-policy.js",
"logic" : "POSITIVE", "logic" : "POSITIVE",
"decisionStrategy" : "AFFIRMATIVE", "decisionStrategy" : "AFFIRMATIVE"
"config" : {
"code" : "// by default, grants any permission associated with this policy\n$evaluation.grant();\n"
}
}, { }, {
"name" : "Default Permission", "name" : "Default Permission",
"description" : "A permission that applies to the default resource type", "description" : "A permission that applies to the default resource type",

View file

@ -55,12 +55,9 @@
{ {
"name": "Only Owner Policy", "name": "Only Owner Policy",
"description": "Defines that only the resource owner is allowed to do something", "description": "Defines that only the resource owner is allowed to do something",
"type": "js", "type": "script-scripts/only-owner-policy.js",
"logic": "POSITIVE", "logic": "POSITIVE",
"decisionStrategy": "UNANIMOUS", "decisionStrategy": "UNANIMOUS"
"config": {
"code": "var permission = $evaluation.getPermission();\nvar identity = $evaluation.getContext().getIdentity();\nvar resource = permission.getResource();\nif (resource) {\nif (resource.getOwner().equals(identity.getId())) {\n$evaluation.grant();\n}}"
}
}, },
{ {
"name": "Any Admin Policy", "name": "Any Admin Policy",
@ -87,13 +84,16 @@
{ {
"name": "Only From a Specific Client Address", "name": "Only From a Specific Client Address",
"description": "Defines that only clients from a specific address can do something", "description": "Defines that only clients from a specific address can do something",
"type": "js", "type": "script-scripts/only-from-specific-address-policy.js",
"logic": "POSITIVE", "logic": "POSITIVE",
"decisionStrategy": "UNANIMOUS", "decisionStrategy": "UNANIMOUS"
"config": { },
"applyPolicies": "[]", {
"code": "var contextAttributes = $evaluation.getContext().getAttributes();\n\nif (contextAttributes.containsValue('kc.client.network.ip_address', '127.0.0.1') || contextAttributes.containsValue('kc.client.network.ip_address', '0:0:0:0:0:0:0:1')) {\n $evaluation.grant();\n}" "name": "Deny From a Specific Client Address",
} "description": "Defines that only clients from a specific address can do something",
"type": "script-scripts/deny-from-specific-address-policy.js",
"logic": "POSITIVE",
"decisionStrategy": "UNANIMOUS"
}, },
{ {
"name": "Administration Policy", "name": "Administration Policy",
@ -118,13 +118,9 @@
{ {
"name": "Only From @keycloak.org or Admin", "name": "Only From @keycloak.org or Admin",
"description": "Defines that only users from @keycloak.org", "description": "Defines that only users from @keycloak.org",
"type": "js", "type": "script-scripts/only-from-specific-domain-or-admin-policy.js",
"logic": "POSITIVE", "logic": "POSITIVE",
"decisionStrategy": "UNANIMOUS", "decisionStrategy": "UNANIMOUS"
"config": {
"applyPolicies": "[]",
"code": "var context = $evaluation.getContext();\nvar identity = context.getIdentity();\nvar attributes = identity.getAttributes();\nvar email = attributes.getValue('email').asString(0);\n\nif (identity.hasRealmRole('admin') || email.endsWith('@keycloak.org')) {\n $evaluation.grant();\n}"
}
}, },
{ {
"name": "Album Resource Permission", "name": "Album Resource Permission",
@ -185,12 +181,9 @@
}, },
{ {
"name": "Deny Policy", "name": "Deny Policy",
"type": "js", "type": "script-scripts/always-deny-policy.js",
"logic": "POSITIVE", "logic": "POSITIVE",
"decisionStrategy": "UNANIMOUS", "decisionStrategy": "UNANIMOUS"
"config": {
"code": "// by default, grants any permission associated with this policy\n$evaluation.deny();"
}
}, },
{ {
"name": "Protected Scope A Permission", "name": "Protected Scope A Permission",

View file

@ -167,12 +167,9 @@
}, },
{ {
"name": "Deny Policy", "name": "Deny Policy",
"type": "js", "type": "script-scripts/always-deny-policy.js",
"logic": "POSITIVE", "logic": "POSITIVE",
"decisionStrategy": "UNANIMOUS", "decisionStrategy": "UNANIMOUS"
"config": {
"code": "// by default, grants any permission associated with this policy\n$evaluation.deny();"
}
}, },
{ {
"name": "Resource A Read Permission", "name": "Resource A Read Permission",
@ -219,12 +216,9 @@
{ {
"name": "Request Claim Policy", "name": "Request Claim Policy",
"description": "A policy that grants access based on claims from an http request", "description": "A policy that grants access based on claims from an http request",
"type": "js", "type": "script-scripts/allow-value-from-request-claim.js",
"logic": "POSITIVE", "logic": "POSITIVE",
"decisionStrategy": "UNANIMOUS", "decisionStrategy": "UNANIMOUS"
"config": {
"code": "var context = $evaluation.getContext();\nvar attributes = context.getAttributes();\nvar claim = attributes.getValue('request-claim');\n\nif (claim && claim.asString(0) == 'expected-value') {\n $evaluation.grant();\n}"
}
}, },
{ {
"name": "Resource Protected With Body Claim Permission", "name": "Resource Protected With Body Claim Permission",

View file

@ -137,22 +137,15 @@
"policies": [ "policies": [
{ {
"name": "Default Policy", "name": "Default Policy",
"type": "js", "type": "script-scripts/default-policy.js",
"logic": "POSITIVE", "logic": "POSITIVE",
"decisionStrategy": "AFFIRMATIVE", "decisionStrategy": "AFFIRMATIVE"
"config": {
"code": "// by default, grants any permission associated with this policy\n$evaluation.grant();\n",
"applyPolicies": "[]"
}
}, },
{ {
"name": "Deny Policy", "name": "Deny Policy",
"type": "js", "type": "script-scripts/default-policy.js",
"logic": "NEGATIVE", "logic": "NEGATIVE",
"decisionStrategy": "UNANIMOUS", "decisionStrategy": "UNANIMOUS"
"config": {
"code": "$evaluation.grant();"
}
}, },
{ {
"name": "Pattern 3 Permission", "name": "Pattern 3 Permission",

View file

@ -72,6 +72,11 @@
<artifactId>integration-arquillian-testsuite-providers</artifactId> <artifactId>integration-arquillian-testsuite-providers</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.keycloak.testsuite</groupId>
<artifactId>integration-arquillian-testsuite-providers-deployment</artifactId>
<version>${project.version}</version>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>

View file

@ -120,6 +120,7 @@ public class AuthServerTestEnricher {
private Event<StopContainer> stopContainerEvent; private Event<StopContainer> stopContainerEvent;
private JavaArchive testsuiteProvidersArchive; private JavaArchive testsuiteProvidersArchive;
private JavaArchive testsuiteProvidersDeploymentArchive;
private String currentContainerName; private String currentContainerName;
public static final String AUTH_SERVER_CONTAINER_DEFAULT = "auth-server-undertow"; public static final String AUTH_SERVER_CONTAINER_DEFAULT = "auth-server-undertow";
@ -423,8 +424,16 @@ public class AuthServerTestEnricher {
.asSingleFile() .asSingleFile()
).as(JavaArchive.class) ).as(JavaArchive.class)
.addAsManifestResource("jboss-deployment-structure.xml"); .addAsManifestResource("jboss-deployment-structure.xml");
event.getDeployableContainer().deploy(testsuiteProvidersArchive); event.getDeployableContainer().deploy(testsuiteProvidersArchive);
this.testsuiteProvidersDeploymentArchive = ShrinkWrap.create(ZipImporter.class, "testsuiteProvidersDeployment.jar")
.importFrom(Maven.configureResolverViaPlugin()
.resolve("org.keycloak.testsuite:integration-arquillian-testsuite-providers-deployment")
.withoutTransitivity()
.asSingleFile()
).as(JavaArchive.class)
.addAsManifestResource("jboss-deployment-structure.xml");
event.getDeployableContainer().deploy(testsuiteProvidersDeploymentArchive);
} }
} }
@ -432,6 +441,9 @@ public class AuthServerTestEnricher {
if (testsuiteProvidersArchive != null) { if (testsuiteProvidersArchive != null) {
event.getDeployableContainer().undeploy(testsuiteProvidersArchive); event.getDeployableContainer().undeploy(testsuiteProvidersArchive);
} }
if (testsuiteProvidersDeploymentArchive != null) {
event.getDeployableContainer().undeploy(testsuiteProvidersDeploymentArchive);
}
} }
public void runPreMigrationTask(@Observes(precedence = 2) StartSuiteContainers event) throws Exception { public void runPreMigrationTask(@Observes(precedence = 2) StartSuiteContainers event) throws Exception {

View file

@ -151,6 +151,7 @@ public class KeycloakQuarkusServerDeployableContainer implements DeployableConta
List<String> commands = new ArrayList<>(); List<String> commands = new ArrayList<>();
commands.add("./kc.sh"); commands.add("./kc.sh");
commands.add("-v");
commands.add("start"); commands.add("start");
commands.add("--http-enabled=true"); commands.add("--http-enabled=true");

View file

@ -20,7 +20,6 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.keycloak.common.Profile.Feature.AUTHORIZATION; import static org.keycloak.common.Profile.Feature.AUTHORIZATION;
import static org.keycloak.common.Profile.Feature.UPLOAD_SCRIPTS;
import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith; import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith;
import static org.keycloak.testsuite.util.WaitUtils.waitForPageToLoad; import static org.keycloak.testsuite.util.WaitUtils.waitForPageToLoad;
import static org.keycloak.testsuite.utils.io.IOUtil.loadJson; import static org.keycloak.testsuite.utils.io.IOUtil.loadJson;
@ -86,7 +85,6 @@ import org.wildfly.extras.creaper.core.online.operations.admin.Administration;
/** /**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a> * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/ */
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
public abstract class AbstractBasePhotozExampleAdapterTest extends AbstractPhotozJavascriptExecutorTest { public abstract class AbstractBasePhotozExampleAdapterTest extends AbstractPhotozJavascriptExecutorTest {
protected static final String RESOURCE_SERVER_ID = "photoz-restful-api"; protected static final String RESOURCE_SERVER_ID = "photoz-restful-api";

View file

@ -48,7 +48,6 @@ import java.util.List;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.keycloak.common.Profile.Feature.AUTHORIZATION; import static org.keycloak.common.Profile.Feature.AUTHORIZATION;
import static org.keycloak.common.Profile.Feature.UPLOAD_SCRIPTS;
import static org.keycloak.testsuite.util.WaitUtils.waitForPageToLoad; import static org.keycloak.testsuite.util.WaitUtils.waitForPageToLoad;
import static org.keycloak.testsuite.utils.io.IOUtil.loadJson; import static org.keycloak.testsuite.utils.io.IOUtil.loadJson;
import static org.keycloak.testsuite.utils.io.IOUtil.loadRealm; import static org.keycloak.testsuite.utils.io.IOUtil.loadRealm;
@ -57,7 +56,6 @@ import static org.keycloak.testsuite.util.WaitUtils.waitUntilElement;
/** /**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a> * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/ */
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
public abstract class AbstractBaseServletAuthzAdapterTest extends AbstractExampleAdapterTest { public abstract class AbstractBaseServletAuthzAdapterTest extends AbstractExampleAdapterTest {
protected static final String REALM_NAME = "servlet-authz"; protected static final String REALM_NAME = "servlet-authz";

View file

@ -27,10 +27,13 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.junit.Test; import org.junit.Test;
@ -137,11 +140,10 @@ public abstract class AbstractPhotozExampleAdapterTest extends AbstractBasePhoto
log.debug("Changing codes \"127.0.0.1\" to \"127.3.3.3\" of \"Only From a Specific Client Address\" policies."); log.debug("Changing codes \"127.0.0.1\" to \"127.3.3.3\" of \"Only From a Specific Client Address\" policies.");
for (PolicyRepresentation policy : getAuthorizationResource().policies().policies()) { for (PolicyRepresentation policy : getAuthorizationResource().policies().policies()) {
if ("Only From a Specific Client Address".equals(policy.getName())) { if ("Administration Policy".equals(policy.getName())) {
String code = policy.getConfig().get("code") policy.setPolicies(new HashSet<>());
.replaceAll("127.0.0.1", "127.3.3.3") policy.getPolicies().add("Any Admin Policy");
.replaceAll("0:0:0:0:0:0:0:1", "0:0:0:0:0:ffff:7f03:303"); policy.getPolicies().add("Deny From a Specific Client Address");
policy.getConfig().put("code", code);
getAuthorizationResource().policies().policy(policy.getId()).update(policy); getAuthorizationResource().policies().policy(policy.getId()).update(policy);
} }
} }

View file

@ -16,8 +16,6 @@
*/ */
package org.keycloak.testsuite.adapter.example.authorization; package org.keycloak.testsuite.adapter.example.authorization;
import static org.keycloak.common.Profile.Feature.UPLOAD_SCRIPTS;
import java.io.File; import java.io.File;
import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.Deployment;
@ -37,7 +35,6 @@ import org.keycloak.testsuite.utils.arquillian.ContainerConstants;
@AppServerContainer(ContainerConstants.APP_SERVER_EAP71) @AppServerContainer(ContainerConstants.APP_SERVER_EAP71)
@AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT8) @AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT8)
@AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT9) @AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT9)
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
public class ServletPolicyEnforcerLifespanTest extends AbstractServletPolicyEnforcerTest { public class ServletPolicyEnforcerLifespanTest extends AbstractServletPolicyEnforcerTest {
@Deployment(name = RESOURCE_SERVER_ID, managed = false) @Deployment(name = RESOURCE_SERVER_ID, managed = false)

View file

@ -16,12 +16,9 @@
*/ */
package org.keycloak.testsuite.adapter.example.authorization; package org.keycloak.testsuite.adapter.example.authorization;
import static org.keycloak.common.Profile.Feature.UPLOAD_SCRIPTS;
import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.keycloak.testsuite.arquillian.annotation.AppServerContainer; import org.keycloak.testsuite.arquillian.annotation.AppServerContainer;
import org.keycloak.testsuite.arquillian.annotation.EnableFeature;
import org.keycloak.testsuite.utils.arquillian.ContainerConstants; import org.keycloak.testsuite.utils.arquillian.ContainerConstants;
/** /**
@ -35,7 +32,6 @@ import org.keycloak.testsuite.utils.arquillian.ContainerConstants;
@AppServerContainer(ContainerConstants.APP_SERVER_EAP71) @AppServerContainer(ContainerConstants.APP_SERVER_EAP71)
@AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT8) @AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT8)
@AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT9) @AppServerContainer(ContainerConstants.APP_SERVER_TOMCAT9)
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
public class ServletPolicyEnforcerTest extends AbstractServletPolicyEnforcerTest { public class ServletPolicyEnforcerTest extends AbstractServletPolicyEnforcerTest {
@Deployment(name = RESOURCE_SERVER_ID, managed = false) @Deployment(name = RESOURCE_SERVER_ID, managed = false)

View file

@ -54,7 +54,6 @@ import static junit.framework.TestCase.assertNotNull;
import org.junit.Assume; import org.junit.Assume;
import org.keycloak.testsuite.util.DroneUtils; import org.keycloak.testsuite.util.DroneUtils;
import static org.keycloak.common.Profile.Feature.UPLOAD_SCRIPTS;
import static org.keycloak.testsuite.utils.io.IOUtil.loadRealm; import static org.keycloak.testsuite.utils.io.IOUtil.loadRealm;
import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith; import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith;
import static org.keycloak.testsuite.util.WaitUtils.waitForPageToLoad; import static org.keycloak.testsuite.util.WaitUtils.waitForPageToLoad;
@ -75,7 +74,6 @@ import static org.keycloak.testsuite.util.WaitUtils.waitUntilElement;
@AppServerContainer(ContainerConstants.APP_SERVER_EAP) @AppServerContainer(ContainerConstants.APP_SERVER_EAP)
@AppServerContainer(ContainerConstants.APP_SERVER_EAP6) @AppServerContainer(ContainerConstants.APP_SERVER_EAP6)
@AppServerContainer(ContainerConstants.APP_SERVER_EAP71) @AppServerContainer(ContainerConstants.APP_SERVER_EAP71)
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
@DisableFeature(value = Profile.Feature.ACCOUNT2, skipRestart = true) // TODO remove this (KEYCLOAK-16228) @DisableFeature(value = Profile.Feature.ACCOUNT2, skipRestart = true) // TODO remove this (KEYCLOAK-16228)
public class CorsExampleAdapterTest extends AbstractExampleAdapterTest { public class CorsExampleAdapterTest extends AbstractExampleAdapterTest {

View file

@ -18,7 +18,6 @@
package org.keycloak.testsuite.admin.client.authorization; package org.keycloak.testsuite.admin.client.authorization;
import org.junit.After; import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.keycloak.admin.client.resource.AuthorizationResource; import org.keycloak.admin.client.resource.AuthorizationResource;
import org.keycloak.admin.client.resource.ClientResource; import org.keycloak.admin.client.resource.ClientResource;
@ -30,7 +29,6 @@ import org.keycloak.representations.idm.authorization.ResourceServerRepresentati
import org.keycloak.representations.idm.authorization.ScopeRepresentation; import org.keycloak.representations.idm.authorization.ScopeRepresentation;
import org.keycloak.testsuite.ProfileAssume; import org.keycloak.testsuite.ProfileAssume;
import org.keycloak.testsuite.admin.client.AbstractClientTest; import org.keycloak.testsuite.admin.client.AbstractClientTest;
import org.keycloak.testsuite.arquillian.annotation.EnableFeature;
import org.keycloak.testsuite.util.ClientBuilder; import org.keycloak.testsuite.util.ClientBuilder;
import org.keycloak.testsuite.util.RealmBuilder; import org.keycloak.testsuite.util.RealmBuilder;
import org.keycloak.testsuite.util.UserBuilder; import org.keycloak.testsuite.util.UserBuilder;
@ -39,14 +37,12 @@ import javax.ws.rs.core.Response;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.keycloak.common.Profile.Feature.AUTHORIZATION; import static org.keycloak.common.Profile.Feature.AUTHORIZATION;
import static org.keycloak.common.Profile.Feature.UPLOAD_SCRIPTS;
import java.util.List; import java.util.List;
/** /**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a> * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/ */
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
public abstract class AbstractAuthorizationTest extends AbstractClientTest { public abstract class AbstractAuthorizationTest extends AbstractClientTest {
protected static final String RESOURCE_SERVER_CLIENT_ID = "resource-server-test"; protected static final String RESOURCE_SERVER_CLIENT_ID = "resource-server-test";

View file

@ -32,6 +32,7 @@ import org.keycloak.representations.idm.authorization.JSPolicyRepresentation;
import org.keycloak.representations.idm.authorization.PolicyRepresentation; import org.keycloak.representations.idm.authorization.PolicyRepresentation;
import org.keycloak.representations.idm.authorization.ResourceRepresentation; import org.keycloak.representations.idm.authorization.ResourceRepresentation;
import org.keycloak.representations.idm.authorization.ResourceServerRepresentation; import org.keycloak.representations.idm.authorization.ResourceServerRepresentation;
import org.keycloak.representations.idm.authorization.RolePolicyRepresentation;
import java.util.List; import java.util.List;
@ -64,12 +65,12 @@ public class AuthorizationTest extends AbstractAuthorizationTest {
serviceAccountRoles = realm.users().get(serviceAccount.getId()).roles().clientLevel(resourceServer.getId()).listEffective(); serviceAccountRoles = realm.users().get(serviceAccount.getId()).roles().clientLevel(resourceServer.getId()).listEffective();
Assert.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName()))); Assert.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName())));
JSPolicyRepresentation policy = new JSPolicyRepresentation(); RolePolicyRepresentation policy = new RolePolicyRepresentation();
policy.setName("should be removed"); policy.setName("should be removed");
policy.setCode(""); policy.addRole("uma_authorization");
clientResource.authorization().policies().js().create(policy); clientResource.authorization().policies().role().create(policy);
List<ResourceRepresentation> defaultResources = clientResource.authorization().resources().resources(); List<ResourceRepresentation> defaultResources = clientResource.authorization().resources().resources();

View file

@ -54,7 +54,7 @@ import static org.junit.Assert.assertTrue;
*/ */
public class GenericPolicyManagementTest extends AbstractAuthorizationTest { public class GenericPolicyManagementTest extends AbstractAuthorizationTest {
private static final String[] EXPECTED_BUILTIN_POLICY_PROVIDERS = {"test", "user", "role", "js", "time", "aggregate", "scope", "resource"}; private static final String[] EXPECTED_BUILTIN_POLICY_PROVIDERS = {"test", "user", "role", "time", "aggregate", "scope", "resource"};
@Test @Test
public void testCreate() { public void testCreate() {

View file

@ -18,28 +18,23 @@ package org.keycloak.testsuite.admin.client.authorization;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.keycloak.common.Profile.Feature.UPLOAD_SCRIPTS;
import java.util.Collections; import java.util.Collections;
import javax.ws.rs.NotFoundException; import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.keycloak.admin.client.resource.AuthorizationResource; import org.keycloak.admin.client.resource.AuthorizationResource;
import org.keycloak.admin.client.resource.JSPoliciesResource; import org.keycloak.admin.client.resource.JSPoliciesResource;
import org.keycloak.admin.client.resource.JSPolicyResource; import org.keycloak.admin.client.resource.JSPolicyResource;
import org.keycloak.common.Profile;
import org.keycloak.representations.idm.authorization.DecisionStrategy; import org.keycloak.representations.idm.authorization.DecisionStrategy;
import org.keycloak.representations.idm.authorization.JSPolicyRepresentation; import org.keycloak.representations.idm.authorization.JSPolicyRepresentation;
import org.keycloak.representations.idm.authorization.Logic; import org.keycloak.representations.idm.authorization.Logic;
import org.keycloak.testsuite.arquillian.annotation.EnableFeature;
/** /**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a> * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/ */
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
public class JSPolicyManagementTest extends AbstractPolicyManagementTest { public class JSPolicyManagementTest extends AbstractPolicyManagementTest {
@Test @Test
@ -51,7 +46,7 @@ public class JSPolicyManagementTest extends AbstractPolicyManagementTest {
representation.setDescription("description"); representation.setDescription("description");
representation.setDecisionStrategy(DecisionStrategy.CONSENSUS); representation.setDecisionStrategy(DecisionStrategy.CONSENSUS);
representation.setLogic(Logic.NEGATIVE); representation.setLogic(Logic.NEGATIVE);
representation.setCode("$evaluation.grant();"); representation.setType("script-scripts/default-policy.js");
assertCreated(authorization, representation); assertCreated(authorization, representation);
} }
@ -65,7 +60,7 @@ public class JSPolicyManagementTest extends AbstractPolicyManagementTest {
representation.setDescription("description"); representation.setDescription("description");
representation.setDecisionStrategy(DecisionStrategy.CONSENSUS); representation.setDecisionStrategy(DecisionStrategy.CONSENSUS);
representation.setLogic(Logic.NEGATIVE); representation.setLogic(Logic.NEGATIVE);
representation.setCode("$evaluation.grant();"); representation.setType("script-scripts/default-policy.js");
assertCreated(authorization, representation); assertCreated(authorization, representation);
@ -73,7 +68,6 @@ public class JSPolicyManagementTest extends AbstractPolicyManagementTest {
representation.setDescription("changed"); representation.setDescription("changed");
representation.setDecisionStrategy(DecisionStrategy.AFFIRMATIVE); representation.setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);
representation.setLogic(Logic.POSITIVE); representation.setLogic(Logic.POSITIVE);
representation.setCode("$evaluation.deny()");
JSPoliciesResource policies = authorization.policies().js(); JSPoliciesResource policies = authorization.policies().js();
JSPolicyResource permission = policies.findById(representation.getId()); JSPolicyResource permission = policies.findById(representation.getId());
@ -88,7 +82,7 @@ public class JSPolicyManagementTest extends AbstractPolicyManagementTest {
JSPolicyRepresentation representation = new JSPolicyRepresentation(); JSPolicyRepresentation representation = new JSPolicyRepresentation();
representation.setName("Test Delete Policy"); representation.setName("Test Delete Policy");
representation.setCode("$evaluation.grant()"); representation.setType("script-scripts/default-policy.js");
JSPoliciesResource policies = authorization.policies().js(); JSPoliciesResource policies = authorization.policies().js();
try (Response response = policies.create(representation)) { try (Response response = policies.create(representation)) {
@ -120,6 +114,6 @@ public class JSPolicyManagementTest extends AbstractPolicyManagementTest {
private void assertRepresentation(JSPolicyRepresentation representation, JSPolicyResource permission) { private void assertRepresentation(JSPolicyRepresentation representation, JSPolicyResource permission) {
JSPolicyRepresentation actual = permission.toRepresentation(); JSPolicyRepresentation actual = permission.toRepresentation();
assertRepresentation(representation, actual, () -> permission.resources(), () -> Collections.emptyList(), () -> permission.associatedPolicies()); assertRepresentation(representation, actual, () -> permission.resources(), () -> Collections.emptyList(), () -> permission.associatedPolicies());
assertEquals(representation.getCode(), actual.getCode()); assertEquals(representation.getType(), actual.getType());
} }
} }

View file

@ -21,7 +21,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.keycloak.common.Profile.Feature.AUTHORIZATION; import static org.keycloak.common.Profile.Feature.AUTHORIZATION;
import static org.keycloak.common.Profile.Feature.UPLOAD_SCRIPTS;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@ -82,7 +81,6 @@ import org.keycloak.testsuite.util.UserBuilder;
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a> * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/ */
@AuthServerContainerExclude(AuthServer.REMOTE) @AuthServerContainerExclude(AuthServer.REMOTE)
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
public class PolicyEnforcerClaimsTest extends AbstractKeycloakTest { public class PolicyEnforcerClaimsTest extends AbstractKeycloakTest {
protected static final String REALM_NAME = "authz-test"; protected static final String REALM_NAME = "authz-test";
@ -335,17 +333,7 @@ public class PolicyEnforcerClaimsTest extends AbstractKeycloakTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName("Withdrawal Limit Policy"); policy.setName("Withdrawal Limit Policy");
policy.setType("script-scripts/enforce-withdraw-limit-policy.js");
StringBuilder code = new StringBuilder();
code.append("var context = $evaluation.getContext();");
code.append("var attributes = context.getAttributes();");
code.append("var withdrawalAmount = attributes.getValue('withdrawal.amount');");
code.append("if (withdrawalAmount && withdrawalAmount.asDouble(0) <= 100) {");
code.append(" $evaluation.grant();");
code.append("}");
policy.setCode(code.toString());
clientResource.authorization().policies().js().create(policy).close(); clientResource.authorization().policies().js().create(policy).close();

View file

@ -22,7 +22,6 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.keycloak.common.Profile.Feature.AUTHORIZATION; import static org.keycloak.common.Profile.Feature.AUTHORIZATION;
import static org.keycloak.common.Profile.Feature.UPLOAD_SCRIPTS;
import javax.security.cert.X509Certificate; import javax.security.cert.X509Certificate;
import javax.ws.rs.HttpMethod; import javax.ws.rs.HttpMethod;
@ -98,7 +97,6 @@ import org.keycloak.testsuite.util.UserBuilder;
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a> * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/ */
@AuthServerContainerExclude(AuthServer.REMOTE) @AuthServerContainerExclude(AuthServer.REMOTE)
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
public class PolicyEnforcerTest extends AbstractKeycloakTest { public class PolicyEnforcerTest extends AbstractKeycloakTest {
private static final String RESOURCE_SERVER_CLIENT_ID = "resource-server-test"; private static final String RESOURCE_SERVER_CLIENT_ID = "resource-server-test";
@ -700,12 +698,7 @@ public class PolicyEnforcerTest extends AbstractKeycloakTest {
JSPolicyRepresentation jsPolicy = new JSPolicyRepresentation(); JSPolicyRepresentation jsPolicy = new JSPolicyRepresentation();
jsPolicy.setName("Always Grant Policy"); jsPolicy.setName("Always Grant Policy");
jsPolicy.setType("script-scripts/default-policy.js");
StringBuilder code = new StringBuilder();
code.append("$evaluation.grant();");
jsPolicy.setCode(code.toString());
clientResource.authorization().policies().js().create(jsPolicy).close(); clientResource.authorization().policies().js().create(jsPolicy).close();
@ -731,12 +724,7 @@ public class PolicyEnforcerTest extends AbstractKeycloakTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName("Always Deny Policy"); policy.setName("Always Deny Policy");
policy.setType("script-scripts/always-deny-policy.js");
StringBuilder code = new StringBuilder();
code.append("$evaluation.deny();");
policy.setCode(code.toString());
clientResource.authorization().policies().js().create(policy).close(); clientResource.authorization().policies().js().create(policy).close();

View file

@ -67,7 +67,6 @@ import org.keycloak.partialimport.ResourceType;
import org.keycloak.representations.idm.authorization.ResourceServerRepresentation; import org.keycloak.representations.idm.authorization.ResourceServerRepresentation;
import static org.keycloak.common.Profile.Feature.AUTHORIZATION; import static org.keycloak.common.Profile.Feature.AUTHORIZATION;
import static org.keycloak.common.Profile.Feature.UPLOAD_SCRIPTS;
import static org.keycloak.testsuite.auth.page.AuthRealm.MASTER; import static org.keycloak.testsuite.auth.page.AuthRealm.MASTER;
import org.keycloak.util.JsonSerialization; import org.keycloak.util.JsonSerialization;
@ -468,7 +467,6 @@ public class PartialImportTest extends AbstractAuthTest {
} }
} }
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
@Test @Test
public void testAddClientsWithServiceAccountsAndAuthorization() throws IOException { public void testAddClientsWithServiceAccountsAndAuthorization() throws IOException {
setFail(); setFail();
@ -622,7 +620,6 @@ public class PartialImportTest extends AbstractAuthTest {
testSkip(); testSkip();
} }
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
@Test @Test
public void testAddClientsSkipWithServiceAccountsAndAuthorization() throws IOException { public void testAddClientsSkipWithServiceAccountsAndAuthorization() throws IOException {
addClients(true); addClients(true);
@ -679,7 +676,6 @@ public class PartialImportTest extends AbstractAuthTest {
testOverwrite(); testOverwrite();
} }
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
@Test @Test
public void testAddClientsOverwriteWithServiceAccountsAndAuthorization() throws IOException { public void testAddClientsOverwriteWithServiceAccountsAndAuthorization() throws IOException {
addClients(true); addClients(true);
@ -691,7 +687,6 @@ public class PartialImportTest extends AbstractAuthTest {
assertEquals(NUM_ENTITIES * 2, results.getOverwritten()); assertEquals(NUM_ENTITIES * 2, results.getOverwritten());
} }
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
@Test @Test
public void testAddClientsOverwriteServiceAccountsWithNoServiceAccounts() throws IOException { public void testAddClientsOverwriteServiceAccountsWithNoServiceAccounts() throws IOException {
addClients(true); addClients(true);
@ -767,7 +762,6 @@ public class PartialImportTest extends AbstractAuthTest {
assertEquals(NUM_ENTITIES * NUM_RESOURCE_TYPES, results.getSkipped()); assertEquals(NUM_ENTITIES * NUM_RESOURCE_TYPES, results.getSkipped());
} }
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
@Test @Test
public void testEverythingSkipWithServiceAccounts() throws IOException { public void testEverythingSkipWithServiceAccounts() throws IOException {
setSkip(); setSkip();
@ -784,7 +778,6 @@ public class PartialImportTest extends AbstractAuthTest {
assertEquals(NUM_ENTITIES * NUM_RESOURCE_TYPES, results.getOverwritten()); assertEquals(NUM_ENTITIES * NUM_RESOURCE_TYPES, results.getOverwritten());
} }
@EnableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
@Test @Test
public void testEverythingOverwriteWithServiceAccounts() throws IOException { public void testEverythingOverwriteWithServiceAccounts() throws IOException {
setOverwrite(); setOverwrite();

View file

@ -14,7 +14,6 @@ import static org.keycloak.common.Profile.Feature.AUTHORIZATION;
/** /**
* @author mhajas * @author mhajas
*/ */
@EnableFeature(value = Profile.Feature.UPLOAD_SCRIPTS, skipRestart = true)
public abstract class AbstractAuthzTest extends AbstractKeycloakTest { public abstract class AbstractAuthzTest extends AbstractKeycloakTest {
@BeforeClass @BeforeClass

View file

@ -118,7 +118,7 @@ public class AuthorizationAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName("Default Policy"); policy.setName("Default Policy");
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
response = authorization.policies().js().create(policy); response = authorization.policies().js().create(policy);
response.close(); response.close();

View file

@ -92,14 +92,14 @@ public class AuthorizationTest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName("Grant Policy"); policy.setName("Grant Policy");
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
policy = new JSPolicyRepresentation(); policy = new JSPolicyRepresentation();
policy.setName("Deny Policy"); policy.setName("Deny Policy");
policy.setCode("$evaluation.deny();"); policy.setType("script-scripts/always-deny-policy.js");
} }
@After @After

View file

@ -424,7 +424,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName("Only Owner Policy"); policy.setName("Only Owner Policy");
policy.setCode("if ($evaluation.getContext().getIdentity().getId() == $evaluation.getPermission().getResource().getOwner()) {$evaluation.grant();}"); policy.setType("script-scripts/only-owner-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -563,7 +563,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -614,7 +614,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -670,7 +670,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -769,7 +769,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -809,7 +809,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -891,7 +891,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -981,14 +981,14 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation grantPolicy = new JSPolicyRepresentation(); JSPolicyRepresentation grantPolicy = new JSPolicyRepresentation();
grantPolicy.setName(KeycloakModelUtils.generateId()); grantPolicy.setName(KeycloakModelUtils.generateId());
grantPolicy.setCode("$evaluation.grant();"); grantPolicy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(grantPolicy).close(); authorization.policies().js().create(grantPolicy).close();
JSPolicyRepresentation denyPolicy = new JSPolicyRepresentation(); JSPolicyRepresentation denyPolicy = new JSPolicyRepresentation();
denyPolicy.setName(KeycloakModelUtils.generateId()); denyPolicy.setName(KeycloakModelUtils.generateId());
denyPolicy.setCode("$evaluation.deny();"); denyPolicy.setType("script-scripts/always-deny-policy.js");
authorization.policies().js().create(denyPolicy).close(); authorization.policies().js().create(denyPolicy).close();
@ -1117,7 +1117,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -1730,16 +1730,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation onlyOwnerPolicy = new JSPolicyRepresentation(); JSPolicyRepresentation onlyOwnerPolicy = new JSPolicyRepresentation();
onlyOwnerPolicy.setName(KeycloakModelUtils.generateId()); onlyOwnerPolicy.setName(KeycloakModelUtils.generateId());
onlyOwnerPolicy.setCode("var context = $evaluation.getContext();\n" + onlyOwnerPolicy.setType("script-scripts/only-owner-policy.js");
"var identity = context.getIdentity();\n" +
"var permission = $evaluation.getPermission();\n" +
"var resource = permission.getResource();\n" +
"\n" +
"if (resource) {\n" +
" if (resource.owner == identity.id) {\n" +
" $evaluation.grant();\n" +
" }\n" +
"}");
return onlyOwnerPolicy; return onlyOwnerPolicy;
} }
@ -1751,19 +1742,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation onlyPublicResourcesPolicy = new JSPolicyRepresentation(); JSPolicyRepresentation onlyPublicResourcesPolicy = new JSPolicyRepresentation();
onlyPublicResourcesPolicy.setName(KeycloakModelUtils.generateId()); onlyPublicResourcesPolicy.setName(KeycloakModelUtils.generateId());
onlyPublicResourcesPolicy.setCode("var createPermission = $evaluation.getPermission();\n" + onlyPublicResourcesPolicy.setType("script-scripts/resource-visibility-attribute-policy.js");
"var resource = createPermission.getResource();\n" +
"\n" +
"if (resource) {\n" +
" var attributes = resource.getAttributes();\n" +
" var visibility = attributes.get('visibility');\n" +
" \n" +
" if (visibility && \"private\".equals(visibility.get(0))) {\n" +
" $evaluation.deny();\n" +
" } else {\n" +
" $evaluation.grant();\n" +
" }\n" +
"}");
authorization.policies().js().create(onlyPublicResourcesPolicy).close(); authorization.policies().js().create(onlyPublicResourcesPolicy).close();
@ -1929,7 +1908,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -1997,7 +1976,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -2051,7 +2030,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -2107,7 +2086,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -2155,7 +2134,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -2220,7 +2199,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation grantPolicy = new JSPolicyRepresentation(); JSPolicyRepresentation grantPolicy = new JSPolicyRepresentation();
grantPolicy.setName("Grant Policy"); grantPolicy.setName("Grant Policy");
grantPolicy.setCode("$evaluation.grant();"); grantPolicy.setType("script-scripts/default-policy.js");
rsB.authorization().policies().js().create(grantPolicy); rsB.authorization().policies().js().create(grantPolicy);
@ -2263,7 +2242,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -2318,7 +2297,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -2493,7 +2472,7 @@ public class EntitlementAPITest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName("Default Policy"); policy.setName("Default Policy");
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();

View file

@ -103,28 +103,28 @@ public class PermissionClaimTest extends AbstractAuthzTest {
claimAPolicy = new JSPolicyRepresentation(); claimAPolicy = new JSPolicyRepresentation();
claimAPolicy.setName("Claim A Policy"); claimAPolicy.setName("Claim A Policy");
claimAPolicy.setCode("$evaluation.getPermission().addClaim('claim-a', 'claim-a');$evaluation.getPermission().addClaim('claim-a', 'claim-a1');$evaluation.grant();"); claimAPolicy.setType("script-scripts/add-claim-a-policy.js");
authorization.policies().js().create(claimAPolicy).close(); authorization.policies().js().create(claimAPolicy).close();
claimBPolicy = new JSPolicyRepresentation(); claimBPolicy = new JSPolicyRepresentation();
claimBPolicy.setName("Policy Claim B"); claimBPolicy.setName("Policy Claim B");
claimBPolicy.setCode("$evaluation.getPermission().addClaim('claim-b', 'claim-b');$evaluation.grant();"); claimBPolicy.setType("script-scripts/add-claim-b-policy.js");
authorization.policies().js().create(claimBPolicy).close(); authorization.policies().js().create(claimBPolicy).close();
claimCPolicy = new JSPolicyRepresentation(); claimCPolicy = new JSPolicyRepresentation();
claimCPolicy.setName("Policy Claim C"); claimCPolicy.setName("Policy Claim C");
claimCPolicy.setCode("$evaluation.getPermission().addClaim('claim-c', 'claim-c');$evaluation.grant();"); claimCPolicy.setType("script-scripts/add-claim-c-policy.js");
authorization.policies().js().create(claimCPolicy).close(); authorization.policies().js().create(claimCPolicy).close();
denyPolicy = new JSPolicyRepresentation(); denyPolicy = new JSPolicyRepresentation();
denyPolicy.setName("Deny Policy"); denyPolicy.setName("Deny Policy");
denyPolicy.setCode("$evaluation.getPermission().addClaim('deny-policy', 'deny-policy');$evaluation.deny();"); denyPolicy.setType("script-scripts/always-deny-with-claim-policy.js");
authorization.policies().js().create(denyPolicy).close(); authorization.policies().js().create(denyPolicy).close();
} }

View file

@ -174,12 +174,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("testCheckUserInGroup"); policyRepresentation.setName("testCheckUserInGroup");
StringBuilder builder = new StringBuilder(); policyRepresentation.setType("script-scripts/allow-group-name-in-role-policy.js");
builder.append("var realm = $evaluation.getRealm();");
builder.append("if (realm.isUserInGroup('marta', 'Group C')) { $evaluation.grant(); }");
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation); Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType()); PolicyProvider provider = authorization.getProvider(policy.getType());
@ -190,15 +185,12 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
Assert.assertNull(evaluation.getEffect()); Assert.assertNull(evaluation.getEffect());
builder = new StringBuilder(); policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setId(KeycloakModelUtils.generateId());
builder.append("var realm = $evaluation.getRealm();"); policyRepresentation.setName(policyRepresentation.getId());
builder.append("if (realm.isUserInGroup('marta', 'Group A')) { $evaluation.grant(); }"); policyRepresentation.setType("script-scripts/allow-user-in-group-name-a-policy.js");
policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
policyRepresentation.setCode(builder.toString()); provider = authorization.getProvider(policy.getType());
policyRepresentation.setId(policy.getId());
policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);
evaluation = createEvaluation(session, authorization, resourceServer, policy); evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -206,15 +198,11 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
Assert.assertEquals(Effect.PERMIT, evaluation.getEffect()); Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
builder = new StringBuilder(); policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("allow-user-in-group-path-a-policy");
builder.append("var realm = $evaluation.getRealm();"); policyRepresentation.setType("script-scripts/allow-user-in-group-path-a-policy.js");
builder.append("if (realm.isUserInGroup('marta', '/Group A')) { $evaluation.grant(); }"); policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
provider = authorization.getProvider(policy.getType());
policyRepresentation.setCode(builder.toString());
policyRepresentation.setId(policy.getId());
policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);
evaluation = createEvaluation(session, authorization, resourceServer, policy); evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -222,15 +210,11 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
Assert.assertEquals(Effect.PERMIT, evaluation.getEffect()); Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
builder = new StringBuilder(); policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("allow-user-in-group-path-b-policy");
builder.append("var realm = $evaluation.getRealm();"); policyRepresentation.setType("script-scripts/allow-user-in-group-path-b-policy.js");
builder.append("if (realm.isUserInGroup('marta', '/Group A/Group B')) { $evaluation.grant(); }"); policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
provider = authorization.getProvider(policy.getType());
policyRepresentation.setCode(builder.toString());
policyRepresentation.setId(policy.getId());
policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);
evaluation = createEvaluation(session, authorization, resourceServer, policy); evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -238,15 +222,11 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
Assert.assertNull(evaluation.getEffect()); Assert.assertNull(evaluation.getEffect());
builder = new StringBuilder(); policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("allow-user-in-group-path-e-policy");
builder.append("var realm = $evaluation.getRealm();"); policyRepresentation.setType("script-scripts/allow-alice-in-group-child-e-policy.js");
builder.append("if (realm.isUserInGroup('alice', '/Group A/Group B/Group E')) { $evaluation.grant(); }"); policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
provider = authorization.getProvider(policy.getType());
policyRepresentation.setCode(builder.toString());
policyRepresentation.setId(policy.getId());
policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);
evaluation = createEvaluation(session, authorization, resourceServer, policy); evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -254,15 +234,11 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
Assert.assertEquals(Effect.PERMIT, evaluation.getEffect()); Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
builder = new StringBuilder(); policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("allow-alice-in-group-path-a-policy");
builder.append("var realm = $evaluation.getRealm();"); policyRepresentation.setType("script-scripts/allow-alice-in-group-path-a-policy.js");
builder.append("if (realm.isUserInGroup('alice', '/Group A')) { $evaluation.grant(); }"); policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
provider = authorization.getProvider(policy.getType());
policyRepresentation.setCode(builder.toString());
policyRepresentation.setId(policy.getId());
policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);
evaluation = createEvaluation(session, authorization, resourceServer, policy); evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -270,15 +246,11 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
Assert.assertEquals(Effect.PERMIT, evaluation.getEffect()); Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
builder = new StringBuilder(); policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("allow-alice-in-group-path-a-no-parent-policy.js");
builder.append("var realm = $evaluation.getRealm();"); policyRepresentation.setType("script-scripts/allow-alice-in-group-path-a-no-parent-policy.js");
builder.append("if (!realm.isUserInGroup('alice', '/Group A', false)) { $evaluation.grant(); }"); policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
provider = authorization.getProvider(policy.getType());
policyRepresentation.setCode(builder.toString());
policyRepresentation.setId(policy.getId());
policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);
evaluation = createEvaluation(session, authorization, resourceServer, policy); evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -286,15 +258,11 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
Assert.assertNull(evaluation.getEffect()); Assert.assertNull(evaluation.getEffect());
builder = new StringBuilder(); policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("allow-alice-in-group-path-e-policy.js");
builder.append("var realm = $evaluation.getRealm();"); policyRepresentation.setType("script-scripts/allow-alice-in-group-path-e-policy.js");
builder.append("if (realm.isUserInGroup('alice', '/Group E')) { $evaluation.grant(); }"); policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
provider = authorization.getProvider(policy.getType());
policyRepresentation.setCode(builder.toString());
policyRepresentation.setId(policy.getId());
policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);
evaluation = createEvaluation(session, authorization, resourceServer, policy); evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -302,15 +270,11 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
Assert.assertNull(evaluation.getEffect()); Assert.assertNull(evaluation.getEffect());
builder = new StringBuilder(); policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("allow-alice-in-group-name-e-policy.js");
builder.append("var realm = $evaluation.getRealm();"); policyRepresentation.setType("script-scripts/allow-alice-in-group-name-e-policy.js");
builder.append("if (realm.isUserInGroup('alice', 'Group E')) { $evaluation.grant(); }"); policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
provider = authorization.getProvider(policy.getType());
policyRepresentation.setCode(builder.toString());
policyRepresentation.setId(policy.getId());
policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);
evaluation = createEvaluation(session, authorization, resourceServer, policy); evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -332,13 +296,8 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(clientModel); ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(clientModel);
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("testCheckUserInRole"); policyRepresentation.setName("testCheckUserInRoleA");
StringBuilder builder = new StringBuilder(); policyRepresentation.setType("script-scripts/allow-marta-in-role-a-policy.js");
builder.append("var realm = $evaluation.getRealm();");
builder.append("if (realm.isUserInRealmRole('marta', 'role-a')) { $evaluation.grant(); }");
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation); Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType()); PolicyProvider provider = authorization.getProvider(policy.getType());
@ -349,15 +308,12 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
Assert.assertEquals(Effect.PERMIT, evaluation.getEffect()); Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
builder = new StringBuilder(); policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setId(null);
builder.append("var realm = $evaluation.getRealm();"); policyRepresentation.setName("testCheckUserInRoleB");
builder.append("if (realm.isUserInRealmRole('marta', 'role-b')) { $evaluation.grant(); }"); policyRepresentation.setType("script-scripts/allow-marta-in-role-b-policy.js");
policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
policyRepresentation.setCode(builder.toString()); provider = authorization.getProvider(policy.getType());
policyRepresentation.setId(policy.getId());
policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);
evaluation = createEvaluation(session, authorization, resourceServer, policy); evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -380,12 +336,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("testCheckUserInClientRole"); policyRepresentation.setName("testCheckUserInClientRole");
StringBuilder builder = new StringBuilder(); policyRepresentation.setType("script-scripts/allow-trinity-in-client-roles-policy.js");
builder.append("var realm = $evaluation.getRealm();");
builder.append("if (realm.isUserInClientRole('trinity', 'role-mapping-client', 'client-role-a')) { $evaluation.grant(); }");
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation); Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType()); PolicyProvider provider = authorization.getProvider(policy.getType());
@ -396,15 +347,11 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
Assert.assertEquals(Effect.PERMIT, evaluation.getEffect()); Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
builder = new StringBuilder(); policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("allow-trinity-in-client-role-b-policy");
builder.append("var realm = $evaluation.getRealm();"); policyRepresentation.setType("script-scripts/allow-trinity-in-client-role-b-policy.js");
builder.append("if (realm.isUserInRealmRole('trinity', 'client-role-b')) { $evaluation.grant(); }"); policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
provider = authorization.getProvider(policy.getType());
policyRepresentation.setCode(builder.toString());
policyRepresentation.setId(policy.getId());
policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);
evaluation = createEvaluation(session, authorization, resourceServer, policy); evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -427,12 +374,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("testCheckGroupInRole"); policyRepresentation.setName("testCheckGroupInRole");
StringBuilder builder = new StringBuilder(); policyRepresentation.setType("script-scripts/allow-group-in-role-policy.js");
builder.append("var realm = $evaluation.getRealm();");
builder.append("if (realm.isGroupInRole('/Group A/Group D', 'role-a')) { $evaluation.grant(); }");
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation); Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType()); PolicyProvider provider = authorization.getProvider(policy.getType());
@ -443,15 +385,12 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
Assert.assertEquals(Effect.PERMIT, evaluation.getEffect()); Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
builder = new StringBuilder(); policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setType("script-scripts/allow-child-group-in-role-policy.js");
builder.append("var realm = $evaluation.getRealm();"); policyRepresentation.setId(KeycloakModelUtils.generateId());
builder.append("if (realm.isGroupInRole('/Group A/Group D', 'role-b')) { $evaluation.grant(); }"); policyRepresentation.setName(policyRepresentation.getId());
policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
policyRepresentation.setCode(builder.toString()); provider = authorization.getProvider(policy.getType());
policyRepresentation.setId(policy.getId());
policy = RepresentationToModel.toModel(policyRepresentation, authorization, policy);
evaluation = createEvaluation(session, authorization, resourceServer, policy); evaluation = createEvaluation(session, authorization, resourceServer, policy);
@ -474,13 +413,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("testCheckUserRealmRoles"); policyRepresentation.setName("testCheckUserRealmRoles");
StringBuilder builder = new StringBuilder(); policyRepresentation.setType("script-scripts/allow-user-realm-roles-policy.js");
builder.append("var realm = $evaluation.getRealm();");
builder.append("var roles = realm.getUserRealmRoles('marta');");
builder.append("if (roles.size() == 2 && roles.contains('uma_authorization') && roles.contains('role-a')) { $evaluation.grant(); }");
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation); Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType()); PolicyProvider provider = authorization.getProvider(policy.getType());
@ -506,13 +439,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("testCheckUserClientRoles"); policyRepresentation.setName("testCheckUserClientRoles");
StringBuilder builder = new StringBuilder(); policyRepresentation.setType("script-scripts/allow-user-client-roles-policy.js");
builder.append("var realm = $evaluation.getRealm();");
builder.append("var roles = realm.getUserClientRoles('trinity', 'role-mapping-client');");
builder.append("if (roles.size() == 1 && roles.contains('client-role-a')) { $evaluation.grant(); }");
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation); Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType()); PolicyProvider provider = authorization.getProvider(policy.getType());
@ -538,13 +465,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("testCheckUserGroups"); policyRepresentation.setName("testCheckUserGroups");
StringBuilder builder = new StringBuilder(); policyRepresentation.setType("script-scripts/allow-user-from-groups-policy.js");
builder.append("var realm = $evaluation.getRealm();");
builder.append("var groups = realm.getUserGroups('jdoe');");
builder.append("if (groups.size() == 2 && groups.contains('/Group A/Group B') && groups.contains('/Group A/Group D')) { $evaluation.grant(); }");
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation); Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType()); PolicyProvider provider = authorization.getProvider(policy.getType());
@ -576,13 +497,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("testCheckUserAttributes"); policyRepresentation.setName("testCheckUserAttributes");
StringBuilder builder = new StringBuilder(); policyRepresentation.setType("script-scripts/allow-user-with-attributes.js");
builder.append("var realm = $evaluation.getRealm();");
builder.append("var attributes = realm.getUserAttributes('jdoe');");
builder.append("if (attributes.size() == 6 && attributes.containsKey('a1') && attributes.containsKey('a2') && attributes.get('a1').size() == 2 && attributes.get('a2').get(0).equals('3')) { $evaluation.grant(); }");
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation); Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType()); PolicyProvider provider = authorization.getProvider(policy.getType());
@ -608,14 +523,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("testCheckResourceAttributes"); policyRepresentation.setName("testCheckResourceAttributes");
StringBuilder builder = new StringBuilder(); policyRepresentation.setType("script-scripts/allow-resources-with-attributes.js");
builder.append("var permission = $evaluation.getPermission();");
builder.append("var resource = permission.getResource();");
builder.append("var attributes = resource.getAttributes();");
builder.append("if (attributes.size() == 2 && attributes.containsKey('a1') && attributes.containsKey('a2') && attributes.get('a1').size() == 2 && attributes.get('a2').get(0).equals('3') && resource.getAttribute('a1').size() == 2 && resource.getSingleAttribute('a2').equals('3')) { $evaluation.grant(); }");
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation); Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
PolicyProvider provider = authorization.getProvider(policy.getType()); PolicyProvider provider = authorization.getProvider(policy.getType());
@ -645,11 +553,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation(); JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("testCheckReadOnlyInstances"); policyRepresentation.setName("testCheckReadOnlyInstances");
StringBuilder builder = new StringBuilder(); policyRepresentation.setType("script-scripts/check-readonly-context-policy.js");
builder.append("$evaluation.getPermission().getResource().setName('test')");
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation); Policy policy = storeFactory.getPolicyStore().create(resourceServer, policyRepresentation);
@ -695,7 +599,7 @@ public class PolicyEvaluationTest extends AbstractAuthzTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId()); policy.setName(KeycloakModelUtils.generateId());
policy.setCode("$evaluation.grant()"); policy.setType("script-scripts/default-policy.js");
policy.setLogic(Logic.NEGATIVE); policy.setLogic(Logic.NEGATIVE);
storeFactory.getPolicyStore().create(resourceServer, policy); storeFactory.getPolicyStore().create(resourceServer, policy);

View file

@ -93,7 +93,7 @@ public class UmaGrantTypeTest extends AbstractResourceServerTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName("Default Policy"); policy.setName("Default Policy");
policy.setCode("$evaluation.grant();"); policy.setType("script-scripts/default-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
@ -109,7 +109,7 @@ public class UmaGrantTypeTest extends AbstractResourceServerTest {
policy = new JSPolicyRepresentation(); policy = new JSPolicyRepresentation();
policy.setName("Deny Policy"); policy.setName("Deny Policy");
policy.setCode("$evaluation.deny();"); policy.setType("script-scripts/always-deny-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
} }

View file

@ -53,17 +53,7 @@ public class UmaPermissionTicketPushedClaimsTest extends AbstractResourceServerT
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName("Withdraw Limit Policy"); policy.setName("Withdraw Limit Policy");
policy.setType("script-scripts/withdraw-limit-policy.js");
StringBuilder code = new StringBuilder();
code.append("var context = $evaluation.getContext();");
code.append("var attributes = context.getAttributes();");
code.append("var withdrawValue = attributes.getValue('my.bank.account.withdraw.value');");
code.append("if (withdrawValue && withdrawValue.asDouble(0) <= 100) {");
code.append(" $evaluation.grant();");
code.append("}");
policy.setCode(code.toString());
AuthorizationResource authorization = getClient(getRealm()).authorization(); AuthorizationResource authorization = getClient(getRealm()).authorization();

View file

@ -70,7 +70,7 @@ public class UserManagedAccessTest extends AbstractResourceServerTest {
JSPolicyRepresentation policy = new JSPolicyRepresentation(); JSPolicyRepresentation policy = new JSPolicyRepresentation();
policy.setName("Only Owner Policy"); policy.setName("Only Owner Policy");
policy.setCode("if ($evaluation.getContext().getIdentity().getId() == $evaluation.getPermission().getResource().getOwner()) {$evaluation.grant();}"); policy.setType("script-scripts/only-owner-policy.js");
authorization.policies().js().create(policy).close(); authorization.policies().js().create(policy).close();
} }

View file

@ -65,6 +65,7 @@ import org.keycloak.representations.idm.authorization.UmaPermissionRepresentatio
import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude; import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude;
import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer; import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer;
import org.keycloak.testsuite.arquillian.annotation.DisableFeature; import org.keycloak.testsuite.arquillian.annotation.DisableFeature;
import org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected;
import org.keycloak.testsuite.runonserver.RunOnServer; import org.keycloak.testsuite.runonserver.RunOnServer;
import org.keycloak.testsuite.util.ClientBuilder; import org.keycloak.testsuite.util.ClientBuilder;
import org.keycloak.testsuite.util.GroupBuilder; import org.keycloak.testsuite.util.GroupBuilder;
@ -139,9 +140,7 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
newPermission.addGroup("/group_a", "/group_a/group_b", "/group_c"); newPermission.addGroup("/group_a", "/group_a/group_b", "/group_c");
newPermission.addClient("client-a", "resource-server-test"); newPermission.addClient("client-a", "resource-server-test");
if (Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS)) { newPermission.setCondition("script-scripts/default-policy.js");
newPermission.setCondition("$evaluation.grant()");
}
newPermission.addUser("kolo"); newPermission.addUser("kolo");
@ -170,7 +169,6 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
} }
@Test @Test
@DisableFeature(value = Profile.Feature.UPLOAD_SCRIPTS, skipRestart = true)
public void testCreateDeprecatedFeaturesDisabled() { public void testCreateDeprecatedFeaturesDisabled() {
testCreate(); testCreate();
} }
@ -274,21 +272,19 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
assertTrue(permission.getClients().containsAll(updated.getClients())); assertTrue(permission.getClients().containsAll(updated.getClients()));
if (Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS)) { permission.setCondition("script-scripts/default-policy.js");
permission.setCondition("$evaluation.grant()");
protection.policy(resource.getId()).update(permission); protection.policy(resource.getId()).update(permission);
assertEquals(4, getAssociatedPolicies(permission).size()); assertEquals(4, getAssociatedPolicies(permission).size());
updated = protection.policy(resource.getId()).findById(permission.getId()); updated = protection.policy(resource.getId()).findById(permission.getId());
assertEquals(permission.getCondition(), updated.getCondition()); assertEquals(permission.getCondition(), updated.getCondition());
}
permission.addUser("alice"); permission.addUser("alice");
protection.policy(resource.getId()).update(permission); protection.policy(resource.getId()).update(permission);
int expectedPolicies = Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS) ? 5 : 4; int expectedPolicies = 5;
assertEquals(expectedPolicies, getAssociatedPolicies(permission).size()); assertEquals(expectedPolicies, getAssociatedPolicies(permission).size());
updated = protection.policy(resource.getId()).findById(permission.getId()); updated = protection.policy(resource.getId()).findById(permission.getId());
@ -319,15 +315,13 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
assertEquals(permission.getUsers(), updated.getUsers()); assertEquals(permission.getUsers(), updated.getUsers());
if (Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS)) { permission.setCondition(null);
permission.setCondition(null);
protection.policy(resource.getId()).update(permission); protection.policy(resource.getId()).update(permission);
assertEquals(--expectedPolicies, getAssociatedPolicies(permission).size()); assertEquals(--expectedPolicies, getAssociatedPolicies(permission).size());
updated = protection.policy(resource.getId()).findById(permission.getId()); updated = protection.policy(resource.getId()).findById(permission.getId());
assertEquals(permission.getCondition(), updated.getCondition()); assertEquals(permission.getCondition(), updated.getCondition());
};
permission.setRoles(null); permission.setRoles(null);
@ -359,18 +353,12 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
} }
@Test @Test
public void testUpdateDeprecatedFeaturesEnabled() { public void testUpdatePermission() {
testUpdate(); testUpdate();
} }
@Test @Test
@DisableFeature(value = Profile.Feature.UPLOAD_SCRIPTS, skipRestart = true) @UncaughtServerErrorExpected
public void testUpdateDeprecatedFeaturesDisabled() {
testUpdate();
}
@Test
@DisableFeature(value = Profile.Feature.UPLOAD_SCRIPTS, skipRestart = true)
public void testUploadScriptDisabled() { public void testUploadScriptDisabled() {
ResourceRepresentation resource = new ResourceRepresentation(); ResourceRepresentation resource = new ResourceRepresentation();
@ -381,28 +369,26 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
resource = getAuthzClient().protection().resource().create(resource); resource = getAuthzClient().protection().resource().create(resource);
UmaPermissionRepresentation newPermission = new UmaPermissionRepresentation();
newPermission.setName("Custom User-Managed Permission");
newPermission.setDescription("Users from specific roles are allowed to access");
newPermission.setCondition("$evaluation.grant()");
ProtectionResource protection = getAuthzClient().protection("marta", "password"); ProtectionResource protection = getAuthzClient().protection("marta", "password");
UmaPermissionRepresentation newPermission = new UmaPermissionRepresentation();
try { try {
newPermission.setName("Custom User-Managed Permission");
newPermission.setDescription("Users from specific roles are allowed to access");
newPermission.setCondition("$evaluation.grant()");
protection.policy(resource.getId()).create(newPermission); protection.policy(resource.getId()).create(newPermission);
fail("Should fail because upload scripts is disabled"); fail("Should fail because upload scripts is disabled");
} catch (Exception ignore) { } catch (Exception ignore) {
} }
newPermission.setCondition(null);
UmaPermissionRepresentation representation = protection.policy(resource.getId()).create(newPermission);
representation.setCondition("$evaluation.grant();");
try { try {
UmaPermissionRepresentation representation = protection.policy(resource.getId()).create(newPermission);
representation.setCondition("$evaluation.grant();");
protection.policy(resource.getId()).update(newPermission); protection.policy(resource.getId()).update(newPermission);
fail("Should fail because upload scripts is disabled"); fail("Should fail because upload scripts is disabled");
} catch (Exception ignore) { } catch (Exception ignore) {
@ -998,9 +984,7 @@ public class UserManagedPermissionServiceTest extends AbstractResourceServerTest
newPermission.addGroup("/group_a", "/group_a/group_b", "/group_c"); newPermission.addGroup("/group_a", "/group_a/group_b", "/group_c");
newPermission.addClient("client-a", "resource-server-test"); newPermission.addClient("client-a", "resource-server-test");
if (Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS)) { newPermission.setCondition("script-scripts/default-policy.js");
newPermission.setCondition("$evaluation.grant()");
}
newPermission.addUser("kolo"); newPermission.addUser("kolo");

View file

@ -57,7 +57,7 @@ import static org.keycloak.common.Profile.Feature.AUTHORIZATION;
* *
* @author <a href="mailto:thomas.darimont@gmail.com">Thomas Darimont</a> * @author <a href="mailto:thomas.darimont@gmail.com">Thomas Darimont</a>
*/ */
@EnableFeature(value = Profile.Feature.UPLOAD_SCRIPTS, skipRestart = true) @EnableFeature(value = Profile.Feature.SCRIPTS)
public class ScriptAuthenticatorTest extends AbstractFlowTest { public class ScriptAuthenticatorTest extends AbstractFlowTest {
@Page @Page
@ -103,12 +103,13 @@ public class ScriptAuthenticatorTest extends AbstractFlowTest {
@Before @Before
public void configureFlows() throws Exception { public void configureFlows() throws Exception {
String scriptFlow = "scriptBrowser";
if (testContext.isInitialized()) { if (testContext.isInitialized()) {
this.flow = findFlowByAlias(scriptFlow);
return; return;
} }
String scriptFlow = "scriptBrowser";
AuthenticationFlowRepresentation scriptBrowserFlow = FlowBuilder.create() AuthenticationFlowRepresentation scriptBrowserFlow = FlowBuilder.create()
.alias(scriptFlow) .alias(scriptFlow)
.description("dummy pass through registration") .description("dummy pass through registration")
@ -138,7 +139,7 @@ public class ScriptAuthenticatorTest extends AbstractFlowTest {
.id(EXECUTION_ID) .id(EXECUTION_ID)
.parentFlow(this.flow.getId()) .parentFlow(this.flow.getId())
.requirement(AuthenticationExecutionModel.Requirement.REQUIRED.name()) .requirement(AuthenticationExecutionModel.Requirement.REQUIRED.name())
.authenticator(ScriptBasedAuthenticatorFactory.PROVIDER_ID) .authenticator("script-scripts/auth-example.js")
.build(); .build();
Response addExecutionResponse = testRealm().flows().addExecution(usernamePasswordFormExecution); Response addExecutionResponse = testRealm().flows().addExecution(usernamePasswordFormExecution);
@ -157,8 +158,6 @@ public class ScriptAuthenticatorTest extends AbstractFlowTest {
*/ */
@Test @Test
public void loginShouldWorkWithScriptAuthenticator() { public void loginShouldWorkWithScriptAuthenticator() {
addConfigFromFile("/scripts/authenticator-example.js");
loginPage.open(); loginPage.open();
loginPage.login("user", "password"); loginPage.login("user", "password");
@ -171,8 +170,6 @@ public class ScriptAuthenticatorTest extends AbstractFlowTest {
*/ */
@Test @Test
public void loginShouldFailWithScriptAuthenticator() { public void loginShouldFailWithScriptAuthenticator() {
addConfigFromFile("/scripts/authenticator-example.js");
loginPage.open(); loginPage.open();
loginPage.login("fail", "password"); loginPage.login("fail", "password");
@ -185,10 +182,16 @@ public class ScriptAuthenticatorTest extends AbstractFlowTest {
*/ */
@Test @Test
public void scriptWithClientSession() { public void scriptWithClientSession() {
addConfigFromFile("/scripts/client-session-test.js", ImmutableMap.of( AuthenticationExecutionRepresentation authScriptExecution = ExecutionBuilder.create()
"realm", "test", .id(EXECUTION_ID + "client-session")
"clientId", "test-app", .parentFlow(this.flow.getId())
"authMethod", "openid-connect")); .requirement(AuthenticationExecutionModel.Requirement.REQUIRED.name())
.authenticator("script-scripts/auth-session.js")
.build();
Response addExecutionResponse = testRealm().flows().addExecution(authScriptExecution);
Assert.assertEquals(201, addExecutionResponse.getStatus());
addExecutionResponse.close();
loginPage.open(); loginPage.open();
@ -196,49 +199,5 @@ public class ScriptAuthenticatorTest extends AbstractFlowTest {
events.expectLogin().user(userId).detail(Details.USERNAME, "user").assertEvent(); events.expectLogin().user(userId).detail(Details.USERNAME, "user").assertEvent();
} }
private void addConfigFromFile(String filename) {
addConfigFromFile(filename, null);
}
private void addConfigFromFile(String filename, Map<String, String> parameters) {
String alias = filename.substring(filename.lastIndexOf("/") + 1);
String script = loadFile(filename, parameters);
Response newExecutionConfigResponse = testRealm().flows().
newExecutionConfig(EXECUTION_ID, createScriptAuthConfig(EXECUTION_ID, alias, script, "script based authenticator"));
newExecutionConfigResponse.close();
Assert.assertEquals(201, newExecutionConfigResponse.getStatus());
}
private String loadFile(String filename, Map<String, String> parameters) {
String script = null;
try {
script = IOUtils.toString(getClass().getResourceAsStream(filename));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (parameters != null) {
for (Map.Entry<String, String> entry : parameters.entrySet()) {
script = script.replaceAll("\\$\\{" + entry.getKey() + "}", entry.getValue());
}
}
return script;
}
private AuthenticatorConfigRepresentation createScriptAuthConfig(String alias, String scriptName, String script, String scriptDescription) {
AuthenticatorConfigRepresentation configRep = new AuthenticatorConfigRepresentation();
configRep.setAlias(alias);
configRep.getConfig().put("scriptCode", script);
configRep.getConfig().put("scriptName", scriptName);
configRep.getConfig().put("scriptDescription", scriptDescription);
return configRep;
}
} }

View file

@ -140,16 +140,17 @@ public class OIDCProtocolMappersTest extends AbstractKeycloakTest {
} }
@Test @Test
@EnableFeature(value = Profile.Feature.UPLOAD_SCRIPTS, skipRestart = true) // This requires also SCRIPTS feature, therefore we need to restart container @EnableFeature(value = Profile.Feature.SCRIPTS) // This requires also SCRIPTS feature, therefore we need to restart container
public void testTokenScriptMapping() { public void testTokenScriptMapping() throws Exception {
{ {
reconnectAdminClient();
ClientResource app = findClientResourceByClientId(adminClient.realm("test"), "test-app"); ClientResource app = findClientResourceByClientId(adminClient.realm("test"), "test-app");
app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper1","computed-via-script", "computed-via-script", "String", true, true, "'hello_' + user.username", false)).close(); app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper1","computed-via-script", "computed-via-script", "String", true, true, "script-scripts/test-script-mapper1.js", false)).close();
app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper2","multiValued-via-script", "multiValued-via-script", "String", true, true, "new java.util.ArrayList(['A','B'])", true)).close(); app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper2","multiValued-via-script", "multiValued-via-script", "String", true, true, "script-scripts/test-script-mapper2.js", true)).close();
app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper3","computed-json-via-script", "computed-json-via-script", "JSON", true, true, "var x = {'int':42, 'bool': true, 'string': 'test'}; x", false)).close(); app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper3","computed-json-via-script", "computed-json-via-script", "JSON", true, true, "script-scripts/test-script-mapper3.js", false)).close();
Response response = app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper3", "syntax-error-script", "syntax-error-script", "String", true, true, "func_tion foo(){ return 'fail';} foo()", false)); Response response = app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper3", "syntax-error-script", "syntax-error-script", "String", true, true, "script-scripts/test-bad-script-mapper3.js", false));
assertThat(response.getStatusInfo().getFamily(), is(Response.Status.Family.CLIENT_ERROR)); assertThat(response.getStatusInfo().getFamily(), is(Response.Status.Family.CLIENT_ERROR));
response.close(); response.close();
} }

View file

@ -18,7 +18,6 @@ package org.keycloak.testsuite.script;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.keycloak.common.Profile.Feature.UPLOAD_SCRIPTS;
import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT; import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@ -122,14 +121,12 @@ public class DeployedScriptPolicyTest extends AbstractAuthzTest {
} }
@Test @Test
@DisableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
public void testJSPolicyProviderNotAvailable() { public void testJSPolicyProviderNotAvailable() {
assertFalse(getAuthorizationResource().policies().policyProviders().stream().anyMatch(rep -> "js".equals(rep.getType()))); assertFalse(getAuthorizationResource().policies().policyProviders().stream().anyMatch(rep -> "js".equals(rep.getType())));
} }
@Test @Test
@UncaughtServerErrorExpected @UncaughtServerErrorExpected
@DisableFeature(value = UPLOAD_SCRIPTS, skipRestart = true)
public void failCreateJSPolicy() { public void failCreateJSPolicy() {
JSPolicyRepresentation grantPolicy = new JSPolicyRepresentation(); JSPolicyRepresentation grantPolicy = new JSPolicyRepresentation();

View file

@ -443,16 +443,6 @@
} }
], ],
"policies": [ "policies": [
{
"name": "Default Policy",
"description": "A policy that grants access only for users within this realm",
"type": "js",
"logic": "POSITIVE",
"decisionStrategy": "AFFIRMATIVE",
"config": {
"code": "// by default, grants any permission associated with this policy\n$evaluation.grant();\n"
}
},
{ {
"name": "Resource 1 Policy", "name": "Resource 1 Policy",
"type": "role", "type": "role",

View file

@ -54,12 +54,9 @@
{ {
"name": "Only Owner Policy", "name": "Only Owner Policy",
"description": "Defines that only the resource owner is allowed to do something", "description": "Defines that only the resource owner is allowed to do something",
"type": "js", "type": "script-scripts/only-owner-policy.js",
"logic": "POSITIVE", "logic": "POSITIVE",
"decisionStrategy": "UNANIMOUS", "decisionStrategy": "UNANIMOUS"
"config": {
"code": "var permission = $evaluation.getPermission();\nvar identity = $evaluation.getContext().getIdentity();\nvar resource = permission.getResource();\nif (resource) {\nif (resource.getOwner().equals(identity.getId())) {\n$evaluation.grant();\n}}"
}
}, },
{ {
"name": "Any User Policy", "name": "Any User Policy",
@ -74,12 +71,9 @@
{ {
"name": "Only From a Specific Client Address", "name": "Only From a Specific Client Address",
"description": "Defines that only clients from a specific address can do something", "description": "Defines that only clients from a specific address can do something",
"type": "js", "type": "script-scripts/only-from-specific-address-policy.js",
"logic": "POSITIVE", "logic": "POSITIVE",
"decisionStrategy": "UNANIMOUS", "decisionStrategy": "UNANIMOUS"
"config": {
"code": "var contextAttributes = $evaluation.getContext().getAttributes();\n\nif (contextAttributes.containsValue('kc.client.network.ip_address', '127.0.0.1')) {\n $evaluation.grant();\n}"
}
}, },
{ {
"name": "Administration Policy", "name": "Administration Policy",
@ -149,12 +143,9 @@
{ {
"name": "Only From @keycloak.org or Admin", "name": "Only From @keycloak.org or Admin",
"description": "Defines that only users from @keycloak.org", "description": "Defines that only users from @keycloak.org",
"type": "js", "type": "script-scripts/only-from-specific-domain-or-admin-policy.js",
"logic": "POSITIVE", "logic": "POSITIVE",
"decisionStrategy": "UNANIMOUS", "decisionStrategy": "UNANIMOUS"
"config": {
"code": "var context = $evaluation.getContext();\nvar identity = context.getIdentity();\nvar attributes = identity.getAttributes();\nvar email = attributes.getValue('email').asString(0);\n\nif (identity.hasRealmRole('admin') || email.endsWith('@keycloak.org')) {\n $evaluation.grant();\n}"
}
}, },
{ {
"name": "Test Client Policy", "name": "Test Client Policy",

Some files were not shown because too many files have changed in this diff Show more