use of org.forgerock.openam.scripting.ScriptObject in project OpenAM by OpenRock.
the class ScriptResource method actionCollection.
@Override
public Promise<ActionResponse, ResourceException> actionCollection(Context context, ActionRequest request) {
if ("validate".equals(request.getAction())) {
try {
JsonValue json = request.getContent();
SupportedScriptingLanguage language = getLanguageFromString(json.get(SCRIPT_LANGUAGE).asString());
String script = json.get(SCRIPT_TEXT).asString();
if (script == null) {
throw new ScriptException(MISSING_SCRIPT);
}
List<ScriptError> scriptErrorList = scriptValidator.validateScript(new ScriptObject(EMPTY, decodeScript(script), language, null));
if (scriptErrorList.isEmpty()) {
return newResultPromise(newActionResponse(json(object(field("success", true)))));
}
Set<Object> errors = new HashSet<>();
for (ScriptError error : scriptErrorList) {
errors.add(object(field("line", error.getLineNumber()), field("column", error.getColumnNumber()), field("message", error.getMessage())));
}
return newResultPromise(newActionResponse(json(object(field("success", false), field("errors", errors)))));
} catch (ScriptException se) {
return exceptionMappingHandler.handleError(context, request, se).asPromise();
}
} else {
return new NotSupportedException().asPromise();
}
}
use of org.forgerock.openam.scripting.ScriptObject in project OpenAM by OpenRock.
the class ScriptConditionTest method successfulEvaluation.
@Test
public void successfulEvaluation() throws EntitlementException, ScriptException, javax.script.ScriptException, IdRepoException, SSOException {
// Given
Subject subject = new Subject();
SSOToken token = mock(SSOToken.class);
subject.getPrivateCredentials().add(token);
subject.getPrincipals().add(new AuthSPrincipal("user"));
Map<String, Set<String>> env = new HashMap<>();
Map<String, Set<String>> advice = new HashMap<>();
final ScriptConfiguration configuration = ScriptConfiguration.builder().setId("123-456-789").setName("test-script").setContext(ScriptContext.POLICY_CONDITION).setLanguage(SupportedScriptingLanguage.JAVASCRIPT).setScript("some-script-here").build();
scriptCondition = new ScriptCondition() {
@Override
protected ScriptConfiguration getScriptConfiguration(String realm) throws ScriptException {
return configuration;
}
};
given(coreWrapper.getIdentity(token)).willReturn(mock(AMIdentity.class));
// When
scriptCondition.setScriptId("123-456-789");
ConditionDecision decision = scriptCondition.evaluate("/abc", subject, "http://a:b/c", env);
// Then
// Hard to test true scenario
assertThat(decision.isSatisfied()).isFalse();
verify(scriptEvaluator).evaluateScript(scriptObjectCaptor.capture(), bindingsCaptor.capture());
ScriptObject scriptObject = scriptObjectCaptor.getValue();
assertThat(scriptObject.getName()).isEqualTo("test-script");
assertThat(scriptObject.getLanguage()).isEqualTo(SupportedScriptingLanguage.JAVASCRIPT);
assertThat(scriptObject.getScript()).isEqualTo("some-script-here");
Bindings bindings = bindingsCaptor.getValue();
assertThat(bindings.get("logger")).isEqualTo(PolicyConstants.DEBUG);
assertThat(bindings.get("username")).isEqualTo("user");
assertThat(bindings.get("resourceURI")).isEqualTo("http://a:b/c");
assertThat(bindings.get("environment")).isEqualTo(env);
assertThat(bindings.get("advice")).isEqualTo(advice);
assertThat(bindings.get("httpClient")).isEqualTo(restletHttpClient);
assertThat(bindings.get("authorized")).isEqualTo(Boolean.FALSE);
assertThat(bindings.get("ttl")).isEqualTo(Long.MAX_VALUE);
}
use of org.forgerock.openam.scripting.ScriptObject in project OpenAM by OpenRock.
the class OpenAMScopeValidator method getOIDCClaimsExtensionScript.
private ScriptObject getOIDCClaimsExtensionScript(String realm) throws ServerException {
OpenAMSettingsImpl settings = new OpenAMSettingsImpl(OAuth2Constants.OAuth2ProviderService.NAME, OAuth2Constants.OAuth2ProviderService.VERSION);
try {
String scriptId = settings.getStringSetting(realm, OAuth2Constants.OAuth2ProviderService.OIDC_CLAIMS_EXTENSION_SCRIPT);
if (EMPTY_SCRIPT_SELECTION.equals(scriptId)) {
return new ScriptObject("oidc-claims-script", "", SupportedScriptingLanguage.JAVASCRIPT);
}
ScriptConfiguration config = getScriptConfiguration(realm, scriptId);
return new ScriptObject(config.getName(), config.getScript(), config.getLanguage());
} catch (org.forgerock.openam.scripting.ScriptException | SSOException | SMSException e) {
logger.message("Error running OIDC claims script", e);
throw new ServerException("Error running OIDC claims script: " + e.getMessage());
}
}
use of org.forgerock.openam.scripting.ScriptObject in project OpenAM by OpenRock.
the class OpenAMScopeValidator method getUserInfo.
/**
* {@inheritDoc}
*/
public UserInfoClaims getUserInfo(AccessToken token, OAuth2Request request) throws UnauthorizedClientException, NotFoundException {
Map<String, Object> response = new HashMap<>();
Bindings scriptVariables = new SimpleBindings();
SSOToken ssoToken = getUsersSession(request);
String realm;
Set<String> scopes;
AMIdentity id;
OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
Map<String, Set<String>> requestedClaimsValues = gatherRequestedClaims(providerSettings, request, token);
try {
if (token != null) {
OpenIdConnectClientRegistration clientRegistration;
try {
clientRegistration = clientRegistrationStore.get(token.getClientId(), request);
} catch (InvalidClientException e) {
logger.message("Unable to retrieve client from store.");
throw new NotFoundException("No valid client registration found.");
}
final String subId = clientRegistration.getSubValue(token.getResourceOwnerId(), providerSettings);
//data comes from token when we have one
realm = token.getRealm();
scopes = token.getScope();
id = identityManager.getResourceOwnerIdentity(token.getResourceOwnerId(), realm);
response.put(OAuth2Constants.JWTTokenParams.SUB, subId);
response.put(OAuth2Constants.JWTTokenParams.UPDATED_AT, getUpdatedAt(token.getResourceOwnerId(), token.getRealm(), request));
} else {
//otherwise we're simply reading claims into the id_token, so grab it from the request/ssoToken
realm = DNMapper.orgNameToRealmName(ssoToken.getProperty(ISAuthConstants.ORGANIZATION));
id = identityManager.getResourceOwnerIdentity(ssoToken.getProperty(ISAuthConstants.USER_ID), realm);
String scopeStr = request.getParameter(OAuth2Constants.Params.SCOPE);
scopes = splitScope(scopeStr);
}
scriptVariables.put(OAuth2Constants.ScriptParams.SCOPES, getScriptFriendlyScopes(scopes));
scriptVariables.put(OAuth2Constants.ScriptParams.IDENTITY, id);
scriptVariables.put(OAuth2Constants.ScriptParams.LOGGER, logger);
scriptVariables.put(OAuth2Constants.ScriptParams.CLAIMS, response);
scriptVariables.put(OAuth2Constants.ScriptParams.SESSION, ssoToken);
scriptVariables.put(OAuth2Constants.ScriptParams.REQUESTED_CLAIMS, requestedClaimsValues);
ScriptObject script = getOIDCClaimsExtensionScript(realm);
try {
return scriptEvaluator.evaluateScript(script, scriptVariables);
} catch (ScriptException e) {
logger.message("Error running OIDC claims script", e);
throw new ServerException("Error running OIDC claims script: " + e.getMessage());
}
} catch (ServerException e) {
//API does not allow ServerExceptions to be thrown!
throw new NotFoundException(e.getMessage());
} catch (SSOException e) {
throw new NotFoundException(e.getMessage());
}
}
use of org.forgerock.openam.scripting.ScriptObject in project OpenAM by OpenRock.
the class ScriptCondition method evaluate.
@Override
public ConditionDecision evaluate(String realm, Subject subject, String resourceName, Map<String, Set<String>> environment) throws EntitlementException {
try {
ScriptConfiguration configuration = getScriptConfiguration(realm);
if (configuration == null) {
throw new EntitlementException(EntitlementException.INVALID_SCRIPT_ID, scriptId);
}
ScriptObject script = new ScriptObject(configuration.getName(), configuration.getScript(), configuration.getLanguage());
Map<String, List<String>> advice = new HashMap<>();
Map<String, List<String>> responseAttributes = new HashMap<>();
Bindings scriptVariables = new SimpleBindings();
scriptVariables.put("logger", PolicyConstants.DEBUG);
scriptVariables.put("username", SubjectUtils.getPrincipalId(subject));
scriptVariables.put("resourceURI", resourceName);
scriptVariables.put("environment", environment);
scriptVariables.put("advice", advice);
scriptVariables.put("responseAttributes", responseAttributes);
scriptVariables.put("httpClient", getHttpClient(configuration.getLanguage()));
scriptVariables.put("authorized", Boolean.FALSE);
scriptVariables.put("ttl", Long.MAX_VALUE);
SSOToken ssoToken = SubjectUtils.getSSOToken(subject);
if (ssoToken != null) {
// If a token is present include the corresponding identity and session objects.
scriptVariables.put("identity", new ScriptedIdentity(coreWrapper.getIdentity(ssoToken)));
scriptVariables.put("session", new ScriptedSession(ssoToken));
}
evaluator.evaluateScript(script, scriptVariables);
boolean authorized = (Boolean) scriptVariables.get("authorized");
if (!authorized) {
return ConditionDecision.newFailureBuilder().setAdvice(transformMap(advice, LIST_TO_SET)).setResponseAttributes(transformMap(responseAttributes, LIST_TO_SET)).build();
}
long ttl = ((Number) scriptVariables.get("ttl")).longValue();
return ConditionDecision.newSuccessBuilder().setResponseAttributes(transformMap(responseAttributes, LIST_TO_SET)).setTimeToLive(ttl).build();
} catch (ScriptException | javax.script.ScriptException | IdRepoException | SSOException ex) {
throw new EntitlementException(EntitlementException.CONDITION_EVALUATION_FAILED, ex);
}
}
Aggregations