Search in sources :

Example 1 with ScriptObject

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();
    }
}
Also used : ScriptException(org.forgerock.openam.scripting.ScriptException) ScriptObject(org.forgerock.openam.scripting.ScriptObject) ScriptError(org.forgerock.openam.scripting.ScriptError) JsonValue(org.forgerock.json.JsonValue) ScriptObject(org.forgerock.openam.scripting.ScriptObject) SupportedScriptingLanguage(org.forgerock.openam.scripting.SupportedScriptingLanguage) NotSupportedException(org.forgerock.json.resource.NotSupportedException) HashSet(java.util.HashSet)

Example 2 with ScriptObject

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);
}
Also used : ScriptObject(org.forgerock.openam.scripting.ScriptObject) SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashMap(java.util.HashMap) ConditionDecision(com.sun.identity.entitlement.ConditionDecision) Bindings(javax.script.Bindings) Subject(javax.security.auth.Subject) ScriptException(org.forgerock.openam.scripting.ScriptException) AMIdentity(com.sun.identity.idm.AMIdentity) AuthSPrincipal(com.sun.identity.rest.AuthSPrincipal) ScriptConfiguration(org.forgerock.openam.scripting.service.ScriptConfiguration) Test(org.testng.annotations.Test)

Example 3 with ScriptObject

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());
    }
}
Also used : ScriptObject(org.forgerock.openam.scripting.ScriptObject) ScriptException(javax.script.ScriptException) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) SMSException(com.sun.identity.sm.SMSException) OpenAMSettingsImpl(org.forgerock.openam.utils.OpenAMSettingsImpl) ScriptConfiguration(org.forgerock.openam.scripting.service.ScriptConfiguration) SSOException(com.iplanet.sso.SSOException)

Example 4 with ScriptObject

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());
    }
}
Also used : ScriptObject(org.forgerock.openam.scripting.ScriptObject) OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AMHashMap(com.iplanet.am.sdk.AMHashMap) HashMap(java.util.HashMap) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) SSOException(com.iplanet.sso.SSOException) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) ScriptException(javax.script.ScriptException) SimpleBindings(javax.script.SimpleBindings) AMIdentity(com.sun.identity.idm.AMIdentity) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) JSONObject(org.json.JSONObject) ScriptObject(org.forgerock.openam.scripting.ScriptObject) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 5 with ScriptObject

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);
    }
}
Also used : ScriptObject(org.forgerock.openam.scripting.ScriptObject) SSOToken(com.iplanet.sso.SSOToken) HashMap(java.util.HashMap) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) EntitlementException(com.sun.identity.entitlement.EntitlementException) ScriptException(org.forgerock.openam.scripting.ScriptException) SimpleBindings(javax.script.SimpleBindings) ScriptConfiguration(org.forgerock.openam.scripting.service.ScriptConfiguration) List(java.util.List) ScriptedSession(org.forgerock.openam.scripting.api.ScriptedSession) ScriptedIdentity(org.forgerock.openam.scripting.api.ScriptedIdentity)

Aggregations

ScriptObject (org.forgerock.openam.scripting.ScriptObject)7 Bindings (javax.script.Bindings)4 ScriptException (org.forgerock.openam.scripting.ScriptException)4 ScriptConfiguration (org.forgerock.openam.scripting.service.ScriptConfiguration)4 SSOException (com.iplanet.sso.SSOException)3 SSOToken (com.iplanet.sso.SSOToken)3 HashMap (java.util.HashMap)3 SimpleBindings (javax.script.SimpleBindings)3 AMIdentity (com.sun.identity.idm.AMIdentity)2 HashSet (java.util.HashSet)2 Set (java.util.Set)2 ScriptException (javax.script.ScriptException)2 JsonValue (org.forgerock.json.JsonValue)2 NotSupportedException (org.forgerock.json.resource.NotSupportedException)2 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)2 SupportedScriptingLanguage (org.forgerock.openam.scripting.SupportedScriptingLanguage)2 AMHashMap (com.iplanet.am.sdk.AMHashMap)1 ConditionDecision (com.sun.identity.entitlement.ConditionDecision)1 EntitlementException (com.sun.identity.entitlement.EntitlementException)1 IdRepoException (com.sun.identity.idm.IdRepoException)1