diff --git a/CHANGELOG.md b/CHANGELOG.md index 57ad9fa0c..df70e8eb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,22 @@ +## 1.7.18 +NEW FEATURES: +* Each Cell's OAuth 2.0 token endpoint now accepts scope request. + * Apps can request single or multiple Cell level privilege name(s) as scope request. + * Issued tokens now carry assigned scope information. + * Cell Level API Access is now limited to tokens with appropriate scope. ([#445](https://github.com/personium/personium-core/issues/445)) + * Added unit config keys for configuring default scopes for different grant type ([#470](https://github.com/personium/personium-core/issues/470)) + * Default configurations for all grant types are set to "root" for backward compatibility. (Change configuration to use your unit with more security) +* URL scheme "personium-localunit" is extended and supports a syntax using two colons. ([#284](https://github.com/personium/personium-core/issues/284)) + +IMPROVEMENTS: +* Base URL in ACL is now converted to one using "personium-localunit" scheme when internally pesisted. Unit FQDN change won't require data change. + +SECURITY FIX: +* Token refreshing between apps now disabled. ([#463](https://github.com/personium/personium-core/issues/463)) + ## 1.7.17 IMPROVEMENTS: -* Add IO logging with IO time. ([#446](https://github.com/personium/personium-core/issues/446)) +* Add IO logging with elapsed time. ([#446](https://github.com/personium/personium-core/issues/446)) ## 1.7.16 BUG FIXES: @@ -8,7 +24,7 @@ BUG FIXES: * If Accept request header contains extra values, 409 is returned ([#435](https://github.com/personium/personium-core/issues/435)) IMPROVEMENTS: -* Fix crossdomain.xml error in Eclipse. ([#448](https://github.com/personium/personium-core/issues/444)) +* Fix crossdomain.xml namespace URL. ([#448](https://github.com/personium/personium-core/issues/444)) ## 1.7.15 BUG FIXES: diff --git a/pom.xml b/pom.xml index 90dad118f..c88521df7 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ io.personium personium-core war - 1.7.17_es6.6.1 + 1.7.18_es6.6.1 personium-core Maven Webapp http://maven.apache.org @@ -28,11 +28,11 @@ 1.1.1 - + io.personium personium-lib-common - 1.4.20 + 1.5.1 io.personium diff --git a/src/main/java/io/personium/core/PersoniumCoreAuthnException.java b/src/main/java/io/personium/core/PersoniumCoreAuthnException.java index 9ee17607b..03c44edf7 100644 --- a/src/main/java/io/personium/core/PersoniumCoreAuthnException.java +++ b/src/main/java/io/personium/core/PersoniumCoreAuthnException.java @@ -38,9 +38,6 @@ /** * Log message creation class. */ -/** - * @author naoki - */ @SuppressWarnings("serial") public final class PersoniumCoreAuthnException extends PersoniumCoreException { @@ -56,7 +53,7 @@ public final class PersoniumCoreAuthnException extends PersoniumCoreException { /** * Client Secret Parsing error. */ - public static final PersoniumCoreAuthnException CLIENT_SECRET_PARSE_ERROR = + public static final PersoniumCoreAuthnException CLIENT_ASSERTION_PARSE_ERROR = create("PR400-AN-0003", Error.INVALID_CLIENT); /** * Client Secret expiration date check. @@ -69,7 +66,7 @@ public final class PersoniumCoreAuthnException extends PersoniumCoreException { public static final PersoniumCoreAuthnException CLIENT_SECRET_DSIG_INVALID = create("PR400-AN-0005", Error.INVALID_CLIENT); /** - * Issuer of Client Secret is not equal to ID. + * Issuer of Client Secret does not match client id. */ public static final PersoniumCoreAuthnException CLIENT_SECRET_ISSUER_MISMATCH = create("PR400-AN-0006", Error.INVALID_CLIENT); @@ -129,12 +126,29 @@ public final class PersoniumCoreAuthnException extends PersoniumCoreException { */ public static final PersoniumCoreAuthnException AUTH_HEADER_IS_INVALID = create("PR400-AN-0018", Error.INVALID_CLIENT); + /** + * Invalid assertion type parameter. + */ + public static final PersoniumCoreAuthnException INVALID_CLIENT_ASSERTION_TYPE = + create("PR400-AN-0022", Error.INVALID_CLIENT); + /** + * Authenticated Client does not match the refresh token. + */ + public static final PersoniumCoreAuthnException CLIENT_MISMATCH_FOR_REFRESH = + create("PR401-AN-0020", Error.INVALID_CLIENT); + /** + * Client auth required to refresh the token. + */ + public static final PersoniumCoreAuthnException CLIENT_AUTH_REQUIRED = + create("PR401-AN-0021", Error.INVALID_CLIENT); /** * Password change required. */ public static final PersoniumCoreAuthnException PASSWORD_CHANGE_REQUIRED = create("PR401-AN-0001", Error.UNAUTHORIZED_CLIENT); + + /** * NetWork related error. */ diff --git a/src/main/java/io/personium/core/PersoniumCoreException.java b/src/main/java/io/personium/core/PersoniumCoreException.java index 91d246443..c2a351ff6 100644 --- a/src/main/java/io/personium/core/PersoniumCoreException.java +++ b/src/main/java/io/personium/core/PersoniumCoreException.java @@ -739,6 +739,11 @@ public static class Auth { * Schema authentication level is insufficient. */ public static final PersoniumCoreException INSUFFICIENT_SCHEMA_AUTHZ_LEVEL = create("PR403-AU-0006"); + /** + * Scope is insufficient. + */ + public static final PersoniumCoreException INSUFFICIENT_SCOPE = create("PR403-AU-0007"); + /** * Error setting root CA certificate. */ @@ -1014,6 +1019,13 @@ public static class Common { * {0} : Overview of failed processing */ public static final PersoniumCoreException FILE_IO_ERROR = create("PR500-CM-0002"); + + /** + * Unchecked Invalid URL used internally. + *

+ * {0} : URL + */ + public static final PersoniumCoreException INVALID_URL = create("PR500-CM-0003"); } /** diff --git a/src/main/java/io/personium/core/PersoniumReadDeleteModeManager.java b/src/main/java/io/personium/core/PersoniumReadDeleteModeManager.java index 6f2a31caa..e11cb2082 100644 --- a/src/main/java/io/personium/core/PersoniumReadDeleteModeManager.java +++ b/src/main/java/io/personium/core/PersoniumReadDeleteModeManager.java @@ -42,7 +42,7 @@ private PersoniumReadDeleteModeManager() { HttpMethod.DELETE, HttpMethod.OPTIONS, HttpMethod.HEAD, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND, + io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND, "REPORT" ) ); diff --git a/src/main/java/io/personium/core/PersoniumUnitConfig.java b/src/main/java/io/personium/core/PersoniumUnitConfig.java index 222edb85f..dad6bfde4 100644 --- a/src/main/java/io/personium/core/PersoniumUnitConfig.java +++ b/src/main/java/io/personium/core/PersoniumUnitConfig.java @@ -1,6 +1,7 @@ /** - * personium.io - * Copyright 2014-2018 FUJITSU LIMITED + * Personium + * Copyright 2014-2018 Personium Project + * - FUJITSU LIMITED * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +35,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.auth.AuthUtils; import io.personium.core.utils.UriUtils; @@ -188,6 +189,16 @@ public static final class Security { /** Encrypt the DAV file (true: enabled false: disabled (default)). */ public static final String DAV_ENCRYPT_ENABLED = KEY_ROOT + "security.dav.encrypt.enabled"; + + /** Default scope of token for grant_type=password . */ + public static final String TOKEN_DEFAULT_SCOPE_ROPC = KEY_ROOT + "security.token.defaultScope.ropc"; + + /** Default scope of token for grant_type=assertion . */ + public static final String TOKEN_DEFAULT_SCOPE_ASSERTION = KEY_ROOT + "security.token.defaultScope.assertion"; + + /** Default scope of token for grant_type=code . */ + public static final String TOKEN_DEFAULT_SCOPE_CODE = KEY_ROOT + "security.token.defaultScope.grant_code"; + } /** @@ -538,14 +549,14 @@ private synchronized void doReload() { } } - private static boolean isSpaceSeparatedValueIncluded(String spaceSeparatedValue, String testValue, String unitUrl) { + private static boolean isSpaceSeparatedValueIncluded(String spaceSeparatedValue, String testValue) { if (testValue == null || spaceSeparatedValue == null) { return false; } String[] values = spaceSeparatedValue.split(" "); for (String val : values) { // Correspondence when "localunit" is set for issuers. - String convertedValue = UriUtils.convertSchemeFromLocalUnitToHttp(unitUrl, val); + String convertedValue = UriUtils.convertSchemeFromLocalUnitToHttp(val); if (testValue.equals(convertedValue)) { return true; } @@ -871,7 +882,7 @@ public static String getPluginPath() { public static String getBaseUrl() { return UriBuilder.fromPath("/") .scheme(getUnitScheme()) - .host(PersoniumCoreUtils.getFQDN()) + .host(CommonUtils.getFQDN()) .port(getUnitPort()) .build() .toString(); @@ -1473,6 +1484,29 @@ public static boolean isDavEncryptEnabled() { return Boolean.parseBoolean(get(Security.DAV_ENCRYPT_ENABLED)); } + /** + * + * @return scope string + */ + public static String getTokenDefaultScopeRopc() { + return get(Security.TOKEN_DEFAULT_SCOPE_ROPC); + } + /** + * + * @return scope string + */ + public static String getTokenDefaultScopeCode() { + return get(Security.TOKEN_DEFAULT_SCOPE_CODE); + } + /** + * + * @return scope string + */ + public static String getTokenDefaultScopeAssertion() { + return get(Security.TOKEN_DEFAULT_SCOPE_ASSERTION); + } + + /** * Get message queue implementation of EventBus. * @return message queue @@ -1614,8 +1648,8 @@ public static boolean isHttps() { * @param unitUrl Unit URL * @return Included:true */ - public static boolean checkUnitUserIssuers(String url, String unitUrl) { - return isSpaceSeparatedValueIncluded(getUnitUserIssuers(), url, unitUrl); + public static boolean checkUnitUserIssuers(String url) { + return isSpaceSeparatedValueIncluded(getUnitUserIssuers(), url); } /** diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index bf3b27de6..d5b853821 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -16,10 +16,15 @@ */ package io.personium.core.auth; +import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; +import java.net.URL; import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; import java.util.List; +import java.util.Set; import javax.ws.rs.core.UriInfo; @@ -27,20 +32,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import io.personium.common.auth.token.AbstractLocalAccessToken; import io.personium.common.auth.token.AbstractOAuth2Token; import io.personium.common.auth.token.AbstractOAuth2Token.TokenDsigException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenRootCrtException; -import io.personium.common.auth.token.AccountAccessToken; -import io.personium.common.auth.token.CellLocalAccessToken; import io.personium.common.auth.token.IAccessToken; -import io.personium.common.auth.token.LocalToken; import io.personium.common.auth.token.PasswordChangeAccessToken; +import io.personium.common.auth.token.ResidentLocalAccessToken; import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; -import io.personium.common.auth.token.TransCellRefreshToken; import io.personium.common.auth.token.UnitLocalUnitUserToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.auth.token.VisitorLocalAccessToken; +import io.personium.common.auth.token.VisitorRefreshToken; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreAuthzException; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; @@ -67,23 +72,23 @@ public class AccessContext { /** Anonymous access : No Authorization header. */ public static final String TYPE_ANONYMOUS = "anon"; - /** Access with invalid permissions : Authorization header was present, but it was not authenticated. */ + /** Access with invalid access token : Authorization header was present, but it was not authenticated. */ public static final String TYPE_INVALID = "invalid"; - /** Access with master token : Authorization header content is master token. */ + /** Access with master token : Authorization header content is unit master token. */ public static final String TYPE_UNIT_MASTER = "unit-master"; - /** Access by basic authentication. */ + /** Access with basic authentication. */ public static final String TYPE_BASIC = "basic"; - /** Access by account access token. */ - public static final String TYPE_ACCOUNT = "account"; - /** Access by password change access token. */ + /** Access with Resident Local Access Token. */ + public static final String TYPE_RESIDENT = "account"; + /** Access with password change access token. */ public static final String TYPE_PASSWORD_CHANGE = "password-change"; - /** Access by cell local access token. */ - public static final String TYPE_LOCAL = "local"; - /** Access by TransCell Access Token. */ + /** Access with visitor local access token. */ + public static final String TYPE_VISITOR = "local"; + /** Access with Trans Cell Access Token. */ public static final String TYPE_TRANS = "trans"; - /** Access by Unit User Access token. */ + /** Access with Unit User Access token. */ public static final String TYPE_UNIT_USER = "unit-user"; - /** Access by "Unit User Access token" assigned "UnitAdmin authority". */ + /** Access with "Unit User Access token" assigned "UnitAdmin authority". */ public static final String TYPE_UNIT_ADMIN = "unit-admin"; /** Access by Unit Local Unit User Token. */ public static final String TYPE_UNIT_LOCAL = "unit-local"; @@ -134,12 +139,19 @@ private enum InvalidReason { private Cell cell; /** Access token type. */ private String accessType; - /** subject. */ + /** accessing user subject. */ private String subject; - /** issuer. */ + /** access token issuer. */ private String issuer; - /** schema. */ + /** accessing app schema. */ private String schema; + /** scopes granted to the app. */ + private Set scopes = new HashSet<>(); + /** CellPrivilege granted for App as scope. */ + private Set scopePrivileges = new HashSet<>(); + /** Roles granted for App as scope. */ + private Set scopeRoles = new HashSet<>(); + /** confidentialLevel. */ private String confidentialLevel; /** Roles associated with access account. */ @@ -163,6 +175,7 @@ private AccessContext(String type, Cell cell, String baseUri, UriInfo uriInfo, I this.baseUri = baseUri; this.uriInfo = uriInfo; this.invalidReason = invalidReason; + } /** @@ -184,40 +197,22 @@ public static AccessContext create(String authzHeaderValue, if (pCookiePeer == null || 0 == pCookiePeer.length()) { return new AccessContext(TYPE_ANONYMOUS, cell, baseUri, requestURIInfo); } - //Cookie authentication - //Get decrypted value of cookie value - if (null == pCookieAuthValue) { - return new AccessContext( - TYPE_INVALID, cell, baseUri, requestURIInfo, InvalidReason.cookieAuthError); - } + String nonPortHost = headerHost.split(":")[0]; + // Cookie related processing requires no port number. - String decodedCookieValue; + String authToken = null; try { - String nonPortHost = headerHost.split(":")[0]; - decodedCookieValue = LocalToken.decode(pCookieAuthValue, - UnitLocalUnitUserToken.getIvBytes(AccessContext.getCookieCryptKey(nonPortHost))); - } catch (TokenParseException e) { - return new AccessContext( - TYPE_INVALID, cell, baseUri, requestURIInfo, InvalidReason.cookieAuthError); - } - int separatorIndex = decodedCookieValue.indexOf("\t"); - String peer = decodedCookieValue.substring(0, separatorIndex); - //Obtain authorizationHeader equivalent token from information in cookie - String authToken = decodedCookieValue.substring(separatorIndex + 1); - if (pCookiePeer.equals(peer)) { - //Generate appropriate AccessContext with recursive call. + authToken = AbstractLocalAccessToken.parseCookie(pCookieAuthValue, pCookiePeer, + AccessContext.getCookieCryptKey(nonPortHost), true); return create(OAuth2Helper.Scheme.BEARER + " " + authToken, requestURIInfo, null, null, cell, baseUri, headerHost, xPersoniumUnitUser); - } else { + } catch (TokenParseException e) { return new AccessContext( TYPE_INVALID, cell, baseUri, requestURIInfo, InvalidReason.cookieAuthError); } } - //TODO V1.1 Here is the part that can be cached. You can get it from the cache here. - - //First branch depending on the authentication method - + // First branch depending on the authentication method if (authzHeaderValue.startsWith(OAuth2Helper.Scheme.BASIC)) { //Basic authentication return createBasicAuthz(authzHeaderValue, cell, baseUri, requestURIInfo); @@ -284,6 +279,13 @@ public String getIssuer() { public String getSchema() { return schema; } + /** + * Get scopes. + * @return scopes + */ + public String[] getScope() { + return this.scopes.toArray(new String[0]); + } /** * Get confidentialLevel. @@ -327,12 +329,11 @@ public String getUnitUserRole() { /** * Merge with the parent's ACL information and judge whether access is possible. - * @param acl ALC set in the resource + * @param acl ACL set in the resource * @param resourcePrivilege Privilege required to access the resource - * @param cellUrl Cell URL * @return boolean */ - public boolean requirePrivilege(Acl acl, Privilege resourcePrivilege, String cellUrl) { + public boolean hasSubjectPrivilegeForAcl(Acl acl, Privilege resourcePrivilege) { //No access if ACL is not set if (acl == null || acl.getAceList() == null) { return false; @@ -371,7 +372,7 @@ public boolean requirePrivilege(Acl acl, Privilege resourcePrivilege, String cel } //Detect setting corresponding to role - if (role.localCreateUrl(cellUrl).equals(principalHref)) { + if (role.localCreateUrl(this.cell.getUrl()).equals(principalHref)) { //Confirm whether Root is set if (ace.getGrantedPrivilegeList().contains(CellPrivilege.ROOT.getName())) { return true; @@ -392,17 +393,17 @@ public boolean requirePrivilege(Acl acl, Privilege resourcePrivilege, String cel */ public boolean isUnitUserToken() { String type = getType(); - if (TYPE_UNIT_MASTER.equals(type) - || TYPE_UNIT_ADMIN.equals(type)) { + if (TYPE_UNIT_MASTER.equals(type) || TYPE_UNIT_ADMIN.equals(type)) { return true; } else if ((TYPE_UNIT_USER.equals(type) || TYPE_UNIT_LOCAL.equals(type)) - && getSubject().equals(getCell().getOwner())) { + && getSubject().equals(getCell().getOwnerNormalized())) { //↑ Unit user, Unit For local unit users, this is valid only when the unit owner name included in the token and the cell owner to be processed match. return true; } return false; } + /** * Perform access control (only master token, unit user token, unit local unit user token accessible). * @param resourcePrivilege Required authority @@ -414,7 +415,7 @@ public boolean isUnitUserToken(Privilege resourcePrivilege) { return true; } else if (TYPE_UNIT_ADMIN.equals(type) || ((TYPE_UNIT_USER.equals(type) || TYPE_UNIT_LOCAL.equals(type)) //NOPMD - To maintain readability - && getSubject().equals(getCell().getOwner()))) { + && getSubject().equals(getCell().getOwnerNormalized()))) { // In the case of a UnitUser or UnitLocal, it is effective only when the unit owner name included // in the processing target cell owner and the token matches. @@ -444,8 +445,9 @@ public JSONObject getUnitMetadataJson() { } /** - * Access control is performed (Subject can access only token of CELL). - * @param acceptableAuthScheme Whether it is a call from a resource that does not allow basic authentication + * Check that the subject in the TCAT is identical to the issuer. + * @param acceptableAuthScheme + * Whether it is a call from a resource that does not allow basic authentication */ public void checkCellIssueToken(AcceptableAuthScheme acceptableAuthScheme) { if (TYPE_TRANS.equals(this.getType()) @@ -469,7 +471,7 @@ public void checkCellIssueToken(AcceptableAuthScheme acceptableAuthScheme) { * @param cellname cell * @param acceptableAuthScheme Whether it is a call from a resource that does not allow basic authentication */ - public void checkMyLocalOrPasswordChangeToken(Cell cellname, AcceptableAuthScheme acceptableAuthScheme) { + public void checkResidentLocalOrPasswordChangeToken(AcceptableAuthScheme acceptableAuthScheme) { //Returning 401 if there is no illegal token or token designation //Returning 403 for a token other than your own cell local token if (TYPE_INVALID.equals(this.getType())) { @@ -477,9 +479,14 @@ public void checkMyLocalOrPasswordChangeToken(Cell cellname, AcceptableAuthSchem } else if (TYPE_ANONYMOUS.equals(this.getType()) || TYPE_BASIC.equals(this.getType())) { throw PersoniumCoreAuthzException.AUTHORIZATION_REQUIRED.realm(getRealm(), acceptableAuthScheme); - } else if (!TYPE_ACCOUNT.equals(this.getType()) && !TYPE_PASSWORD_CHANGE.equals(this.getType())) { + } else if (!TYPE_RESIDENT.equals(this.getType()) && !TYPE_PASSWORD_CHANGE.equals(this.getType())) { throw PersoniumCoreException.Auth.NECESSARY_PRIVILEGE_LACKING; } + + // Check that the subject is resident and the app scope include auth priv. + if (TYPE_RESIDENT.equals(this.getType()) && !this.hasScopeCellPrivilege(CellPrivilege.AUTH)) { + throw PersoniumCoreException.Auth.INSUFFICIENT_SCOPE.params(CellPrivilege.AUTH.getName()); + } } /** @@ -489,7 +496,8 @@ public void checkMyLocalOrPasswordChangeToken(Cell cellname, AcceptableAuthSchem * @param acceptableAuthScheme Whether it is a call from a resource that does not allow basic authentication */ public void checkSchemaAccess(String settingConfidentialLevel, Box box, AcceptableAuthScheme acceptableAuthScheme) { - //If you are a master token or unit user, unit local unit user pass through schema authentication. + // If accessed with a master, unit user token, or unit local unit user token, + // Then pass through schema authentication. if (this.isUnitUserToken()) { return; } @@ -532,7 +540,7 @@ public void checkSchemaAccess(String settingConfidentialLevel, Box box, Acceptab */ public void checkSchemaMatches(Box box) { if (box != null) { - String boxSchema = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), box.getSchema()); + String boxSchema = UriUtils.convertSchemeFromLocalUnitToHttp(box.getSchema()); String tokenSchema = getSchema(); // Do not check if box schema is not set. @@ -548,8 +556,10 @@ public void checkSchemaMatches(Box box) { } /** - * If basic authentication can not be done, it is checked whether basic authentication can be performed or not, and the state of Basic authentication disabled is set in context.
- * In this method, only checking is performed, and whether or not it is actually an authentication error is left to the access right check process of the structure. + * If basic authentication can not be done, it is checked whether basic authentication can be performed or not, + * and the state of Basic authentication disabled is set in context.
+ * In this method, only checking is performed, and whether or not it is actually an authentication error + * is left to the access right check process of the structure. * @param box Box object (specify null for Cell level) */ public void updateBasicAuthenticationStateForResource(Box box) { @@ -565,7 +575,7 @@ public void updateBasicAuthenticationStateForResource(Box box) { } //The main box has a schema but basic authentication is possible - if (Role.DEFAULT_BOX_NAME.equals(box.getName())) { + if (Box.MAIN_BOX_NAME.equals(box.getName())) { return; } @@ -647,7 +657,7 @@ private static AccessContext createBasicAuthz(String authzHeaderValue, Cell cell return new AccessContext(TYPE_INVALID, null, baseUri, uriInfo, InvalidReason.basicAuthError); } - String[] idpw = PersoniumCoreUtils.parseBasicAuthzHeader(authzHeaderValue); + String[] idpw = CommonUtils.parseBasicAuthzHeader(authzHeaderValue); if (idpw == null) { return new AccessContext(TYPE_INVALID, cell, baseUri, uriInfo, InvalidReason.basicAuthFormat); } @@ -680,8 +690,27 @@ private static AccessContext createBasicAuthz(String authzHeaderValue, Cell cell ret.subject = username; //Acquire role information ret.roles = cell.getRoleListForAccount(username); + // TODO Make configurable + ret.addScope("root"); + return ret; } + public void addScope(String scopeStr) { + this.scopes.add(scopeStr); + if (scopeStr.startsWith("https://")||scopeStr.startsWith("http://")) { + try { + this.scopeRoles.add(new Role(new URL(scopeStr))); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } else { + CellPrivilege prv = CellPrivilege.get(CellPrivilege.class, scopeStr); + if (prv != null) { + this.scopePrivileges.add(prv); + } + } + + } /** * Factory method, which creates and returns an object by Bearer authentication based on the value of Cell and Authorization header being accessed. @@ -736,7 +765,7 @@ private static AccessContext createBearerAuthz(String authzHeaderValue, Cell cel } log.debug(tk.getClass().getCanonicalName()); //If it is not an AccessToken, ie a refresh token. - if (!(tk instanceof IAccessToken) || tk instanceof TransCellRefreshToken) { + if (!(tk instanceof IAccessToken) || tk instanceof VisitorRefreshToken) { //Access by refresh token is not permitted. return new AccessContext(TYPE_INVALID, cell, baseUri, uriInfo, InvalidReason.refreshToken); } @@ -747,8 +776,8 @@ private static AccessContext createBearerAuthz(String authzHeaderValue, Cell cel } AccessContext ret = new AccessContext(null, cell, baseUri, uriInfo); - if (tk instanceof AccountAccessToken) { - ret.accessType = TYPE_ACCOUNT; + if (tk instanceof ResidentLocalAccessToken) { + ret.accessType = TYPE_RESIDENT; //Retrieve role information. String acct = tk.getSubject(); ret.roles = cell.getRoleListForAccount(acct); @@ -763,9 +792,9 @@ private static AccessContext createBearerAuthz(String authzHeaderValue, Cell cel ret.accessType = TYPE_PASSWORD_CHANGE; ret.subject = cell.getUrl() + "#" + tk.getSubject(); ret.issuer = tk.getIssuer(); - } else if (tk instanceof CellLocalAccessToken) { - CellLocalAccessToken clat = (CellLocalAccessToken) tk; - ret.accessType = TYPE_LOCAL; + } else if (tk instanceof VisitorLocalAccessToken) { + VisitorLocalAccessToken clat = (VisitorLocalAccessToken) tk; + ret.accessType = TYPE_VISITOR; //Acquire roll information and pack it. ret.roles = clat.getRoles(); ret.subject = tk.getSubject(); @@ -791,8 +820,26 @@ private static AccessContext createBearerAuthz(String authzHeaderValue, Cell cel } else { ret.confidentialLevel = OAuth2Helper.SchemaLevel.PUBLIC; } - - // TODO Cache Cell Level + if (tk.getScope() != null) { + ret.scopes.addAll(Arrays.asList(tk.getScope())); + for (String scope : ret.scopes) { + if (OAuth2Helper.Scope.OPENID.contentEquals(scope)) { + continue; + } + if (scope.startsWith("https://")||scope.startsWith("http://")) { + try { + ret.scopeRoles.add(new Role(new URL(scope))); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } else { + CellPrivilege prv = CellPrivilege.get(CellPrivilege.class, scope); + if (prv != null) { + ret.scopePrivileges.add(prv); + } + } + } + } return ret; } @@ -887,8 +934,8 @@ private static AccessContext createAccessContext(Cell cell, String requestURIHos String issuer = tca.getIssuer(); if ((tca.getTarget().equals(baseUri) || tca.getTarget().equals(escapedBaseUri)) - && (PersoniumUnitConfig.checkUnitUserIssuers(issuer, baseUri) - || PersoniumUnitConfig.checkUnitUserIssuers(issuer, escapedBaseUri))) { + && (PersoniumUnitConfig.checkUnitUserIssuers(issuer) + || PersoniumUnitConfig.checkUnitUserIssuers(issuer))) { //Processing unit user tokens ret.accessType = TYPE_UNIT_USER; ret.subject = tca.getSubject(); @@ -896,12 +943,12 @@ private static AccessContext createAccessContext(Cell cell, String requestURIHos //Take role information and if you have unit admin roll, promote to unit admin. List roles = tca.getRoles(); - Role unitAdminRole = new Role(ROLE_UNIT_ADMIN, Box.DEFAULT_BOX_NAME, null, tca.getIssuer()); + Role unitAdminRole = new Role(ROLE_UNIT_ADMIN, Box.MAIN_BOX_NAME, null, tca.getIssuer()); String unitAdminRoleUrl = unitAdminRole.createUrl(); - Role cellContentsReaderRole = new Role(ROLE_CELL_CONTENTS_READER, Box.DEFAULT_BOX_NAME, + Role cellContentsReaderRole = new Role(ROLE_CELL_CONTENTS_READER, Box.MAIN_BOX_NAME, null, tca.getIssuer()); String cellContentsReaderUrl = cellContentsReaderRole.createUrl(); - Role cellContentsAdminRole = new Role(ROLE_CELL_CONTENTS_ADMIN, Box.DEFAULT_BOX_NAME, + Role cellContentsAdminRole = new Role(ROLE_CELL_CONTENTS_ADMIN, Box.MAIN_BOX_NAME, null, tca.getIssuer()); String cellContentsAdminUrl = cellContentsAdminRole.createUrl(); @@ -944,4 +991,18 @@ private static AccessContext createAccessContext(Cell cell, String requestURIHos } } + /** + * Check if this access context has the cell level privilege. + * @param cellPriv + * @return + */ + public boolean hasScopeCellPrivilege(CellPrivilege cellPriv) { + for (CellPrivilege scopePriv : this.scopePrivileges) { + if (scopePriv.includes(cellPriv)) { + return true; + } + } + // TODO scope role check + return false; + } } diff --git a/src/main/java/io/personium/core/auth/OAuth2Helper.java b/src/main/java/io/personium/core/auth/OAuth2Helper.java index ee0cfd01c..6df344a1a 100644 --- a/src/main/java/io/personium/core/auth/OAuth2Helper.java +++ b/src/main/java/io/personium/core/auth/OAuth2Helper.java @@ -1,6 +1,7 @@ /** - * personium.io - * Copyright 2014 FUJITSU LIMITED + * Personium + * Copyright 2014-2019 Personium Project + * - FUJITSU LIMITED * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,26 +19,21 @@ import javax.xml.namespace.QName; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; /** - * A utility around OAuth 2. - * The OAuth 2.0 Authorization Protocol - * http://tools.ietf.org/html/draft-ietf-oauth-v2-27 - * The OAuth 2.0 Authorization Protocol: Bearer Tokens - * http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-19 - * OAuth SAML Assertion Profiles - * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-12 + * A utility around OAuth 2.0. + * RFC6749 The OAuth 2.0 Authorization Framework + * https://tools.ietf.org/html/rfc6749 + * RFC6750 The OAuth 2.0 The OAuth 2.0 Authorization Framework: Bearer Token Usage + * https://tools.ietf.org/html/rfc6750 + * RFC7522 SAML 2.0 Profile for OAuth 2.0 Client Authentication and Authorization Grants + * https://tools.ietf.org/html/rfc7522 */ public final class OAuth2Helper { private OAuth2Helper() { } - /** - * Version of OAuth 2. - */ - public static final String VERSION = "Draft 27"; - /** * URN representing SAML Assertion. */ @@ -180,6 +176,7 @@ public static class ResponseType { public static class Scope { /** openid. It is used with the openid connect of the oauth2 extension. */ public static final String OPENID = "openid"; + } /** @@ -210,6 +207,18 @@ public static class Key { * client_secret. */ public static final String CLIENT_SECRET = "client_secret"; + /** + * "client_assertion" parameter key defined in RFC7521. + * https://tools.ietf.org/html/rfc7521#section-4.2 + */ + public static final String CLIENT_ASSERTION = "client_assertion"; + /** + * "client_assertion_type" parameter key defined in RFC7521. + * https://tools.ietf.org/html/rfc7521#section-4.2 + */ + public static final String CLIENT_ASSERTION_TYPE = "client_assertion_type"; + + /** * state. */ @@ -291,10 +300,15 @@ public static class Key { * p_owner. */ public static final String OWNER = "p_owner"; + /** + * p_cookie. + */ + public static final String P_COOKIE = "p_cookie"; /** * p_owner value. */ public static final String TRUE_STR = "true"; + /** * refresh_token_expires_in. */ @@ -323,12 +337,12 @@ public static class Key { * ownerRepresentativeAccounts. */ public static final QName PROP_KEY_OWNER_REPRESENTIVE_ACCOUNTS = - new QName(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, "ownerRepresentativeAccounts"); + new QName(CommonUtils.XmlConst.NS_PERSONIUM, "ownerRepresentativeAccounts"); /** * ownerRepresentativeAccount. */ public static final QName PROP_KEY_OWNER_REPRESENTIVE_ACCOUNT = - new QName(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, "account"); + new QName(CommonUtils.XmlConst.NS_PERSONIUM, "account"); } /** @@ -354,7 +368,7 @@ public static class SchemaLevel { * @param value Target value * @return true:match false:not match */ - public static boolean isMatchPermittedValue(String value) { + public static boolean isPermittedValue(String value) { if (value == null || NONE.equals(value) || PUBLIC.equals(value) diff --git a/src/main/java/io/personium/core/auth/ScopeArbitrator.java b/src/main/java/io/personium/core/auth/ScopeArbitrator.java new file mode 100644 index 000000000..561449dda --- /dev/null +++ b/src/main/java/io/personium/core/auth/ScopeArbitrator.java @@ -0,0 +1,119 @@ +package io.personium.core.auth; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import io.personium.common.auth.token.AbstractOAuth2Token; +import io.personium.core.PersoniumUnitConfig; +import io.personium.core.model.Box; +import io.personium.core.model.Cell; +import io.personium.core.utils.UriUtils; + +/** + * Class for scope arbitration object. + * Create an instance with Cell and Box information and grant_type string. + * + * With isROPC true: + * It is a cell admin mode. So any scope request will be admitted. + * if not request is made then default scope will be root. + * + * With isROPC false: + * Normal use cases. + * only scopes that are pre-granted to box will be admitted. + * i.e. Cell Level Privileges and Roles + * if no box exists then no scope will be granted. + * + * not implemented yet. + */ +public class ScopeArbitrator { + Cell cell; + Box box; + boolean isRopc; + String grantType; + Privilege unitMaxScopePrivilege; + Set requestedScopes = new HashSet<>(); + List permittedScopes = new ArrayList(); + + static final Set VALID_NON_URL_SCOPES = new HashSet<>(Arrays.asList(new String[] { + OAuth2Helper.Scope.OPENID + })); + public ScopeArbitrator(Cell cell, Box box, String grantType) { + this.cell = cell; + this.box = box; + this.grantType = grantType; + String unitMaxScopeStr = null; + if (OAuth2Helper.GrantType.PASSWORD.equals(this.grantType)) { + unitMaxScopeStr = PersoniumUnitConfig.getTokenDefaultScopeRopc(); + } else if (OAuth2Helper.GrantType.AUTHORIZATION_CODE.equals(this.grantType)) { + unitMaxScopeStr = PersoniumUnitConfig.getTokenDefaultScopeCode(); + } else if (OAuth2Helper.GrantType.SAML2_BEARER.equals(this.grantType)) { + unitMaxScopeStr = PersoniumUnitConfig.getTokenDefaultScopeAssertion(); + } else { + unitMaxScopeStr = PersoniumUnitConfig.getTokenDefaultScopeRopc(); + } + this.unitMaxScopePrivilege = Privilege.get(CellPrivilege.class, unitMaxScopeStr); + } + public ScopeArbitrator requestString(String requestScopes) { + return this.request(AbstractOAuth2Token.Scope.parse(requestScopes)); + } + public ScopeArbitrator request(String[] requestScopes) { + if (requestScopes != null) { + this.requestedScopes = new HashSet<>(Arrays.asList(requestScopes)); + } + // remove empty entry + this.requestedScopes.remove(""); + this.arbitrate(); + return this; + } + private void arbitrate() { + if (this.requestedScopes.size() == 0 && this.unitMaxScopePrivilege != null) { + this.requestedScopes.add(this.unitMaxScopePrivilege.getName()); + } + for (String scope : this.requestedScopes) { + if (this.check(scope)) { + this.permittedScopes.add(scope); + } + } + } + public String[] getResults() { + return this.permittedScopes.toArray(new String[0]); + } + private boolean check(String scope) { + // + if (VALID_NON_URL_SCOPES.contains(scope)) { + return true; + } + String resolvedScope = UriUtils.resolveLocalUnit(scope); + // If it looks like a role because it is a http URL. + if (resolvedScope.startsWith("http://") || resolvedScope.startsWith("https://")) { + // check if it is really a role or not + if (isRole(resolvedScope)) { + return true; + } + return false; + } + + // If not, it should probably be Cell Privilege. + // make sure. + CellPrivilege cp = Privilege.get(CellPrivilege.class, scope); + if (cp == null) { + return false; + } + // Now Cell Level privilege can come here. + // if ROPC then allow any valid scopes. + if (this.unitMaxScopePrivilege != null && this.unitMaxScopePrivilege.includes(cp)) { + return true; + } + // if not then reject all .. (Tentatively) + // TODO implement Box configuration to allow Cell Level privilege, and refer to that + // setting. + return false; + } + private boolean isRole(String scope) { + String id = this.cell.roleResourceUrlToId(scope, PersoniumUnitConfig.getBaseUrl()); + return id != null; + } +} diff --git a/src/main/java/io/personium/core/auth/hash/Sha256HashPasswordImpl.java b/src/main/java/io/personium/core/auth/hash/Sha256HashPasswordImpl.java index 22114db1d..9165ec446 100644 --- a/src/main/java/io/personium/core/auth/hash/Sha256HashPasswordImpl.java +++ b/src/main/java/io/personium/core/auth/hash/Sha256HashPasswordImpl.java @@ -22,7 +22,7 @@ import org.apache.commons.lang.CharEncoding; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.core.model.ctl.Account; import io.personium.core.odata.OEntityWrapper; @@ -59,7 +59,7 @@ public String createHashPassword(String passwd) { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM_NAME); byte[] digestBytes = md.digest(str2hash.getBytes(CharEncoding.UTF_8)); //Although its data efficiency is better, this implementation is made for compatibility with DC 0. - return PersoniumCoreUtils.byteArray2HexString(digestBytes); + return CommonUtils.byteArray2HexString(digestBytes); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { diff --git a/src/main/java/io/personium/core/bar/BarFile.java b/src/main/java/io/personium/core/bar/BarFile.java index 0fdeaf63b..1817ded98 100644 --- a/src/main/java/io/personium/core/bar/BarFile.java +++ b/src/main/java/io/personium/core/bar/BarFile.java @@ -38,7 +38,7 @@ import org.apache.commons.io.Charsets; import org.apache.wink.webdav.model.Multistatus; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; /** @@ -47,7 +47,7 @@ public class BarFile implements Closeable { /** Content-Type of bar file. */ - public static final String CONTENT_TYPE = PersoniumCoreUtils.ContentType.CONTENT_TYPE_BAR; + public static final String CONTENT_TYPE = CommonUtils.ContentType.CONTENT_TYPE_BAR; /** Directory name : meta. */ private static final String META_DIR = "00_meta"; diff --git a/src/main/java/io/personium/core/bar/BarFileContentsInstallVisitor.java b/src/main/java/io/personium/core/bar/BarFileContentsInstallVisitor.java index 862cb034a..71d5763ea 100644 --- a/src/main/java/io/personium/core/bar/BarFileContentsInstallVisitor.java +++ b/src/main/java/io/personium/core/bar/BarFileContentsInstallVisitor.java @@ -70,7 +70,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.personium.common.es.util.PersoniumUUID; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreMessageUtils; import io.personium.core.PersoniumUnitConfig; @@ -1022,7 +1022,7 @@ private void registWebDavFile(String entryName, Path pathInZip) { if (aclElement != null) { StringBuffer sbAclXml = new StringBuffer(); sbAclXml.append(""); - sbAclXml.append(PersoniumCoreUtils.nodeToString(aclElement)); + sbAclXml.append(CommonUtils.nodeToString(aclElement)); Reader aclXml = new StringReader(sbAclXml.toString()); fileCmp.acl(aclXml); } @@ -1051,7 +1051,7 @@ private Reader getProppatchXml(List propElements) { sbPropXml.append(""); sbPropXml.append(""); for (Element element : propElements) { - sbPropXml.append(PersoniumCoreUtils.nodeToString(element)); + sbPropXml.append(CommonUtils.nodeToString(element)); } sbPropXml.append(""); sbPropXml.append(""); diff --git a/src/main/java/io/personium/core/bar/BarFileInstallRunner.java b/src/main/java/io/personium/core/bar/BarFileInstallRunner.java index efc179a98..945c8b218 100644 --- a/src/main/java/io/personium/core/bar/BarFileInstallRunner.java +++ b/src/main/java/io/personium/core/bar/BarFileInstallRunner.java @@ -51,8 +51,8 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import io.personium.common.utils.PersoniumCoreUtils; -import io.personium.common.utils.PersoniumCoreUtils.HttpMethod; +import io.personium.common.utils.CommonUtils; +import io.personium.common.utils.CommonUtils.HttpMethod; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreMessageUtils; import io.personium.core.bar.jackson.IJSONMappedObjects; @@ -740,7 +740,7 @@ private void registBoxAclAndProppatch(Box targetBox, Element aclElement, if (aclElement != null) { StringBuffer sbAclXml = new StringBuffer(); sbAclXml.append(""); - sbAclXml.append(PersoniumCoreUtils.nodeToString(aclElement)); + sbAclXml.append(CommonUtils.nodeToString(aclElement)); Reader aclXml = new StringReader(sbAclXml.toString()); boxCmp.acl(aclXml); } @@ -769,7 +769,7 @@ private Reader getProppatchXml(List propElements) { sbPropXml.append(""); sbPropXml.append(""); for (Element element : propElements) { - sbPropXml.append(PersoniumCoreUtils.nodeToString(element)); + sbPropXml.append(CommonUtils.nodeToString(element)); } sbPropXml.append(""); sbPropXml.append(""); @@ -825,7 +825,7 @@ private void createCollection(String collectionUrl, if (aclElement != null) { StringBuffer sbAclXml = new StringBuffer(); sbAclXml.append(""); - sbAclXml.append(PersoniumCoreUtils.nodeToString(aclElement)); + sbAclXml.append(CommonUtils.nodeToString(aclElement)); Reader aclXml = new StringReader(sbAclXml.toString()); collectionCmp.acl(aclXml); } diff --git a/src/main/java/io/personium/core/bar/BarFileInstaller.java b/src/main/java/io/personium/core/bar/BarFileInstaller.java index 3dc413629..1528f5fa6 100644 --- a/src/main/java/io/personium/core/bar/BarFileInstaller.java +++ b/src/main/java/io/personium/core/bar/BarFileInstaller.java @@ -1,6 +1,6 @@ /** - * personium.io - * Copyright 2014 FUJITSU LIMITED + * Personium + * Copyright 2014-2019 FUJITSU LIMITED * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,6 @@ import io.personium.common.utils.PersoniumThread; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; -import io.personium.core.auth.AccessContext; import io.personium.core.auth.CellPrivilege; import io.personium.core.bar.jackson.JSONManifest; import io.personium.core.model.Box; @@ -239,13 +238,11 @@ private void removeBarFile(File barFile) { */ private void checkPreConditions(Map headers) { //[403] Access control - AccessContext accessContext = this.oDataEntityResource.getAccessContext(); ODataResource odataResource = this.oDataEntityResource.getOdataResource(); - odataResource.checkAccessContext(accessContext, CellPrivilege.BOX_BAR_INSTALL); + odataResource.checkAccessContext(CellPrivilege.BOX_BAR_INSTALL); //[400] Request header format check checkHeaders(headers); - } /** @@ -311,7 +308,7 @@ public void sync(FileDescriptor fd) throws SyncFailedException { private File storeTemporaryBarFile(InputStream inStream) { //If there is no directory to store the bar file, it creates it. - String unitUserName = BarFileUtils.getUnitUserName(this.cell.getOwner()); + String unitUserName = BarFileUtils.getUnitUserName(this.cell.getOwnerNormalized()); File barFileDir = new File(new File(barTempDir, unitUserName), "bar"); if (!barFileDir.exists() && !barFileDir.mkdirs()) { String message = "unable create directory: " + barFileDir.getAbsolutePath(); diff --git a/src/main/java/io/personium/core/bar/BarFileReadRunner.java b/src/main/java/io/personium/core/bar/BarFileReadRunner.java index b1041b740..b36dbddac 100644 --- a/src/main/java/io/personium/core/bar/BarFileReadRunner.java +++ b/src/main/java/io/personium/core/bar/BarFileReadRunner.java @@ -82,8 +82,8 @@ import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import io.personium.common.es.util.PersoniumUUID; -import io.personium.common.utils.PersoniumCoreUtils; -import io.personium.common.utils.PersoniumCoreUtils.HttpMethod; +import io.personium.common.utils.CommonUtils; +import io.personium.common.utils.CommonUtils.HttpMethod; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreMessageUtils; import io.personium.core.PersoniumUnitConfig; @@ -876,7 +876,7 @@ protected boolean registWebDavFile(String entryName, InputStream inputStream, if (aclElement != null) { StringBuffer sbAclXml = new StringBuffer(); sbAclXml.append(""); - sbAclXml.append(PersoniumCoreUtils.nodeToString(aclElement)); + sbAclXml.append(CommonUtils.nodeToString(aclElement)); Reader aclXml = new StringReader(sbAclXml.toString()); fileCmp.acl(aclXml); } @@ -2111,7 +2111,7 @@ private void createCollection(String collectionUrl, if (aclElement != null) { StringBuffer sbAclXml = new StringBuffer(); sbAclXml.append(""); - sbAclXml.append(PersoniumCoreUtils.nodeToString(aclElement)); + sbAclXml.append(CommonUtils.nodeToString(aclElement)); Reader aclXml = new StringReader(sbAclXml.toString()); collectionCmp.acl(aclXml); } @@ -2137,7 +2137,7 @@ private void registBoxAclAndProppatch(Box targetBox, Element aclElement, if (aclElement != null) { StringBuffer sbAclXml = new StringBuffer(); sbAclXml.append(""); - sbAclXml.append(PersoniumCoreUtils.nodeToString(aclElement)); + sbAclXml.append(CommonUtils.nodeToString(aclElement)); Reader aclXml = new StringReader(sbAclXml.toString()); boxCmp.acl(aclXml); } @@ -2458,7 +2458,7 @@ private Reader getProppatchXml(List propElements) { sbPropXml.append(""); sbPropXml.append(""); for (Element element : propElements) { - sbPropXml.append(PersoniumCoreUtils.nodeToString(element)); + sbPropXml.append(CommonUtils.nodeToString(element)); } sbPropXml.append(""); sbPropXml.append(""); diff --git a/src/main/java/io/personium/core/eventlog/ArchiveLogCollection.java b/src/main/java/io/personium/core/eventlog/ArchiveLogCollection.java index 472697c56..550888d47 100644 --- a/src/main/java/io/personium/core/eventlog/ArchiveLogCollection.java +++ b/src/main/java/io/personium/core/eventlog/ArchiveLogCollection.java @@ -70,7 +70,7 @@ public ArchiveLogCollection(Cell cell, UriInfo uriInfo) { urlSb.append(uriInfo.getPath()); this.url = urlSb.toString(); - StringBuilder archiveDirName = EventUtils.getEventLogDir(cell.getId(), cell.getOwner()).append("archive"); + StringBuilder archiveDirName = EventUtils.getEventLogDir(cell.getId(), cell.getOwnerNormalized()).append("archive"); this.directoryPath = archiveDirName.toString(); } diff --git a/src/main/java/io/personium/core/jersey/filter/PersoniumCoreContainerFilter.java b/src/main/java/io/personium/core/jersey/filter/PersoniumCoreContainerFilter.java index 31749b481..161f634d4 100644 --- a/src/main/java/io/personium/core/jersey/filter/PersoniumCoreContainerFilter.java +++ b/src/main/java/io/personium/core/jersey/filter/PersoniumCoreContainerFilter.java @@ -39,8 +39,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.personium.common.utils.PersoniumCoreUtils; -import io.personium.common.utils.PersoniumCoreUtils.HttpHeaders; +import io.personium.common.utils.CommonUtils; +import io.personium.common.utils.CommonUtils.HttpHeaders; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumReadDeleteModeManager; import io.personium.core.PersoniumUnitConfig; @@ -120,7 +120,7 @@ public void filter(ContainerRequestContext requestContext, ContainerResponseCont private void overrideMethod(ContainerRequestContext requestContext) { if (HttpMethod.POST.equalsIgnoreCase(requestContext.getMethod())) { String overrideMethod = requestContext.getHeaders().getFirst( - PersoniumCoreUtils.HttpHeaders.X_HTTP_METHOD_OVERRIDE); + CommonUtils.HttpHeaders.X_HTTP_METHOD_OVERRIDE); if (overrideMethod != null && !overrideMethod.isEmpty()) { requestContext.setMethod(overrideMethod); } @@ -128,7 +128,7 @@ private void overrideMethod(ContainerRequestContext requestContext) { } private void overrideHeaders(ContainerRequestContext requestContext) { - List overrideHeaderList = requestContext.getHeaders().get(PersoniumCoreUtils.HttpHeaders.X_OVERRIDE); + List overrideHeaderList = requestContext.getHeaders().get(CommonUtils.HttpHeaders.X_OVERRIDE); if (overrideHeaderList == null) { return; } @@ -155,9 +155,9 @@ private void overrideHeaders(ContainerRequestContext requestContext) { private void overrideUri(ContainerRequestContext requestContext) { MultivaluedMap headers = requestContext.getHeaders(); - String xForwardedProto = headers.getFirst(PersoniumCoreUtils.HttpHeaders.X_FORWARDED_PROTO); - String xForwardedHost = headers.getFirst(PersoniumCoreUtils.HttpHeaders.X_FORWARDED_HOST); - String xForwardedPath = headers.getFirst(PersoniumCoreUtils.HttpHeaders.X_FORWARDED_PATH); + String xForwardedProto = headers.getFirst(CommonUtils.HttpHeaders.X_FORWARDED_PROTO); + String xForwardedHost = headers.getFirst(CommonUtils.HttpHeaders.X_FORWARDED_HOST); + String xForwardedPath = headers.getFirst(CommonUtils.HttpHeaders.X_FORWARDED_PATH); UriInfo uriInfo = requestContext.getUriInfo(); UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder(); @@ -195,12 +195,12 @@ private void checkOptionsMethod(String method, MultivaluedMap he HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.HEAD, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.MERGE, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.MKCOL, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.MOVE, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPPATCH, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.ACL + io.personium.common.utils.CommonUtils.HttpMethod.MERGE, + io.personium.common.utils.CommonUtils.HttpMethod.MKCOL, + io.personium.common.utils.CommonUtils.HttpMethod.MOVE, + io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND, + io.personium.common.utils.CommonUtils.HttpMethod.PROPPATCH, + io.personium.common.utils.CommonUtils.HttpMethod.ACL ).build(); //Do not pass control to the servlet by issuing an exception diff --git a/src/main/java/io/personium/core/model/Box.java b/src/main/java/io/personium/core/model/Box.java index add269f07..131e5113d 100644 --- a/src/main/java/io/personium/core/model/Box.java +++ b/src/main/java/io/personium/core/model/Box.java @@ -93,7 +93,7 @@ private static List> createSchemaAnnotation(final String name) /** * main box name. */ - public static final String DEFAULT_BOX_NAME = "__"; + public static final String MAIN_BOX_NAME = "__"; /** * Constructor. @@ -104,7 +104,7 @@ public Box(final Cell cell, final OEntity entity) { this.cell = cell; if (entity == null) { // Process for the MAIN BOX - this.name = Box.DEFAULT_BOX_NAME; + this.name = Box.MAIN_BOX_NAME; // Schema URL of MAIN BOX is the URL of its own cell this.schema = cell.getUrl(); // Internal ID of MAIN BOX will be together with the ID of the cell. diff --git a/src/main/java/io/personium/core/model/BoxUrlRsCmp.java b/src/main/java/io/personium/core/model/BoxUrlRsCmp.java index 17dd63447..04389e135 100644 --- a/src/main/java/io/personium/core/model/BoxUrlRsCmp.java +++ b/src/main/java/io/personium/core/model/BoxUrlRsCmp.java @@ -43,9 +43,11 @@ public BoxUrlRsCmp(final CellRsCmp cellRsCmp, final DavCmp davCmp, * {@inheritDoc} */ @Override - public void checkAccessContext(AccessContext ac, Privilege privilege) { + public void checkAccessContext(Privilege privilege) { AcceptableAuthScheme allowedAuthScheme = getAcceptableAuthScheme(); + AccessContext ac = this.getAccessContext(); + // For unit user token, do not check if (ac.isUnitUserToken(privilege)) { return; @@ -63,7 +65,7 @@ public void checkAccessContext(AccessContext ac, Privilege privilege) { ac.updateBasicAuthenticationStateForResource(null); // Check access control. - if (!this.hasPrivilege(ac, privilege)) { + if (!this.hasSubjectPrivilege(privilege)) { // If the token is INVALID or Privilege is set to all it is necessary to grant access. // For this reason, check the validity of the token at this timing. if (AccessContext.TYPE_INVALID.equals(ac.getType())) { diff --git a/src/main/java/io/personium/core/model/Cell.java b/src/main/java/io/personium/core/model/Cell.java index 3dc7fa1fc..a10a8e108 100644 --- a/src/main/java/io/personium/core/model/Cell.java +++ b/src/main/java/io/personium/core/model/Cell.java @@ -16,191 +16,377 @@ */ package io.personium.core.model; +import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.core4j.Enumerable; +import org.odata4j.core.OEntity; +import org.odata4j.core.OEntityKey; import org.odata4j.edm.EdmEntityType; import org.odata4j.edm.EdmProperty; import org.odata4j.edm.EdmSimpleType; +import org.odata4j.expression.BoolCommonExpression; +import org.odata4j.producer.EntitiesResponse; +import org.odata4j.producer.EntityResponse; +import org.odata4j.producer.InlineCount; +import org.odata4j.producer.ODataProducer; +import org.odata4j.producer.QueryInfo; +import org.odata4j.producer.resources.OptionsQueryParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import io.personium.common.auth.token.IExtRoleContainingToken; import io.personium.common.auth.token.Role; +import io.personium.core.PersoniumCoreException; +import io.personium.core.PersoniumUnitConfig; +import io.personium.core.auth.AuthUtils; +import io.personium.core.auth.ScopeArbitrator; import io.personium.core.event.EventBus; +import io.personium.core.model.ctl.Account; import io.personium.core.model.ctl.Common; +import io.personium.core.model.ctl.ExtCell; +import io.personium.core.model.ctl.ExtRole; +import io.personium.core.model.ctl.ReceivedMessage; +import io.personium.core.model.ctl.Relation; +import io.personium.core.model.ctl.Rule; +import io.personium.core.model.ctl.SentMessage; +import io.personium.core.model.impl.es.cache.BoxCache; +import io.personium.core.model.impl.es.odata.CellCtlODataProducer; +import io.personium.core.model.jaxb.Acl; import io.personium.core.odata.OEntityWrapper; +import io.personium.core.utils.UriUtils; +import net.spy.memcached.internal.CheckedOperationTimeoutException; /** * Model Class for Cell. */ -public interface Cell { +public abstract class Cell { + /** logger. */ + static Logger log = LoggerFactory.getLogger(Cell.class); + /** Edm.Entity Type Name. */ - String EDM_TYPE_NAME = "Cell"; + public static String EDM_TYPE_NAME = "Cell"; /** Status normal. */ - String STATUS_NORMAL = "normal"; + public static String STATUS_NORMAL = "normal"; /** Status import error. */ - String STATUS_IMPORT_ERROR = "import failed"; + public static String STATUS_IMPORT_ERROR = "import failed"; /** Error file name. */ - String IMPORT_ERROR_FILE_NAME = "import.error"; + public static String IMPORT_ERROR_FILE_NAME = "import.error"; /** Definition field of Name property. */ - EdmProperty.Builder P_NAME = EdmProperty.newBuilder("Name").setType(EdmSimpleType.STRING) + public static EdmProperty.Builder P_NAME = EdmProperty.newBuilder("Name").setType(EdmSimpleType.STRING) .setNullable(false).setAnnotations(Common.P_FORMAT_CELL_NAME); /** Property List. */ - List PROPS = Collections.unmodifiableList(Arrays.asList( + public static List PROPS = Collections.unmodifiableList(Arrays.asList( new EdmProperty.Builder[] {P_NAME, Common.P_PUBLISHED, Common.P_UPDATED} )); /** Key List. */ - List KEYS = Collections.unmodifiableList(Arrays.asList( + public static List KEYS = Collections.unmodifiableList(Arrays.asList( new String[] {P_NAME.getName()} ));; /** EntityType Builder of the Cell. */ - EdmEntityType.Builder EDM_TYPE_BUILDER = EdmEntityType.newBuilder().setNamespace(Common.EDM_NS_UNIT_CTL) + public static EdmEntityType.Builder EDM_TYPE_BUILDER = EdmEntityType.newBuilder().setNamespace(Common.EDM_NS_UNIT_CTL) .setName(EDM_TYPE_NAME).addProperties(Enumerable.create(PROPS).toList()).addKeys(KEYS); + protected String id; + protected String name; + protected String url; // Note: path base + protected String owner; + protected Long published; + /** - * returns Cell name. - * @return Cell name + * returns the Cell name. + * @return Cell Name */ - String getName(); + public String getName() { + return name; + } /** - * returns internal ID string. - * @return internal ID string + * Returns the internal ID of this Cell. + * @return internal identity string */ - String getId(); + public String getId() { + return this.id; + } + /** * returns URL string for this cell. * Return PathBaseURL or FQDNBaseURL depending on property setting. * @return URL string */ - String getUrl(); + public String getUrl() { + if (PersoniumUnitConfig.isPathBasedCellUrlEnabled()) { + return this.url; + } else { + return getFqdnBaseUrl(); + } + } /** * returns Cell base URL string for this cell. * Cell base url : "https://{cellname}.{domain}/". * @return Cell base URL string */ - String getFqdnBaseUrl(); + public String getFqdnBaseUrl() { + try { + return UriUtils.convertPathBaseToFqdnBase(url); + } catch (URISyntaxException e) { + // Usually it does not occur. + throw PersoniumCoreException.Server.UNKNOWN_ERROR.reason(e); + } + } + + /** * returns Cell base URL string for this cell. * Cell base url : "https://{domain}/{cellname}/". * @return Cell base URL string */ - String getPathBaseUrl(); + public String getPathBaseUrl() { + return url; + } /** * returns Unit URL string for this cell. * @return Unit URL string */ - String getUnitUrl(); + public String getUnitUrl() { + return PersoniumUnitConfig.getBaseUrl(); + } + /** + * Returns the normalized URI of the owner Unit User of this Cell. + * @return normalized owner url. + */ + public String getOwnerNormalized() { + return UriUtils.convertSchemeFromLocalUnitToHttp(this.owner); + } /** - * It gets the URI of the Cell of the Owner Unit User. - * @return Cell name + * Returns the raw URI of the owner Unit User of this Cell. + * @return raw owner url. */ - String getOwner(); + public String getOwnerRaw() { + return this.owner; + } /** - * It gets the prefix without Unit User name of the Cell. + * Returns the prefix without Unit User name of the Cell. * @return . */ - String getDataBundleNameWithOutPrefix(); + public abstract String getDataBundleNameWithOutPrefix(); /** - * It gets the Unit User name of the Cell. + * Returns the Unit User name of the Cell. * @return Unit User name */ - String getDataBundleName(); + public abstract String getDataBundleName(); /** - * It gets the EventBus of the Cell. + * Returns the EventBus of the Cell. * @return EventBus */ - EventBus getEventBus(); + public EventBus getEventBus() { + return new EventBus(this); + } /** - * It gets the Cell of creation time. + * Return the creation time of Cell. * @return time stamp of this cell creation. */ - long getPublished(); - + public long getPublished() { + return this.published; + } /** * Data and control objects under (Box, Account, etc.) if there is no return true.. * The default box may be. * @return It is true if there is no data and control objects under * (Box, Account, etc.). */ - boolean isEmpty(); + public boolean isEmpty() { + CellCtlODataProducer producer = new CellCtlODataProducer(this); + // check no box exists. + QueryInfo queryInfo = new QueryInfo(InlineCount.ALLPAGES, null, null, null, null, null, null, null, null); + if (producer.getEntitiesCount(Box.EDM_TYPE_NAME, queryInfo).getCount() > 0) { + return false; + } + + // check that Main Box is empty + Box defaultBox = this.getBoxForName(Box.MAIN_BOX_NAME); + BoxCmp defaultBoxCmp = ModelFactory.boxCmp(defaultBox); + if (!defaultBoxCmp.isEmpty()) { + return false; + } + + // check that no Cell Control Object exists + //In order to improve the TODO performance, change the type so as to check the value of c: (uuid of the cell) in the Type traversal + if (producer.getEntitiesCount(Account.EDM_TYPE_NAME, queryInfo).getCount() > 0 + || producer.getEntitiesCount(Role.EDM_TYPE_NAME, queryInfo).getCount() > 0 + || producer.getEntitiesCount(ExtCell.EDM_TYPE_NAME, queryInfo).getCount() > 0 + || producer.getEntitiesCount(ExtRole.EDM_TYPE_NAME, queryInfo).getCount() > 0 + || producer.getEntitiesCount(Relation.EDM_TYPE_NAME, queryInfo).getCount() > 0 + || producer.getEntitiesCount(SentMessage.EDM_TYPE_NAME, queryInfo).getCount() > 0 + || producer.getEntitiesCount(ReceivedMessage.EDM_TYPE_NAME, queryInfo).getCount() > 0 + || producer.getEntitiesCount(Rule.EDM_TYPE_NAME, queryInfo).getCount() > 0) { + return false; + } + // TODO check EventLog + return true; + } /** * To delete all the data and control objects in the underlying * (Box, Account, etc.). */ - void makeEmpty(); + public abstract void makeEmpty(); /** * delete this cell. * @param recursive set true if you want to delete recursively * @param unitUserName to use for deletion operation */ - void delete(boolean recursive, String unitUserName); + public abstract void delete(boolean recursive, String unitUserName); /** * Specify the Box name to get the Box. * @param boxName Box name * @return Box */ - Box getBoxForName(String boxName); + public Box getBoxForName(String boxName) { + if (Box.MAIN_BOX_NAME.equals(boxName)) { + return new Box(this, null); + } + + //Check the format of the Box name specified in URl. In case of invalid Because none of Box exists, return null + if (!validatePropertyRegEx(boxName, Common.PATTERN_NAME)) { + return null; + } + //Attempt to acquire the cached Box. + Box cachedBox = BoxCache.get(boxName, this); + if (cachedBox != null) { + return cachedBox; + } + + Box loadedBox = null; + try { + ODataProducer op = ModelFactory.ODataCtl.cellCtl(this); + EntityResponse er = op.getEntity(Box.EDM_TYPE_NAME, OEntityKey.create(boxName), null); + loadedBox = new Box(this, er.getEntity()); + BoxCache.cache(loadedBox); + return loadedBox; + } catch (RuntimeException e) { + if (e.getCause() instanceof CheckedOperationTimeoutException) { + return loadedBox; + } else { + return null; + } + } + } + /** + * Check the value of property item with regular expression. + * @param propValue + * Property value + * @param dcFormat + * Value of dcFormat + * @return In case of format error, return false + */ + protected static boolean validatePropertyRegEx(String propValue, String dcFormat) { + //Perform format check + Pattern pattern = Pattern.compile(dcFormat); + Matcher matcher = pattern.matcher(propValue); + if (!matcher.matches()) { + return false; + } + return true; + } /** * Specify the Box schema to get the Box. * @param boxSchema box schema uri * @return Box */ - Box getBoxForSchema(String boxSchema); - + public Box getBoxForSchema(String boxSchema) { + //Retrieving the schema name list (including aliases) + List boxSchemas = UriUtils.getUrlVariations(boxSchema); + + ODataProducer op = ModelFactory.ODataCtl.cellCtl(this); + for (int i = 0; i < boxSchemas.size(); i++) { + BoolCommonExpression filter = OptionsQueryParser.parseFilter("Schema eq '" + boxSchemas.get(i) + "'"); + QueryInfo qi = QueryInfo.newBuilder().setFilter(filter).build(); + try { + EntitiesResponse er = op.getEntities(Box.EDM_TYPE_NAME, qi); + List entList = er.getEntities(); + if (entList.size() == 1) { + return new Box(this, entList.get(0)); + } + continue; + } catch (RuntimeException e) { + return null; + } + } + return null; + } + + + public ScopeArbitrator getScopeArbitrator(String clientId, String grantType) { + Box box = this.getBoxForSchema(clientId); + return new ScopeArbitrator(this, box, grantType); + } /** * It gets the Accounts to specify the Account name. * @param username Account name * @return Account */ - OEntityWrapper getAccount(String username); - + public OEntityWrapper getAccount(final String username) { + ODataProducer op = ModelFactory.ODataCtl.cellCtl(this); + OEntityKey key = OEntityKey.create(username); + OEntityWrapper oew = null; + try { + EntityResponse resp = op.getEntity("Account", key, null); + oew = (OEntityWrapper) resp.getEntity(); + } catch (PersoniumCoreException dce) { + log.debug(dce.getMessage()); + } + return oew; + } /** * @param oew account * @param password password * @return true if authentication is successful. */ - boolean authenticateAccount(OEntityWrapper oew, String password); - + public boolean authenticateAccount(final OEntityWrapper oew, final String password) { + return AuthUtils.isMatchePassword(oew, password); + } /** * @param username access account id * @return List of Roles */ - List getRoleListForAccount(String username); + public abstract List getRoleListForAccount(String username); /** * Returns a list of roles should be given in this cell. * @param token Transformer cell access token * @return Role List */ - List getRoleListHere(IExtRoleContainingToken token); + public abstract List getRoleListHere(IExtRoleContainingToken token); /** * convert role internal id to role resource URL. * @param roleId internal id of a role. * @return URL string */ - String roleIdToRoleResourceUrl(String roleId); + public abstract String roleIdToRoleResourceUrl(String roleId); /** * convert role resource url to its internal id. @@ -208,5 +394,14 @@ public interface Cell { * @param baseUrl Base Url * @return internal id of the given role */ - String roleResourceUrlToId(String roleUrl, String baseUrl); + public abstract String roleResourceUrlToId(String roleUrl, String baseUrl); + + /** + * @return Cell Level ACL + */ + public Acl getAcl() { + CellCmp cc = ModelFactory.cellCmp(this); + return cc.getAcl(); + } + } diff --git a/src/main/java/io/personium/core/model/CellRsCmp.java b/src/main/java/io/personium/core/model/CellRsCmp.java index 591b0135a..d09d998ae 100644 --- a/src/main/java/io/personium/core/model/CellRsCmp.java +++ b/src/main/java/io/personium/core/model/CellRsCmp.java @@ -1,6 +1,6 @@ /** - * personium.io - * Copyright 2014-2018 FUJITSU LIMITED + * Personium + * Copyright 2014-2019 FUJITSU LIMITED * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,6 +42,7 @@ import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; +import io.personium.core.auth.CellPrivilege; import io.personium.core.auth.OAuth2Helper.AcceptableAuthScheme; import io.personium.core.auth.Privilege; import io.personium.core.utils.HttpClientFactory; @@ -128,6 +129,7 @@ public Box getBox() { /** * @return AccessContext */ + @Override public AccessContext getAccessContext() { return this.accessContext; } @@ -138,11 +140,13 @@ public AccessContext getAccessContext() { * @param privilege Privilege of ACL (read or write) * @return boolean */ - public boolean hasPrivilege(AccessContext ac, Privilege privilege) { + @Override + public boolean hasSubjectPrivilege(Privilege privilege) { - //If davCmp does not exist (resource that does not exist is specified) skip ACL check for that resource + // If davCmp does not exist (resource that does not exist is specified) + // skip ACL check for that resource if (this.davCmp != null - && this.getAccessContext().requirePrivilege(this.davCmp.getAcl(), privilege, this.getCell().getUrl())) { + && this.getAccessContext().hasSubjectPrivilegeForAcl(this.davCmp.getAcl(), privilege)) { return true; } return false; @@ -153,8 +157,10 @@ public boolean hasPrivilege(AccessContext ac, Privilege privilege) { * @param ac Access context * @param privilege Required privilege */ - public void checkAccessContext(AccessContext ac, Privilege privilege) { - // Check UnitUser token. + @Override + public void checkAccessContext(Privilege privilege) { + AccessContext ac = this.getAccessContext(); + // If UnitUser token, then OK. if (ac.isUnitUserToken(privilege)) { return; } @@ -163,9 +169,10 @@ public void checkAccessContext(AccessContext ac, Privilege privilege) { this.accessContext.updateBasicAuthenticationStateForResource(null); //Access right check - if (!this.hasPrivilege(ac, privilege)) { + if (!this.hasSubjectPrivilege(privilege)) { //Check the validity of the token - //Even if the token is INVALID, if the ACL setting and Privilege is set to all, it is necessary to permit access, so check at this timing + // Even if the token is INVALID, if the ACL setting and Privilege is set to all, + // it is necessary to permit access, so check at this timing if (AccessContext.TYPE_INVALID.equals(ac.getType())) { ac.throwInvalidTokenException(getAcceptableAuthScheme()); } else if (AccessContext.TYPE_ANONYMOUS.equals(ac.getType())) { @@ -174,6 +181,11 @@ public void checkAccessContext(AccessContext ac, Privilege privilege) { } throw PersoniumCoreException.Auth.NECESSARY_PRIVILEGE_LACKING; } + + if (privilege instanceof CellPrivilege + && !this.accessContext.hasScopeCellPrivilege((CellPrivilege)privilege)) { + throw PersoniumCoreException.Auth.INSUFFICIENT_SCOPE.params(privilege.getName()); + } } /** @@ -217,7 +229,7 @@ public HttpResponse requestGetRelayHtml() { } // Convert personium-localunit and personium-localcell. - relayHtmlUrl = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), relayHtmlUrl); + relayHtmlUrl = UriUtils.convertSchemeFromLocalUnitToHttp(relayHtmlUrl); relayHtmlUrl = UriUtils.convertSchemeFromLocalCellToHttp(cell.getUrl(), relayHtmlUrl); // Validate relayHtmlUrl. @@ -245,7 +257,7 @@ public HttpResponse requestGetAuthorizationHtml() { } // Convert personium-localunit and personium-localcell. - authorizationHtmlUrl = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), authorizationHtmlUrl); + authorizationHtmlUrl = UriUtils.convertSchemeFromLocalUnitToHttp(authorizationHtmlUrl); authorizationHtmlUrl = UriUtils.convertSchemeFromLocalCellToHttp(cell.getUrl(), authorizationHtmlUrl); // Validate relayHtmlUrl. @@ -274,8 +286,7 @@ public HttpResponse requestGetAuthorizationPasswordChangeHtml() { } // Convert personium-localunit and personium-localcell. - authorizationPasswordHtmlUrl = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), - authorizationPasswordHtmlUrl); + authorizationPasswordHtmlUrl = UriUtils.convertSchemeFromLocalUnitToHttp(authorizationPasswordHtmlUrl); authorizationPasswordHtmlUrl = UriUtils.convertSchemeFromLocalCellToHttp(cell.getUrl(), authorizationPasswordHtmlUrl); @@ -356,6 +367,23 @@ public List getAccountsNotRecordingAuthHistory() { return Arrays.asList(accounts); } + /** + * Check if the target account records authentication history. + * @param accountId account ID + * @param accountName account name + * @return "true" is records authentication history + */ + public boolean isRecordingAuthHistory(String accountId, String accountName) { + if (StringUtils.isEmpty(accountId) || StringUtils.isEmpty(accountName)) { + return false; + } + List ineligibleAccountList = this.getAccountsNotRecordingAuthHistory(); + if (ineligibleAccountList == null) { + return true; + } + return !ineligibleAccountList.contains(accountName); + } + /** * Obtain Auth Scheme that can be used for authentication. * Autret Scheme that can be used for @return authentication diff --git a/src/main/java/io/personium/core/model/DavRsCmp.java b/src/main/java/io/personium/core/model/DavRsCmp.java index ad6e0e70b..30db420b8 100644 --- a/src/main/java/io/personium/core/model/DavRsCmp.java +++ b/src/main/java/io/personium/core/model/DavRsCmp.java @@ -57,8 +57,7 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; -import io.personium.common.auth.token.Role; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreAuthzException; import io.personium.core.PersoniumCoreException; import io.personium.core.auth.AccessContext; @@ -235,7 +234,7 @@ public final Response doPropfind(final Reader requestBodyXml, final String depth // ACL config output is allowed by Unit User or when ACL Privilege is configured. boolean canAclRead = false; if (this.getAccessContext().isUnitUserToken(requiredForReadAcl) - || this.hasPrivilege(this.getAccessContext(), requiredForReadAcl)) { + || this.hasSubjectPrivilege(requiredForReadAcl)) { canAclRead = true; } @@ -381,8 +380,8 @@ public String getConfidentialLevel() { * @param privilege ACL Privilege (read/write/bind/unbind) * @return boolean */ - public boolean hasPrivilege(AccessContext ac, Privilege privilege) { - return hasPrivilege(ac, privilege, privilege); + public boolean hasSubjectPrivilege(Privilege privilege) { + return hasSubjectPrivilege( privilege, privilege); } /** @@ -392,16 +391,17 @@ public boolean hasPrivilege(AccessContext ac, Privilege privilege) { * @param parentPrivilege parent ACL Privilege (read/write/bind/unbind) If it is null, it does not refer to the parent's authority. * @return boolean */ - public boolean hasPrivilege(AccessContext ac, Privilege privilege, Privilege parentPrivilege) { + public boolean hasSubjectPrivilege(Privilege privilege, Privilege parentPrivilege) { // skip ACL check if davCmp does not exist. // (nonexistent resource is specified) if (privilege != null && this.davCmp != null - && this.getAccessContext().requirePrivilege(this.davCmp.getAcl(), privilege, this.getCell().getUrl())) { + && this.getAccessContext().hasSubjectPrivilegeForAcl(this.davCmp.getAcl(), privilege)) { return true; } // check parent (recursively) - if (parentPrivilege != null && this.parent != null && this.parent.hasPrivilege(ac, parentPrivilege)) { + if (parentPrivilege != null && this.parent != null + && this.parent.hasSubjectPrivilege(parentPrivilege)) { return true; } @@ -415,16 +415,16 @@ public boolean hasPrivilege(AccessContext ac, Privilege privilege, Privilege par @OPTIONS public Response options() { // AccessControl - this.checkAccessContext(this.getAccessContext(), BoxPrivilege.READ); + this.checkAccessContext(BoxPrivilege.READ); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.MKCOL, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPPATCH, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.ACL + io.personium.common.utils.CommonUtils.HttpMethod.MKCOL, + io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND, + io.personium.common.utils.CommonUtils.HttpMethod.PROPPATCH, + io.personium.common.utils.CommonUtils.HttpMethod.ACL ).build(); } @@ -434,8 +434,8 @@ public Response options() { * @param ac AccessContext * @param privilege Privilege to check if it is given */ - public void checkAccessContext(final AccessContext ac, Privilege privilege) { - checkAccessContext(ac, privilege, privilege); + public void checkAccessContext(Privilege privilege) { + checkAccessContext(privilege, privilege); } /** @@ -445,7 +445,8 @@ public void checkAccessContext(final AccessContext ac, Privilege privilege) { * @param privilege Privilege to check if it is given * @param parentPrivilege parent ACL Privilege */ - public void checkAccessContext(final AccessContext ac, Privilege privilege, Privilege parentPrivilege) { + public void checkAccessContext(Privilege privilege, Privilege parentPrivilege) { + AccessContext ac = this.getAccessContext(); // if accessed with valid UnitUserToken then fine. if (ac.isUnitUserToken(privilege)) { return; @@ -466,7 +467,7 @@ public void checkAccessContext(final AccessContext ac, Privilege privilege, Priv ac.updateBasicAuthenticationStateForResource(this.getBox()); // check Access Privilege - if (!this.hasPrivilege(ac, privilege, parentPrivilege)) { + if (!this.hasSubjectPrivilege(privilege, parentPrivilege)) { // check token validity // check here because access should be allowed when Privilege "all" is configured // even if the token is invalid @@ -488,7 +489,7 @@ public AcceptableAuthScheme getAcceptableAuthScheme() { // check if this resource if under a box with Schema URL String boxSchema = this.getBox().getSchema(); // only Bearer scheme is allowed if Box Schema URL is defined - if (boxSchema != null && boxSchema.length() > 0 && !Role.DEFAULT_BOX_NAME.equals(this.getBox().getName())) { + if (boxSchema != null && boxSchema.length() > 0 && !Box.MAIN_BOX_NAME.equals(this.getBox().getName())) { allowedAuthScheme = AcceptableAuthScheme.BEARER; } return allowedAuthScheme; @@ -591,8 +592,8 @@ static final org.apache.wink.webdav.model.Response createDavResponse(final Strin Resourcetype colRt = of.createResourcetype(); colRt.setCollection(of.createCollection()); List listElement = colRt.getAny(); - QName qname = new QName(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, PersoniumCoreUtils.XmlConst.ODATA, - PersoniumCoreUtils.XmlConst.NS_PREFIX_PERSONIUM); + QName qname = new QName(CommonUtils.XmlConst.NS_PERSONIUM, CommonUtils.XmlConst.ODATA, + CommonUtils.XmlConst.NS_PREFIX_PERSONIUM); Element element = WebDAVModelHelper.createElement(qname); listElement.add(element); ret.setPropertyOk(colRt); @@ -602,8 +603,8 @@ static final org.apache.wink.webdav.model.Response createDavResponse(final Strin Resourcetype colRt = of.createResourcetype(); colRt.setCollection(of.createCollection()); List listElement = colRt.getAny(); - QName qname = new QName(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, PersoniumCoreUtils.XmlConst.SERVICE, - PersoniumCoreUtils.XmlConst.NS_PREFIX_PERSONIUM); + QName qname = new QName(CommonUtils.XmlConst.NS_PERSONIUM, CommonUtils.XmlConst.SERVICE, + CommonUtils.XmlConst.NS_PREFIX_PERSONIUM); Element element = WebDAVModelHelper.createElement(qname); listElement.add(element); ret.setPropertyOk(colRt); @@ -613,8 +614,8 @@ static final org.apache.wink.webdav.model.Response createDavResponse(final Strin Resourcetype colRt = of.createResourcetype(); colRt.setCollection(of.createCollection()); List listElement = colRt.getAny(); - QName qname = new QName(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, PersoniumCoreUtils.XmlConst.STREAM, - PersoniumCoreUtils.XmlConst.NS_PREFIX_PERSONIUM); + QName qname = new QName(CommonUtils.XmlConst.NS_PERSONIUM, CommonUtils.XmlConst.STREAM, + CommonUtils.XmlConst.NS_PREFIX_PERSONIUM); Element element = WebDAVModelHelper.createElement(qname); listElement.add(element); ret.setPropertyOk(colRt); @@ -626,8 +627,8 @@ static final org.apache.wink.webdav.model.Response createDavResponse(final Strin ret.setPropertyOk(colRt); // Add cellstatus. - QName qname = new QName(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, PersoniumCoreUtils.XmlConst.CELL_STATUS, - PersoniumCoreUtils.XmlConst.NS_PREFIX_PERSONIUM); + QName qname = new QName(CommonUtils.XmlConst.NS_PERSONIUM, CommonUtils.XmlConst.CELL_STATUS, + CommonUtils.XmlConst.NS_PREFIX_PERSONIUM); Element element = WebDAVModelHelper.createElement(qname); element.setTextContent(dCmp.getCellStatus()); ret.setPropertyOk(element); diff --git a/src/main/java/io/personium/core/model/ModelFactory.java b/src/main/java/io/personium/core/model/ModelFactory.java index 4896911ea..73ab255db 100644 --- a/src/main/java/io/personium/core/model/ModelFactory.java +++ b/src/main/java/io/personium/core/model/ModelFactory.java @@ -26,7 +26,6 @@ import io.personium.core.model.impl.fs.BoxCmpFsImpl; import io.personium.core.model.impl.fs.CellCmpFsImpl; import io.personium.core.model.impl.fs.CellSnapshotCellCmpFsImpl; -import io.personium.core.odata.PersoniumODataProducer; /** * Factory class of model object. @@ -105,20 +104,20 @@ public static CellSnapshotCellCmp cellSnapshotCellCmp(final Cell cell) { */ public static class ODataCtl { /** - * Returns the ODataProducer handling the Unit management entity. + * Returns the ODataProducer handling the Unit control objects. * @param ac access context - * @return Unit ODataProducer handling management entities + * @return UnitCtlODataProducer */ - public static PersoniumODataProducer unitCtl(AccessContext ac) { + public static UnitCtlODataProducer unitCtl(AccessContext ac) { return new UnitCtlODataProducer(ac); } /** - * Returns the ODataProducer handling the Cell management entity. + * Returns the ODataProducer handling the Cell control objects. * @param cell Cell's Cell - * @return ODataProducer handling Cell management entities + * @return CellCtlODataProducer */ - public static PersoniumODataProducer cellCtl(final Cell cell) { + public static CellCtlODataProducer cellCtl(final Cell cell) { return new CellCtlODataProducer(cell); } @@ -126,9 +125,9 @@ public static PersoniumODataProducer cellCtl(final Cell cell) { * Return ODataProducer for producing OData about message. * @param cell target cell object * @param davRsCmp DavRsCmp - * @return PersoniumODataProducer MessageODataProducer + * @return MessageODataProducer MessageODataProducer */ - public static PersoniumODataProducer message(final Cell cell, final DavRsCmp davRsCmp) { + public static MessageODataProducer message(final Cell cell, final DavRsCmp davRsCmp) { return new MessageODataProducer(cell, davRsCmp); } @@ -136,9 +135,9 @@ public static PersoniumODataProducer message(final Cell cell, final DavRsCmp dav * Return ODataProducer of user data schema. * @param cell Cell * @param davCmp DavCmp - * @return ODataProducer + * @return UserSchemaODataProducer */ - public static PersoniumODataProducer userSchema(final Cell cell, final DavCmp davCmp) { + public static UserSchemaODataProducer userSchema(final Cell cell, final DavCmp davCmp) { return new UserSchemaODataProducer(cell, davCmp); } @@ -146,9 +145,9 @@ public static PersoniumODataProducer userSchema(final Cell cell, final DavCmp da * Return ODataProducer of user data. * @param cell Cell * @param davCmp DavCmp - * @return ODataProducer + * @return UserDataODataProducer */ - public static PersoniumODataProducer userData(final Cell cell, final DavCmp davCmp) { + public static UserDataODataProducer userData(final Cell cell, final DavCmp davCmp) { return new UserDataODataProducer(cell, davCmp); } diff --git a/src/main/java/io/personium/core/model/ctl/Common.java b/src/main/java/io/personium/core/model/ctl/Common.java index 4db287c6b..13afb8843 100644 --- a/src/main/java/io/personium/core/model/ctl/Common.java +++ b/src/main/java/io/personium/core/model/ctl/Common.java @@ -25,7 +25,7 @@ import org.odata4j.edm.EdmProperty; import org.odata4j.edm.EdmSimpleType; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; /** * Constant values commonly used in Edm. @@ -174,8 +174,8 @@ private Common() { /** * DC namespace. */ - public static final PrefixedNamespace P_NAMESPACE = new PrefixedNamespace(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, - PersoniumCoreUtils.XmlConst.NS_PREFIX_PERSONIUM); + public static final PrefixedNamespace P_NAMESPACE = new PrefixedNamespace(CommonUtils.XmlConst.NS_PERSONIUM, + CommonUtils.XmlConst.NS_PREFIX_PERSONIUM); /** * Name property. diff --git a/src/main/java/io/personium/core/model/impl/es/CellEsImpl.java b/src/main/java/io/personium/core/model/impl/es/CellEsImpl.java index c88f74fb0..6d0ffb39a 100644 --- a/src/main/java/io/personium/core/model/impl/es/CellEsImpl.java +++ b/src/main/java/io/personium/core/model/impl/es/CellEsImpl.java @@ -17,25 +17,19 @@ package io.personium.core.model.impl.es; import java.net.MalformedURLException; -import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import org.odata4j.core.OEntity; import org.odata4j.core.OEntityKey; import org.odata4j.core.OProperty; -import org.odata4j.expression.BoolCommonExpression; import org.odata4j.producer.EntitiesResponse; -import org.odata4j.producer.EntityResponse; import org.odata4j.producer.InlineCount; import org.odata4j.producer.ODataProducer; import org.odata4j.producer.QueryInfo; -import org.odata4j.producer.resources.OptionsQueryParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,11 +44,8 @@ import io.personium.core.PersoniumCoreLog; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; -import io.personium.core.auth.AuthUtils; -import io.personium.core.event.EventBus; import io.personium.core.eventlog.EventUtils; import io.personium.core.model.Box; -import io.personium.core.model.BoxCmp; import io.personium.core.model.Cell; import io.personium.core.model.CellCmp; import io.personium.core.model.CellSnapshotCellCmp; @@ -63,16 +54,12 @@ import io.personium.core.model.ctl.Common; import io.personium.core.model.ctl.ExtCell; import io.personium.core.model.ctl.ExtRole; -import io.personium.core.model.ctl.ReceivedMessage; import io.personium.core.model.ctl.Relation; -import io.personium.core.model.ctl.Rule; -import io.personium.core.model.ctl.SentMessage; import io.personium.core.model.file.BinaryDataAccessException; import io.personium.core.model.impl.es.accessor.CellAccessor; import io.personium.core.model.impl.es.accessor.CellDataAccessor; import io.personium.core.model.impl.es.accessor.EntitySetAccessor; import io.personium.core.model.impl.es.accessor.ODataLinkAccessor; -import io.personium.core.model.impl.es.cache.BoxCache; import io.personium.core.model.impl.es.cache.CellCache; import io.personium.core.model.impl.es.doc.CellDocHandler; import io.personium.core.model.impl.es.doc.OEntityDocHandler; @@ -86,18 +73,13 @@ /** * Cell object implemented using ElasticSearch. */ -public class CellEsImpl implements Cell { +public class CellEsImpl extends Cell { /** logger. */ static Logger log = LoggerFactory.getLogger(CellEsImpl.class); /** Es search result output upper limit. */ private static final int TOP_NUM = PersoniumUnitConfig.getEsTopNum(); - private String id; - private String name; - private String url; // Note: path base - private String owner; - private Long published; private Map json; /** @@ -136,7 +118,6 @@ public static Cell loadFromName(String cellName) { CellEsImpl cell = (CellEsImpl) findCell("s.Name.untouched", cellName); if (cell != null) { cell.url = PersoniumUnitConfig.getBaseUrl() + cell.name + "/"; - cell.owner = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), cell.owner); } return cell; } @@ -204,90 +185,6 @@ private static Cell findCell(String queryKey, String queryValue) { return ret; } - /** - * Check the value of property item with regular expression. - * @param propValue - * Property value - * @param dcFormat - * Value of dcFormat - * @return In case of format error, return false - */ - private static boolean validatePropertyRegEx(String propValue, String dcFormat) { - //Perform format check - Pattern pattern = Pattern.compile(dcFormat); - Matcher matcher = pattern.matcher(propValue); - if (!matcher.matches()) { - return false; - } - return true; - } - - /** - * Get the Cell name. - * @return Cell Name - */ - @Override - public String getName() { - return name; - } - - /** - * Returns the internal ID of this Cell. - * @return internal identity string - */ - @Override - public String getId() { - return this.id; - } - - /** - * Returns the URL of this Cell. - * @return URL string - */ - @Override - public String getUrl() { - if (PersoniumUnitConfig.isPathBasedCellUrlEnabled()) { - return this.url; - } else { - return getFqdnBaseUrl(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getFqdnBaseUrl() { - try { - return UriUtils.convertPathBaseToFqdnBase(url); - } catch (URISyntaxException e) { - // Usually it does not occur. - throw PersoniumCoreException.Server.UNKNOWN_ERROR; - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getPathBaseUrl() { - return url; - } - - /** - * Returns the Unit URL of this Cell. - * @return unitUrl string - */ - @Override - public String getUnitUrl() { - return PersoniumUnitConfig.getBaseUrl(); - } - - @Override - public String getOwner() { - return this.owner; - } - @Override public String getDataBundleNameWithOutPrefix() { String unitUserName; @@ -305,52 +202,6 @@ public String getDataBundleName() { return unitUserName; } - @Override - public EventBus getEventBus() { - return new EventBus(this); - } - - /** - * Return the creation time of Cell. - * @return Cell creation time - */ - @Override - public long getPublished() { - return this.published; - } - - @Override - public boolean isEmpty() { - CellCtlODataProducer producer = new CellCtlODataProducer(this); - // check no box exists. - QueryInfo queryInfo = new QueryInfo(InlineCount.ALLPAGES, null, null, null, null, null, null, null, null); - if (producer.getEntitiesCount(Box.EDM_TYPE_NAME, queryInfo).getCount() > 0) { - return false; - } - - // check that Main Box is empty - Box defaultBox = this.getBoxForName(Box.DEFAULT_BOX_NAME); - BoxCmp defaultBoxCmp = ModelFactory.boxCmp(defaultBox); - if (!defaultBoxCmp.isEmpty()) { - return false; - } - - // check that no Cell Control Object exists - //In order to improve the TODO performance, change the type so as to check the value of c: (uuid of the cell) in the Type traversal - if (producer.getEntitiesCount(Account.EDM_TYPE_NAME, queryInfo).getCount() > 0 - || producer.getEntitiesCount(Role.EDM_TYPE_NAME, queryInfo).getCount() > 0 - || producer.getEntitiesCount(ExtCell.EDM_TYPE_NAME, queryInfo).getCount() > 0 - || producer.getEntitiesCount(ExtRole.EDM_TYPE_NAME, queryInfo).getCount() > 0 - || producer.getEntitiesCount(Relation.EDM_TYPE_NAME, queryInfo).getCount() > 0 - || producer.getEntitiesCount(SentMessage.EDM_TYPE_NAME, queryInfo).getCount() > 0 - || producer.getEntitiesCount(ReceivedMessage.EDM_TYPE_NAME, queryInfo).getCount() > 0 - || producer.getEntitiesCount(Rule.EDM_TYPE_NAME, queryInfo).getCount() > 0) { - return false; - } - // TODO check EventLog - return true; - } - /** * {@inheritDoc} */ @@ -374,7 +225,7 @@ public void makeEmpty() { // Delete event log file. try { - EventUtils.deleteEventLog(this.getId(), this.getOwner()); + EventUtils.deleteEventLog(this.getId(), this.getOwnerNormalized()); } catch (BinaryDataAccessException e) { // If the deletion fails, output a log and continue processing. log.warn("Delete EventLog Failed." + cellInfoLog, e); @@ -428,81 +279,6 @@ public void run() { } }); thread.start(); - - } - - @Override - public Box getBoxForName(String boxName) { - if (Box.DEFAULT_BOX_NAME.equals(boxName)) { - return new Box(this, null); - } - - //Check the format of the Box name specified in URl. In case of invalid Because none of Box exists, return null - if (!validatePropertyRegEx(boxName, Common.PATTERN_NAME)) { - return null; - } - //Attempt to acquire the cached Box. - Box cachedBox = BoxCache.get(boxName, this); - if (cachedBox != null) { - return cachedBox; - } - - Box loadedBox = null; - try { - ODataProducer op = ModelFactory.ODataCtl.cellCtl(this); - EntityResponse er = op.getEntity(Box.EDM_TYPE_NAME, OEntityKey.create(boxName), null); - loadedBox = new Box(this, er.getEntity()); - BoxCache.cache(loadedBox); - return loadedBox; - } catch (RuntimeException e) { - if (e.getCause() instanceof CheckedOperationTimeoutException) { - return loadedBox; - } else { - return null; - } - } - } - - @Override - public Box getBoxForSchema(String boxSchema) { - //Retrieving the schema name list (including aliases) - List boxSchemas = UriUtils.getUrlVariations(this.getUnitUrl(), boxSchema); - - ODataProducer op = ModelFactory.ODataCtl.cellCtl(this); - for (int i = 0; i < boxSchemas.size(); i++) { - BoolCommonExpression filter = OptionsQueryParser.parseFilter("Schema eq '" + boxSchemas.get(i) + "'"); - QueryInfo qi = QueryInfo.newBuilder().setFilter(filter).build(); - try { - EntitiesResponse er = op.getEntities(Box.EDM_TYPE_NAME, qi); - List entList = er.getEntities(); - if (entList.size() == 1) { - return new Box(this, entList.get(0)); - } - continue; - } catch (RuntimeException e) { - return null; - } - } - return null; - } - - @Override - public OEntityWrapper getAccount(final String username) { - ODataProducer op = ModelFactory.ODataCtl.cellCtl(this); - OEntityKey key = OEntityKey.create(username); - OEntityWrapper oew = null; - try { - EntityResponse resp = op.getEntity("Account", key, null); - oew = (OEntityWrapper) resp.getEntity(); - } catch (PersoniumCoreException dce) { - log.debug(dce.getMessage()); - } - return oew; - } - - @Override - public boolean authenticateAccount(final OEntityWrapper oew, final String password) { - return AuthUtils.isMatchePassword(oew, password); } @SuppressWarnings("unchecked") @@ -656,7 +432,7 @@ public String roleResourceUrlToId(String roleUrl, String baseUrl) { } //It is not permitted to designate the cell URL portion of the role resource different from the cell URL of the ACL setting target - if (!(this.getUrl().equals(role.getBaseUrl()))) { + if (!UriUtils.equalIgnoringPort(this.getUrl(), role.getBaseUrl())) { PersoniumCoreLog.Dav.ROLE_NOT_FOUND.params("Cell different").writeLog(); throw PersoniumCoreException.Dav.ROLE_NOT_FOUND; } @@ -668,7 +444,7 @@ public String roleResourceUrlToId(String roleUrl, String baseUrl) { Map query = QueryMapFactory.filteredQuery(null, QueryMapFactory.mustQuery(queries)); List> filters = new ArrayList>(); - if (!(Box.DEFAULT_BOX_NAME.equals(role.getBoxName()))) { + if (!(Box.MAIN_BOX_NAME.equals(role.getBoxName()))) { //Add search queries when Role is tied to a box Box targetBox = this.getBoxForName(role.getBoxName()); if (targetBox == null) { @@ -757,7 +533,7 @@ private void waitCellAccessible(String cellId, int maxLoopCount, long interval) */ private void addRoleListExtCelltoRole(final IExtRoleContainingToken token, List roles) { //Acquisition of Role corresponding to ExtCell-Role binding - String extCell = token.getExtCellUrl(); + String extCell = token.getIssuer(); String principal = token.getSubject(); String principalCell; if (principal.contains("#")) { @@ -773,7 +549,7 @@ private void addRoleListExtCelltoRole(final IExtRoleContainingToken token, List< //Number of search result output setting QueryInfo qi = QueryInfo.newBuilder().setTop(TOP_NUM).setInlineCount(InlineCount.NONE).build(); - List list = UriUtils.getUrlVariations(this.getUnitUrl(), extCell); + List list = UriUtils.getUrlVariations(extCell); for (int i = 0; i < list.size(); i++) { String extCellUrl = list.get(i); try { @@ -822,7 +598,7 @@ private void addRoleListExtCelltoRelationAndExtRole(final IExtRoleContainingToke EntitiesResponse response = null; //Number of search result output setting QueryInfo qi = QueryInfo.newBuilder().setTop(TOP_NUM).setInlineCount(InlineCount.NONE).build(); - List list = UriUtils.getUrlVariations(this.getUnitUrl(), extCell); + List list = UriUtils.getUrlVariations(extCell); for (int i = 0; i < list.size(); i++) { try { String extCellUrl = list.get(i); @@ -989,4 +765,6 @@ private void addRole(String uuid, List roles) { roles.add(new Role(roleName, boxName, schema, this.url)); } + + } diff --git a/src/main/java/io/personium/core/model/impl/es/EsModel.java b/src/main/java/io/personium/core/model/impl/es/EsModel.java index 5715682cf..2228616d5 100644 --- a/src/main/java/io/personium/core/model/impl/es/EsModel.java +++ b/src/main/java/io/personium/core/model/impl/es/EsModel.java @@ -203,7 +203,7 @@ public static EntitySetAccessor cellCtl(final Cell cell, final String type) { } static EntitySetAccessor cell(final Cell cell, final String type) { - String userUri = cell.getOwner(); + String userUri = cell.getOwnerNormalized(); return new ODataEntityAccessor(idxUser(userUri), type, cell.getId()); } @@ -222,7 +222,7 @@ public static ODataLinkAccessor unitCtlLink(String cellId) { * @return Type object */ public static ODataLinkAccessor cellCtlLink(final Cell cell) { - String userUri = cell.getOwner(); + String userUri = cell.getOwnerNormalized(); return new ODataLinkAccessor(idxUser(userUri), TYPE_CTL_LINK, cell.getId()); } @@ -245,7 +245,7 @@ public static DataSourceAccessor batch() { * @return BulkDataAccessor */ public static DataSourceAccessor batch(final Cell cell) { - return new DataSourceAccessor(idxUser(cell.getOwner())); + return new DataSourceAccessor(idxUser(cell.getOwnerNormalized())); } /** diff --git a/src/main/java/io/personium/core/model/impl/es/odata/MessageODataProducer.java b/src/main/java/io/personium/core/model/impl/es/odata/MessageODataProducer.java index 06e0af8e9..600bda84c 100644 --- a/src/main/java/io/personium/core/model/impl/es/odata/MessageODataProducer.java +++ b/src/main/java/io/personium/core/model/impl/es/odata/MessageODataProducer.java @@ -165,7 +165,7 @@ public String changeStatusAndUpdateRelation(final EdmEntitySet entitySet, if (isValidCurrentStatus(currentStatus)) { if (ReceivedMessage.STATUS_APPROVED.equals(status)) { // check social privilege - davRsCmp.checkAccessContext(davRsCmp.getAccessContext(), CellPrivilege.SOCIAL); + davRsCmp.checkAccessContext(CellPrivilege.SOCIAL); // create or delete Relation String messageId = (String) staticFields.get(ReceivedMessage.P_ID.getName()); String boxName = (String) staticFields.get(Common.P_BOX_NAME.getName()); @@ -184,7 +184,7 @@ public String changeStatusAndUpdateRelation(final EdmEntitySet entitySet, if (isValidCurrentStatus(currentStatus)) { if (ReceivedMessage.STATUS_APPROVED.equals(status)) { // check social privilege - davRsCmp.checkAccessContext(davRsCmp.getAccessContext(), CellPrivilege.SOCIAL); + davRsCmp.checkAccessContext(CellPrivilege.SOCIAL); // create or delete Role String messageId = (String) staticFields.get(ReceivedMessage.P_ID.getName()); String boxName = (String) staticFields.get(Common.P_BOX_NAME.getName()); @@ -203,7 +203,7 @@ public String changeStatusAndUpdateRelation(final EdmEntitySet entitySet, if (isValidCurrentStatus(currentStatus)) { if (ReceivedMessage.STATUS_APPROVED.equals(status)) { // check rule privilege - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), CellPrivilege.RULE); + this.davRsCmp.checkAccessContext(CellPrivilege.RULE); // register or unregister rule String messageId = (String) staticFields.get(ReceivedMessage.P_ID.getName()); String boxName = (String) staticFields.get(Common.P_BOX_NAME.getName()); @@ -316,9 +316,9 @@ private void updateRelation(String messageId, String linkedBoxName, Map convertedExtCellKeyMap = new HashMap<>(); convertedExtCellKeyMap.put(Common.P_URL.getName(), convertedTargetUrl); @@ -470,9 +470,9 @@ private void updateRole(String messageId, String linkedBoxName, Map convertedExtCellKeyMap = new HashMap<>(); convertedExtCellKeyMap.put(Common.P_URL.getName(), convertedTargetUrl); @@ -694,7 +694,7 @@ protected String getNameFromClassUrl(String classUrl, String regex) { log.debug(String.format("ClassUrl = [%s]", classUrl)); // convert localunitUrl to unitUrl - String convertedRequestRelation = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), classUrl); + String convertedRequestRelation = UriUtils.convertSchemeFromLocalUnitToHttp(classUrl); Pattern pattern = Pattern.compile(regex); Matcher m = pattern.matcher(convertedRequestRelation); if (m.matches()) { @@ -718,7 +718,7 @@ protected String getBoxNameFromClassUrl(String classUrl, String regex) log.debug(String.format("RequestRelation = [%s]", classUrl)); // convert localunitUrl to unitUrl - String convertedRequestRelation = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), classUrl); + String convertedRequestRelation = UriUtils.convertSchemeFromLocalUnitToHttp(classUrl); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(convertedRequestRelation); if (matcher.matches()) { diff --git a/src/main/java/io/personium/core/model/impl/es/odata/ODataProducerUtils.java b/src/main/java/io/personium/core/model/impl/es/odata/ODataProducerUtils.java index 2d84111be..fe9fc1a38 100644 --- a/src/main/java/io/personium/core/model/impl/es/odata/ODataProducerUtils.java +++ b/src/main/java/io/personium/core/model/impl/es/odata/ODataProducerUtils.java @@ -34,7 +34,7 @@ import org.slf4j.LoggerFactory; import io.personium.common.es.response.PersoniumSearchHits; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AuthUtils; @@ -105,7 +105,7 @@ static void checkUniqueness(EsODataProducer producer, OEntityWrapper newEntity, Iterable> anots = edmProp.getAnnotations(); for (NamespacedAnnotation anot : anots) { if ("Unique".equals(anot.getName()) - && PersoniumCoreUtils.XmlConst.NS_PERSONIUM.equals(anot.getNamespace().getUri())) { + && CommonUtils.XmlConst.NS_PERSONIUM.equals(anot.getNamespace().getUri())) { String ukName = (String) anot.getValue(); List ukProps = uks.get(ukName); if (ukProps == null) { diff --git a/src/main/java/io/personium/core/model/impl/es/odata/UnitCtlODataProducer.java b/src/main/java/io/personium/core/model/impl/es/odata/UnitCtlODataProducer.java index bb793d0c7..1594351aa 100644 --- a/src/main/java/io/personium/core/model/impl/es/odata/UnitCtlODataProducer.java +++ b/src/main/java/io/personium/core/model/impl/es/odata/UnitCtlODataProducer.java @@ -76,8 +76,7 @@ protected List> getImplicitFilters(String entitySetName) { if (AccessContext.TYPE_UNIT_USER.equals(this.accesscontext.getType()) || AccessContext.TYPE_UNIT_LOCAL.equals(this.accesscontext.getType())) { // Search for matching owner in http format or localunit format. - String localOwner = UriUtils.convertSchemeFromHttpToLocalUnit( - accesscontext.getBaseUri(), accesscontext.getSubject()); + String localOwner = UriUtils.convertSchemeFromHttpToLocalUnit(accesscontext.getSubject()); List> orQueries = new ArrayList>(); orQueries.add(QueryMapFactory.termQuery(OEntityDocHandler.KEY_OWNER, accesscontext.getSubject())); orQueries.add(QueryMapFactory.termQuery(OEntityDocHandler.KEY_OWNER, localOwner)); diff --git a/src/main/java/io/personium/core/model/impl/fs/DavCmpFsImpl.java b/src/main/java/io/personium/core/model/impl/fs/DavCmpFsImpl.java index 60097994d..24a0da7d2 100644 --- a/src/main/java/io/personium/core/model/impl/fs/DavCmpFsImpl.java +++ b/src/main/java/io/personium/core/model/impl/fs/DavCmpFsImpl.java @@ -64,7 +64,8 @@ import io.personium.common.auth.token.Role; import io.personium.common.es.response.PersoniumGetResponse; import io.personium.common.es.util.IndexNameEncoder; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; +import io.personium.core.ElapsedTimeLog; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; import io.personium.core.ElapsedTimeLog; @@ -424,7 +425,7 @@ public Multistatus proppatch(final Propertyupdate propUpdate, final String url) for (Element elem : lpe) { res.setProperty(elem, HttpStatus.SC_OK); String key = elem.getLocalName() + PROP_KEY_SEPARATOR + elem.getNamespaceURI(); - String value = PersoniumCoreUtils.nodeToString(elem); + String value = CommonUtils.nodeToString(elem); log.debug("key: " + key); log.debug("val: " + value); propsJson.put(key, value); @@ -738,7 +739,7 @@ public final ResponseBuilder get(final String rangeHeaderField) { endLog.setParams(fileSize / KILO_BYTES); endLog.writeLog(); - return res.header(HttpHeaders.ETAG, getEtag()).header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, + return res.header(HttpHeaders.ETAG, getEtag()).header(CommonUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); } catch (BinaryDataNotFoundException nex) { @@ -784,7 +785,7 @@ private ResponseBuilder davFileResponseForRange(final StreamingOutput sout, Stri //I have returned Content - Length to the clear because I can not process Chunked 's Range response in iPad' s safari. return javax.ws.rs.core.Response.status(HttpStatus.SC_PARTIAL_CONTENT).entity(sout) - .header(PersoniumCoreUtils.HttpHeaders.CONTENT_RANGE, brs.makeContentRangeHeaderField()) + .header(CommonUtils.HttpHeaders.CONTENT_RANGE, brs.makeContentRangeHeaderField()) .header(HttpHeaders.CONTENT_LENGTH, brs.getContentLength()) .header(HttpHeaders.CONTENT_TYPE, contentType); } @@ -924,7 +925,7 @@ public ResponseBuilder move(String etag, String overwrite, DavDestination davDes //In the MOVE method, the source and the destination Box are the same, so even if you acquire the destination access context, //Even if you acquire the access context of the source, you can get the same Object //Therefore, we use the access context of the move destination - AccessContext ac = davDestination.getDestinationRsCmp().getAccessContext(); + //AccessContext ac = davDestination.getDestinationRsCmp().getAccessContext(); //Access control to the destination //For the following reasons, access is controlled to the destination after locking. @@ -932,12 +933,12 @@ public ResponseBuilder move(String etag, String overwrite, DavDestination davDes //2. When performing access control of the move destination before locking, it is necessary to acquire the information of the move destination, and a request to the ES occurs. File destDir = ((DavCmpFsImpl) davDestination.getDestinationCmp()).fsDir; if (!davDestination.getDestinationCmp().exists()) { - davDestination.getDestinationRsCmp().getParent().checkAccessContext(ac, BoxPrivilege.BIND); + davDestination.getDestinationRsCmp().getParent().checkAccessContext(BoxPrivilege.BIND); Files.move(this.fsDir.toPath(), destDir.toPath()); res = javax.ws.rs.core.Response.status(HttpStatus.SC_CREATED); } else { - davDestination.getDestinationRsCmp().getParent().checkAccessContext(ac, BoxPrivilege.BIND); - davDestination.getDestinationRsCmp().getParent().checkAccessContext(ac, BoxPrivilege.UNBIND); + davDestination.getDestinationRsCmp().getParent().checkAccessContext(BoxPrivilege.BIND); + davDestination.getDestinationRsCmp().getParent().checkAccessContext(BoxPrivilege.UNBIND); FileUtils.deleteDirectory(destDir); Files.move(this.fsDir.toPath(), destDir.toPath(), StandardCopyOption.REPLACE_EXISTING); res = javax.ws.rs.core.Response.status(HttpStatus.SC_NO_CONTENT); @@ -1066,7 +1067,7 @@ public void makeEmpty() { * @return instance of accessor */ protected BinaryDataAccessor getBinaryDataAccessor() { - String owner = cell.getOwner(); + String owner = cell.getOwnerNormalized(); String unitUserName = null; if (owner == null) { unitUserName = AccessContext.TYPE_ANONYMOUS; @@ -1186,7 +1187,7 @@ private String createBaseUrlStr() { //In case of Cell level ACL, the resource URL of default box //Since cell URLs are attached with slashes in concatenation, erase the URL if it ends with a slash. result = String.format(Role.ROLE_RESOURCE_FORMAT, this.cell.getUrl().replaceFirst("/$", ""), - Box.DEFAULT_BOX_NAME, ""); + Box.MAIN_BOX_NAME, ""); } return result; } diff --git a/src/main/java/io/personium/core/model/jaxb/Acl.java b/src/main/java/io/personium/core/model/jaxb/Acl.java index b7ebf0348..88569122a 100644 --- a/src/main/java/io/personium/core/model/jaxb/Acl.java +++ b/src/main/java/io/personium/core/model/jaxb/Acl.java @@ -36,13 +36,14 @@ import org.json.simple.parser.ParseException; import io.personium.common.auth.token.Role; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.auth.AccessContext; import io.personium.core.auth.BoxPrivilege; import io.personium.core.auth.CellPrivilege; import io.personium.core.auth.OAuth2Helper; import io.personium.core.auth.Privilege; +import io.personium.core.utils.UriUtils; /** * A model object representing an ACL. @@ -65,7 +66,7 @@ public final class Acl { String base; /** p:requireSchemaAuthz. */ - @XmlAttribute(namespace = PersoniumCoreUtils.XmlConst.NS_PERSONIUM) + @XmlAttribute(namespace = CommonUtils.XmlConst.NS_PERSONIUM) String requireSchemaAuthz; /** Ace tag.*/ @@ -93,7 +94,7 @@ public String getRequireSchemaAuthz() { * @param base baseUrl */ public void setBase(String base) { - this.base = base; + this.base = UriUtils.convertSchemeFromHttpToLocalUnit(base); } /** @@ -101,7 +102,7 @@ public void setBase(String base) { * @return base */ public String getBase() { - return base; + return UriUtils.convertSchemeFromLocalUnitToHttp(base); } /** @@ -199,7 +200,7 @@ public boolean allows(final Privilege priv, final AccessContext ac, Map getResources() { factory.setNamespaceAware(true); try { String prop = this.davCmp.getPropertyAsRawString(PROP_ELEMENT_QUEUES, - PersoniumCoreUtils.XmlConst.NS_PERSONIUM); + CommonUtils.XmlConst.NS_PERSONIUM); if (prop == null) { return queues; } @@ -72,7 +72,7 @@ protected List getResources() { InputStream is = new ByteArrayInputStream(prop.getBytes(CharEncoding.UTF_8)); Document doc = builder.parse(is); Element element = doc.getDocumentElement(); - NodeList nl = element.getElementsByTagNameNS(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, + NodeList nl = element.getElementsByTagNameNS(CommonUtils.XmlConst.NS_PERSONIUM, PROP_ELEMENT_QUEUE); for (int i = 0; i < nl.getLength(); i++) { queues.add(nl.item(i).getTextContent()); diff --git a/src/main/java/io/personium/core/rs/box/StreamResource.java b/src/main/java/io/personium/core/rs/box/StreamResource.java index 3e2d8d631..53c4c10ef 100644 --- a/src/main/java/io/personium/core/rs/box/StreamResource.java +++ b/src/main/java/io/personium/core/rs/box/StreamResource.java @@ -16,9 +16,9 @@ */ package io.personium.core.rs.box; -import java.net.URI; import java.io.IOException; import java.io.InputStream; +import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -137,7 +137,7 @@ public Response options(@PathParam("name") String name) { List allow = new ArrayList<>(); try { - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.STREAM_SEND); + this.davRsCmp.checkAccessContext(BoxPrivilege.STREAM_SEND); allow.add(HttpMethod.POST); allow.add(HttpMethod.PUT); } catch (Exception e) { @@ -145,7 +145,7 @@ public Response options(@PathParam("name") String name) { } try { - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.STREAM_RECEIVE); + this.davRsCmp.checkAccessContext(BoxPrivilege.STREAM_RECEIVE); allow.add(HttpMethod.GET); } catch (Exception e) { logger.debug("no privilege for receive"); @@ -187,8 +187,7 @@ private String getUrl(String name) { */ private String createDestination(String name) { // convert to localunit url - String localunit = UriUtils.convertSchemeFromHttpToLocalUnit(this.davRsCmp.getCell().getUnitUrl(), - getUrl(name)); + String localunit = UriUtils.convertSchemeFromHttpToLocalUnit(getUrl(name)); try { URI uri = new URI(localunit); return Stream.of(uri.getPath().split(Pattern.quote("/"))) @@ -217,7 +216,7 @@ private void checkExistence(final String name) { */ private Response receiveCommon(String name) { // access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.STREAM_RECEIVE); + this.davRsCmp.checkAccessContext(BoxPrivilege.STREAM_RECEIVE); // resource exist? checkExistence(name); @@ -236,7 +235,7 @@ private Response receiveCommon(String name) { */ private Response sendCommon(String name, InputStream is) { // access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.STREAM_SEND); + this.davRsCmp.checkAccessContext(BoxPrivilege.STREAM_SEND); // resource exist? checkExistence(name); diff --git a/src/main/java/io/personium/core/rs/box/StreamTopicResource.java b/src/main/java/io/personium/core/rs/box/StreamTopicResource.java index ea375c545..7436ba05a 100644 --- a/src/main/java/io/personium/core/rs/box/StreamTopicResource.java +++ b/src/main/java/io/personium/core/rs/box/StreamTopicResource.java @@ -30,7 +30,7 @@ import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.model.DavCmp; import io.personium.core.model.DavRsCmp; @@ -63,7 +63,7 @@ protected List getResources() { factory.setNamespaceAware(true); try { String prop = this.davCmp.getPropertyAsRawString(PROP_ELEMENT_TOPICS, - PersoniumCoreUtils.XmlConst.NS_PERSONIUM); + CommonUtils.XmlConst.NS_PERSONIUM); if (prop == null) { return topics; } @@ -71,7 +71,7 @@ protected List getResources() { InputStream is = new ByteArrayInputStream(prop.getBytes(CharEncoding.UTF_8)); Document doc = builder.parse(is); Element element = doc.getDocumentElement(); - NodeList nl = element.getElementsByTagNameNS(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, + NodeList nl = element.getElementsByTagNameNS(CommonUtils.XmlConst.NS_PERSONIUM, PROP_ELEMENT_TOPIC); for (int i = 0; i < nl.getLength(); i++) { topics.add(nl.item(i).getTextContent()); diff --git a/src/main/java/io/personium/core/rs/cell/AuthResourceUtils.java b/src/main/java/io/personium/core/rs/cell/AuthResourceUtils.java index 505decc3c..0b7790a36 100644 --- a/src/main/java/io/personium/core/rs/cell/AuthResourceUtils.java +++ b/src/main/java/io/personium/core/rs/cell/AuthResourceUtils.java @@ -23,9 +23,7 @@ import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; -import java.util.List; -import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,7 +31,6 @@ import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AuthHistoryLastFile; import io.personium.core.model.Cell; -import io.personium.core.model.CellRsCmp; import io.personium.core.model.lock.AccountLockManager; import io.personium.core.model.lock.AccountValidAuthnIntervalLockManager; import io.personium.core.model.lock.Lock; @@ -196,24 +193,6 @@ public static void updateAuthHistoryLastFileWithFailed(String fsPath, String acc } } - /** - * Check if the target account records authentication history. - * @param cellRsCmp cell rs cmp - * @param accountId account ID - * @param accountName account name - * @return "true" is records authentication history - */ - public static boolean isRecordingAuthHistory(CellRsCmp cellRsCmp, String accountId, String accountName) { - if (StringUtils.isEmpty(accountId) || StringUtils.isEmpty(accountName)) { - return false; - } - List ineligibleAccountList = cellRsCmp.getAccountsNotRecordingAuthHistory(); - if (ineligibleAccountList == null) { - return true; - } - return !ineligibleAccountList.contains(accountName); - } - /** * Process to check if an Account valid authentication interval lock exists. * @param accountId account ID diff --git a/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java b/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java index c2957bf8b..d7683b896 100644 --- a/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java @@ -57,19 +57,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import io.personium.common.auth.token.AbstractLocalToken; import io.personium.common.auth.token.AbstractOAuth2Token; import io.personium.common.auth.token.AbstractOAuth2Token.TokenDsigException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenRootCrtException; -import io.personium.common.auth.token.AccountAccessToken; -import io.personium.common.auth.token.CellLocalAccessToken; +import io.personium.common.auth.token.GrantCode; import io.personium.common.auth.token.IAccessToken; import io.personium.common.auth.token.IdToken; -import io.personium.common.auth.token.LocalToken; import io.personium.common.auth.token.PasswordChangeAccessToken; +import io.personium.common.auth.token.ResidentLocalAccessToken; import io.personium.common.auth.token.Role; -import io.personium.common.auth.token.UnitLocalUnitUserToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; import io.personium.core.PersoniumCoreMessageUtils; @@ -78,6 +77,7 @@ import io.personium.core.auth.AuthUtils; import io.personium.core.auth.OAuth2Helper; import io.personium.core.auth.OAuth2Helper.Key; +import io.personium.core.auth.ScopeArbitrator; import io.personium.core.model.Box; import io.personium.core.model.Cell; import io.personium.core.model.CellCmp; @@ -173,7 +173,7 @@ public final Response authGet( @QueryParam(Key.REDIRECT_URI) final String redirectUri, @CookieParam(FacadeResource.P_COOKIE_KEY) final String pCookie, @QueryParam(Key.STATE) final String state, - @QueryParam(Key.SCOPE) final String scope, + @QueryParam(Key.SCOPE) final String scopeStr, @QueryParam(Key.KEEPLOGIN) final String keepLogin, @QueryParam(Key.CANCEL_FLG) final String isCancel, @QueryParam(Key.EXPIRES_IN) final String expiresInStr, @@ -181,7 +181,7 @@ public final Response authGet( @QueryParam(Key.PASSWORD_CHANGE_REQUIRED) final String passwordChangeRequiredStr, @Context final UriInfo uriInfo, @HeaderParam("X-Forwarded-For") final String xForwardedFor) { - + String[] scope = AbstractOAuth2Token.Scope.parse(scopeStr); return auth(false, responseType, clientId, redirectUri, null, null, pCookie, state, scope, keepLogin, isCancel, expiresInStr, uriInfo, xForwardedFor, accessTokenStr, passwordChangeRequiredStr); } @@ -215,7 +215,8 @@ public final Response authPost( String accessTokenStr = formParams.getFirst(Key.ACCESS_TOKEN); String passwordChangeRequiredStr = formParams.getFirst(Key.PASSWORD_CHANGE_REQUIRED); - return auth(true, responseType, clientId, redirectUri, username, password, pCookie, state, scope, keepLogin, + return auth(true, responseType, clientId, redirectUri, username, password, pCookie, state, + AbstractOAuth2Token.Scope.parse(scope), keepLogin, isCancel, expiresInStr, uriInfo, xForwardedFor, accessTokenStr, passwordChangeRequiredStr); } @@ -255,7 +256,7 @@ private Response auth( // CHECKSTYLE IGNORE final String password, final String pCookie, final String state, - final String scope, + final String[] scope, final String keepLogin, final String isCancel, final String expiresInStr, @@ -295,13 +296,17 @@ private Response auth( // CHECKSTYLE IGNORE OAuth2Helper.Error.INVALID_REQUEST, state, "PR400-AZ-0008"); } } + // scope arbitration + ScopeArbitrator sa = this.cell.getScopeArbitrator(clientId, OAuth2Helper.GrantType.AUTHORIZATION_CODE); + String[] assignedScopes = sa.request(scope).getResults(); + // response_type = token || response_type = code || (response_type = id_token && scope = openid) if (!OAuth2Helper.ResponseType.TOKEN.equals(responseType) && !OAuth2Helper.ResponseType.CODE.equals(responseType) && (!OAuth2Helper.ResponseType.ID_TOKEN.equals(responseType) || OAuth2Helper.ResponseType.ID_TOKEN.equals(responseType) - && !OAuth2Helper.Scope.OPENID.equals(scope))) { + && !OAuth2Helper.Scope.OPENID.equals(assignedScopes[0]))) { return this.returnErrorRedirect(responseType, redirectUri, OAuth2Helper.Error.UNSUPPORTED_RESPONSE_TYPE, state, "PR400-AZ-0001"); } @@ -317,15 +322,15 @@ private Response auth( // CHECKSTYLE IGNORE if (accessTokenStr != null && !accessTokenStr.isEmpty()) { //password change and authentication return handlePasswordChange(responseType, clientId, redirectUri, accessTokenStr, - password, state, scope, keepLogin, expiresIn); + password, state, assignedScopes, keepLogin, expiresIn); } else if (username != null || password != null) { //When there is a setting in either user ID or password Response response = handlePassword(responseType, clientId, redirectUri, - username, password, state, scope, keepLogin, expiresIn); + username, password, state, assignedScopes, keepLogin, expiresIn); return response; } else if (pCookie != null) { return handlePCookie(isPost, responseType, clientId, redirectUri, - pCookie, state, scope, keepLogin, expiresIn, uriInfo); + pCookie, state, assignedScopes, keepLogin, expiresIn, uriInfo); } else { //If user ID, password, cookie are not specified, return returnFormRedirect(responseType, clientId, redirectUri, @@ -335,8 +340,9 @@ private Response auth( // CHECKSTYLE IGNORE if (Boolean.parseBoolean(passwordChangeRequiredStr)) { return returnPasswordChangeHtmlForm(clientId); } else if (pCookie != null) { + return handlePCookie(isPost, responseType, clientId, redirectUri, - pCookie, state, scope, keepLogin, expiresIn, uriInfo); + pCookie, state, assignedScopes, keepLogin, expiresIn, uriInfo); } else { return returnHtmlForm(clientId); } @@ -357,7 +363,7 @@ private Response auth( // CHECKSTYLE IGNORE * @return JAX-RS Response */ private Response handlePasswordChange(String responseType, String clientId, String redirectUri, String apTokenStr, - String newPassword, String state, String scope, String keepLogin, long expiresIn) { + String newPassword, String state, String[] scope, String keepLogin, long expiresIn) { if (newPassword == null || StringUtils.isEmpty(newPassword)) { return returnFormRedirect(responseType, clientId, redirectUri, OAuth2Helper.Error.INVALID_REQUEST, state, CODE_PASSWORD_CHANGE_NO_PASS, scope, apTokenStr, true); @@ -437,7 +443,7 @@ private Response handlePasswordChange(String responseType, String clientId, Stri * @return JAX-RS Response */ private Response handlePassword(String responseType, String clientId, String redirectUri, // CHECKSTYLE IGNORE - String username, String password, String state, String scope, String keepLogin, long expiresIn) { + String username, String password, String state, String[] scope, String keepLogin, long expiresIn) { //If both user ID and password are unspecified, return login error if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { return returnFormRedirect(responseType, clientId, redirectUri, @@ -467,7 +473,7 @@ private Response handlePassword(String responseType, String clientId, String red } // Check if the target account records authentication history. - isRecordingAuthHistory = AuthResourceUtils.isRecordingAuthHistory(cellRsCmp, accountId, username); + isRecordingAuthHistory = cellRsCmp.isRecordingAuthHistory(accountId, username); //Check valid authentication interval if (isLockedInterval) { @@ -550,7 +556,7 @@ private Response handlePassword(String responseType, String clientId, String red if (passwordChangeRequired) { //Issue password change. PasswordChangeAccessToken apToken = new PasswordChangeAccessToken( - issuedAt, expiresIn, getIssuerUrl(), username, schema); + issuedAt, expiresIn, getIssuerUrl(), username, schema, scope); return returnFormRedirect(responseType, clientId, redirectUri, OAuth2Helper.Error.UNAUTHORIZED_CLIENT, state, CODE_PASSWORD_CHANGE_REQUIRED, scope, apToken.toTokenString(), true); } @@ -565,22 +571,22 @@ private Response handlePassword(String responseType, String clientId, String red //Respond with 303 and return Location header //Returning cell local token if (OAuth2Helper.ResponseType.TOKEN.equals(responseType)) { - AccountAccessToken aToken = new AccountAccessToken(issuedAt, expiresIn, - getIssuerUrl(), username, schema); + ResidentLocalAccessToken aToken = new ResidentLocalAccessToken(issuedAt, expiresIn, + getIssuerUrl(), username, schema, AbstractOAuth2Token.Scope.EMPTY); paramMap.put(OAuth2Helper.Key.ACCESS_TOKEN, aToken.toTokenString()); paramMap.put(OAuth2Helper.Key.TOKEN_TYPE, OAuth2Helper.Scheme.BEARER); paramMap.put(OAuth2Helper.Key.EXPIRES_IN, String.valueOf(aToken.expiresIn())); } else if (OAuth2Helper.ResponseType.CODE.equals(responseType)) { List roleList = cell.getRoleListForAccount(username); - CellLocalAccessToken aToken = new CellLocalAccessToken(issuedAt, - CellLocalAccessToken.CODE_EXPIRES, getIssuerUrl(), username, roleList, schema, scope); - paramMap.put(OAuth2Helper.Key.CODE, aToken.toCodeString()); + GrantCode aToken = new GrantCode(issuedAt, + GrantCode.CODE_EXPIRES, getIssuerUrl(), username, roleList, schema, scope); + paramMap.put(OAuth2Helper.Key.CODE, aToken.toTokenString()); } } else { CellCmp cellCmp = (CellCmp) cellRsCmp.getDavCmp(); CellKeysFile cellKeysFile = cellCmp.getCellKeys().getCellKeysFile(); long issuedAtSec = issuedAt / AbstractOAuth2Token.MILLISECS_IN_A_SEC; - long expiryTime = issuedAtSec + AbstractOAuth2Token.SECS_IN_A_HOUR; + long expiryTime = issuedAtSec + AbstractOAuth2Token.SECS_IN_AN_HOUR; IdToken idToken = new IdToken( cellKeysFile.getKeyId(), AlgorithmUtils.RS_SHA_256_ALGO, getIssuerUrl(), username, schema, expiryTime, issuedAtSec, cellKeysFile.getPrivateKey()); @@ -630,17 +636,14 @@ private Response handlePassword(String responseType, String clientId, String red * @return JAX-RS Response */ private Response handlePCookie(boolean isPost, String responseType, String clientId, String redirectUri, - String pCookie, String state, String scope, String keepLogin, long expiresIn, UriInfo uriInfo) { + String pCookie, String state, String[] scope, String keepLogin, long expiresIn, UriInfo uriInfo) { //Cookie authentication //Get decrypted value of cookie value AbstractOAuth2Token token; + String authToken; try { - String decodedCookieValue = LocalToken.decode(pCookie, - UnitLocalUnitUserToken.getIvBytes( - AccessContext.getCookieCryptKey(uriInfo.getBaseUri().getHost()))); - int separatorIndex = decodedCookieValue.indexOf("\t"); - //Obtain authorizationHeader equivalent token from information in cookie - String authToken = decodedCookieValue.substring(separatorIndex + 1); + authToken = AbstractLocalToken.parseCookie(pCookie, null, + AccessContext.getCookieCryptKey(uriInfo.getBaseUri().getHost()), false); token = AbstractOAuth2Token.parse(authToken, getIssuerUrl(), cell.getUnitUrl()); @@ -683,23 +686,23 @@ private Response handlePCookie(boolean isPost, String responseType, String clien String username = token.getSubject(); if (OAuth2Helper.ResponseType.TOKEN.equals(responseType)) { - AccountAccessToken aToken = new AccountAccessToken(issuedAt, expiresIn, - getIssuerUrl(), username, clientId); + ResidentLocalAccessToken aToken = new ResidentLocalAccessToken(issuedAt, expiresIn, + getIssuerUrl(), username, clientId, AbstractOAuth2Token.Scope.EMPTY); paramMap.put(OAuth2Helper.Key.ACCESS_TOKEN, aToken.toTokenString()); paramMap.put(OAuth2Helper.Key.TOKEN_TYPE, OAuth2Helper.Scheme.BEARER); paramMap.put(OAuth2Helper.Key.EXPIRES_IN, String.valueOf(aToken.expiresIn())); } else if (OAuth2Helper.ResponseType.CODE.equals(responseType)) { List roleList = cell.getRoleListForAccount(token.getSubject()); - CellLocalAccessToken aToken = new CellLocalAccessToken(issuedAt, - CellLocalAccessToken.CODE_EXPIRES, getIssuerUrl(), username, roleList, clientId, scope); - paramMap.put(OAuth2Helper.Key.CODE, aToken.toCodeString()); + GrantCode aToken = new GrantCode(issuedAt, + GrantCode.CODE_EXPIRES, getIssuerUrl(), username, roleList, clientId, scope); + paramMap.put(OAuth2Helper.Key.CODE, aToken.toTokenString()); } } else { CellCmp cellCmp = (CellCmp) cellRsCmp.getDavCmp(); CellKeysFile cellKeysFile = cellCmp.getCellKeys().getCellKeysFile(); String subject = token.getSubject(); long issuedAtSec = issuedAt / AbstractOAuth2Token.MILLISECS_IN_A_SEC; - long expiryTime = issuedAtSec + AbstractOAuth2Token.SECS_IN_A_HOUR; + long expiryTime = issuedAtSec + AbstractOAuth2Token.SECS_IN_AN_HOUR; IdToken idToken = new IdToken( cellKeysFile.getKeyId(), AlgorithmUtils.RS_SHA_256_ALGO, getIssuerUrl(), subject, clientId, expiryTime, issuedAtSec, cellKeysFile.getPrivateKey()); @@ -732,7 +735,7 @@ private Response handlePCookie(boolean isPost, String responseType, String clien * @return response */ private Response returnHandlePCookieFailedResponse(boolean isPost, String responseType, String clientId, - String redirectUri, String error, String state, String code, String scope) { + String redirectUri, String error, String state, String code, String[] scope) { if (isPost) { // It redirects at POST. return returnFormRedirect(responseType, clientId, redirectUri, error, state, code, scope); @@ -884,7 +887,7 @@ private Response returnErrorRedirect(String responseType, String redirectUri, St * @return response (redirect to the authentication form) */ private Response returnFormRedirect(String responseType, String clientId, String redirectUri, - String error, String state, String code, String scope) { + String error, String state, String code, String[] scope) { return returnFormRedirect(responseType, clientId, redirectUri, error, state, code, scope, null, false); } @@ -902,7 +905,7 @@ private Response returnFormRedirect(String responseType, String clientId, String * @return response (redirect to the authentication form) */ private Response returnFormRedirect(String responseType, String clientId, String redirectUri, - String error, String state, String code, String scope, String accessTokenStr, + String error, String state, String code, String[] scope, String accessTokenStr, boolean passwordChangeRequired) { //Respond with 303 and return Location header ResponseBuilder rb = Response.status(Status.SEE_OTHER) @@ -926,9 +929,10 @@ private Response returnFormRedirect(String responseType, String clientId, String .append("=").append(URLEncoder.encode(state, CharEncoding.UTF_8)); } // scope - if (StringUtils.isNotEmpty(scope)) { + if (scope != null && scope.length > 0) { + String scopeStr = URLEncoder.encode(AbstractOAuth2Token.Scope.toConcatValue(scope), CharEncoding.UTF_8); sbuf.append("&").append(OAuth2Helper.Key.SCOPE) - .append("=").append(URLEncoder.encode(scope, CharEncoding.UTF_8)); + .append("=").append(URLEncoder.encode(scopeStr, CharEncoding.UTF_8)); } // access_token if (StringUtils.isNotEmpty(accessTokenStr)) { @@ -1012,9 +1016,9 @@ private String createForm(String clientId) { //title paramsList.add(PersoniumCoreMessageUtils.getMessage("PS-AU-0001")); //Ansel's profile.json - paramsList.add(clientId + Box.DEFAULT_BOX_NAME + PROFILE_JSON_NAME); + paramsList.add(clientId + Box.MAIN_BOX_NAME + PROFILE_JSON_NAME); //Data cell profile.json - paramsList.add(cell.getUrl() + Box.DEFAULT_BOX_NAME + PROFILE_JSON_NAME); + paramsList.add(cell.getUrl() + Box.MAIN_BOX_NAME + PROFILE_JSON_NAME); //title paramsList.add(PersoniumCoreMessageUtils.getMessage("PS-AU-0001")); //Callee @@ -1024,7 +1028,7 @@ private String createForm(String clientId) { Object[] params = paramsList.toArray(); - String html = PersoniumCoreUtils.readStringResource("html/authform.html", CharEncoding.UTF_8); + String html = CommonUtils.readStringResource("html/authform.html", CharEncoding.UTF_8); html = MessageFormat.format(html, params); return html; @@ -1084,9 +1088,9 @@ private String createPasswordChangeForm(String clientId) { //title paramsList.add(PersoniumCoreMessageUtils.getMessage("PS-AU-0001")); //Ansel's profile.json - paramsList.add(clientId + Box.DEFAULT_BOX_NAME + PROFILE_JSON_NAME); + paramsList.add(clientId + Box.MAIN_BOX_NAME + PROFILE_JSON_NAME); //Data cell profile.json - paramsList.add(cell.getUrl() + Box.DEFAULT_BOX_NAME + PROFILE_JSON_NAME); + paramsList.add(cell.getUrl() + Box.MAIN_BOX_NAME + PROFILE_JSON_NAME); //title paramsList.add(PersoniumCoreMessageUtils.getMessage("PS-AU-0001")); //Callee @@ -1096,7 +1100,7 @@ private String createPasswordChangeForm(String clientId) { Object[] params = paramsList.toArray(); - String html = PersoniumCoreUtils.readStringResource("html/authform_passwordchange.html", + String html = CommonUtils.readStringResource("html/authform_passwordchange.html", CharEncoding.UTF_8); html = MessageFormat.format(html, params); diff --git a/src/main/java/io/personium/core/rs/cell/BoxUrlResource.java b/src/main/java/io/personium/core/rs/cell/BoxUrlResource.java index 82d96c9e1..64dd7d043 100644 --- a/src/main/java/io/personium/core/rs/cell/BoxUrlResource.java +++ b/src/main/java/io/personium/core/rs/cell/BoxUrlResource.java @@ -24,7 +24,7 @@ import org.apache.http.HttpStatus; import org.json.simple.JSONObject; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.auth.AccessContext; import io.personium.core.auth.BoxPrivilege; @@ -38,7 +38,7 @@ import io.personium.core.utils.ODataUtils; /** - * JOX-RS Resource for obtaining Box URL. + * JAX-RS Resource for obtaining Box URL. */ public class BoxUrlResource { @@ -105,7 +105,7 @@ public final Response boxUrl(@QueryParam("schema") final String querySchema) { //Validity check of the authentication token (such as tokens that have expired) DavCmp davCmp = ModelFactory.boxCmp(box); DavRsCmp boxUrlRsCmp = new BoxUrlRsCmp(this.cellRsCmp, davCmp, this.accessContext, box); - boxUrlRsCmp.checkAccessContext(this.accessContext, BoxPrivilege.READ); + boxUrlRsCmp.checkAccessContext(BoxPrivilege.READ); // Response body JSONObject responseBody = new JSONObject(); @@ -113,7 +113,7 @@ public final Response boxUrl(@QueryParam("schema") final String querySchema) { //Return response return Response.status(HttpStatus.SC_OK) - .header(PersoniumCoreUtils.HttpHeaders.ACCESS_CONTROLE_EXPOSE_HEADERS, HttpHeaders.LOCATION) + .header(CommonUtils.HttpHeaders.ACCESS_CONTROLE_EXPOSE_HEADERS, HttpHeaders.LOCATION) .header(HttpHeaders.LOCATION, box.getUrl()) .entity(responseBody.toJSONString()) .build(); diff --git a/src/main/java/io/personium/core/rs/cell/CellCtlResource.java b/src/main/java/io/personium/core/rs/cell/CellCtlResource.java index fcee5aa51..b4f0d0349 100644 --- a/src/main/java/io/personium/core/rs/cell/CellCtlResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellCtlResource.java @@ -29,7 +29,6 @@ import org.odata4j.core.OProperty; import io.personium.core.PersoniumCoreException; -import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; import io.personium.core.auth.AuthUtils; import io.personium.core.auth.CellPrivilege; @@ -39,7 +38,7 @@ import io.personium.core.event.PersoniumEvent; import io.personium.core.event.PersoniumEventType; import io.personium.core.model.Box; -import io.personium.core.model.DavRsCmp; +import io.personium.core.model.CellRsCmp; import io.personium.core.model.ModelFactory; import io.personium.core.model.ctl.Account; import io.personium.core.model.ctl.Common; @@ -56,43 +55,42 @@ import io.personium.core.utils.UriUtils; /** - * JAX-RS Resource handling DC Cell Level Api. + * JAX-RS Resource handling Personium Cell control objects. */ public final class CellCtlResource extends ODataResource { - String pCredHeader; - DavRsCmp davRsCmp; + CellRsCmp cellRsCmp; /** * constructor. * @param accessContext AccessContext * @param pCredHeader X-Personium-Credential header - * @param davRsCmp davRsCmp + * @param cellRsCmp davRsCmp */ - public CellCtlResource(final AccessContext accessContext, final String pCredHeader, DavRsCmp davRsCmp) { + public CellCtlResource(final AccessContext accessContext, final String pCredHeader, CellRsCmp cellRsCmp) { super(accessContext, UriUtils.SCHEME_LOCALCELL + ":/__ctl/", ModelFactory.ODataCtl.cellCtl(accessContext .getCell())); this.pCredHeader = pCredHeader; - this.davRsCmp = davRsCmp; + this.cellRsCmp = cellRsCmp; } @Override - public void checkAccessContext(final AccessContext ac, Privilege privilege) { - this.davRsCmp.checkAccessContext(ac, privilege); + public void checkAccessContext(Privilege privilege) { + this.cellRsCmp.checkAccessContext(privilege); } /** * Obtain Auth Scheme that can be used for authentication. - * Autret Scheme that can be used for @return authentication + * @return Auth Scheme that can be used for authentication */ @Override public AcceptableAuthScheme getAcceptableAuthScheme() { - return this.davRsCmp.getAcceptableAuthScheme(); + return this.cellRsCmp.getAcceptableAuthScheme(); } @Override - public boolean hasPrivilege(AccessContext ac, Privilege privilege) { - return this.davRsCmp.hasPrivilege(ac, privilege); + public boolean hasPrivilege(Privilege privilege) { + return this.cellRsCmp.hasSubjectPrivilege(privilege); } @Override @@ -285,8 +283,7 @@ public void validate(String entitySetName, List> props) { } } - String error = validateRule(PersoniumUnitConfig.getBaseUrl(), - external, subject, type, object, info, action, targetUrl, boxBound); + String error = validateRule(external, subject, type, object, info, action, targetUrl, boxBound); if (error != null) { throw PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(error); } @@ -306,16 +303,15 @@ public void validate(String entitySetName, List> props) { * @param boxBound flag of box bounded * @return property name of format error */ - public static String validateRule(String unitUrl, - Boolean external, String subject, + public static String validateRule(Boolean external, String subject, String type, String object, String info, String action, String targetUrl, Boolean boxBound) { // check if convert scheme to localunit - String converted = UriUtils.convertSchemeFromHttpToLocalUnit(unitUrl, subject); + String converted = UriUtils.convertSchemeFromHttpToLocalUnit(subject); if (converted != null && !converted.equals(subject)) { return Rule.P_SUBJECT.getName(); } - converted = UriUtils.convertSchemeFromHttpToLocalUnit(unitUrl, targetUrl); + converted = UriUtils.convertSchemeFromHttpToLocalUnit(targetUrl); if (converted != null && !converted.equals(targetUrl)) { return Rule.P_TARGETURL.getName(); } @@ -480,7 +476,7 @@ private void postEventInternal(String type, String object, String info) { .type(type) .object(object) .info(info) - .davRsCmp(this.davRsCmp) + .davRsCmp(this.cellRsCmp) .build(); EventBus eventBus = this.getAccessContext().getCell().getEventBus(); eventBus.post(ev); diff --git a/src/main/java/io/personium/core/rs/cell/CellExportResource.java b/src/main/java/io/personium/core/rs/cell/CellExportResource.java index 407d9918c..d8519b477 100644 --- a/src/main/java/io/personium/core/rs/cell/CellExportResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellExportResource.java @@ -72,7 +72,7 @@ public CellExportResource(CellRsCmp cellRsCmp) { @GET public Response get() { // Check the authority required for execution. - cellRsCmp.checkAccessContext(cellRsCmp.getAccessContext(), CellPrivilege.ROOT); + this.cellRsCmp.checkAccessContext(CellPrivilege.ROOT); // Get processing status from cache. // If it returns null, it is regarded as ready state. @@ -96,7 +96,7 @@ public Response get() { @POST public Response post(final Reader reader) { // Check the authority required for execution. - cellRsCmp.checkAccessContext(cellRsCmp.getAccessContext(), CellPrivilege.ROOT); + cellRsCmp.checkAccessContext(CellPrivilege.ROOT); // Reading body. String name = null; @@ -135,7 +135,7 @@ public Response post(final Reader reader) { @OPTIONS public Response options() { // Check the authority required for execution. - cellRsCmp.checkAccessContext(cellRsCmp.getAccessContext(), CellPrivilege.ROOT); + cellRsCmp.checkAccessContext(CellPrivilege.ROOT); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, HttpMethod.POST diff --git a/src/main/java/io/personium/core/rs/cell/CellImportResource.java b/src/main/java/io/personium/core/rs/cell/CellImportResource.java index f2e84ece7..7937f0177 100644 --- a/src/main/java/io/personium/core/rs/cell/CellImportResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellImportResource.java @@ -75,7 +75,7 @@ public CellImportResource(CellRsCmp cellRsCmp) { @GET public Response get() { // Check the authority required for execution. - cellRsCmp.checkAccessContext(cellRsCmp.getAccessContext(), CellPrivilege.ROOT); + cellRsCmp.checkAccessContext(CellPrivilege.ROOT); String jsonString = ""; if (Cell.STATUS_NORMAL.equals(cellRsCmp.getDavCmp().getCellStatus())) { @@ -111,7 +111,7 @@ public Response get() { @POST public Response post(final Reader reader) { // Check the authority required for execution. - cellRsCmp.checkAccessContext(cellRsCmp.getAccessContext(), CellPrivilege.ROOT); + cellRsCmp.checkAccessContext(CellPrivilege.ROOT); // Reading body. JSONObject body; @@ -141,7 +141,7 @@ public Response post(final Reader reader) { @OPTIONS public Response options() { // Check the authority required for execution. - cellRsCmp.checkAccessContext(cellRsCmp.getAccessContext(), CellPrivilege.ROOT); + cellRsCmp.checkAccessContext(CellPrivilege.ROOT); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, HttpMethod.POST diff --git a/src/main/java/io/personium/core/rs/cell/CellResource.java b/src/main/java/io/personium/core/rs/cell/CellResource.java index 8aba21a65..c0e09137b 100644 --- a/src/main/java/io/personium/core/rs/cell/CellResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellResource.java @@ -44,7 +44,7 @@ import org.slf4j.LoggerFactory; import io.personium.common.es.util.IndexNameEncoder; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreAuthzException; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; @@ -129,7 +129,7 @@ public CellResource( private void checkReferenceMode() { Cell cellObj = accessContext.getCell(); String unitPrefix = PersoniumUnitConfig.getEsUnitPrefix(); - String owner = cellObj.getOwner(); + String owner = cellObj.getOwnerNormalized(); if (owner == null) { owner = "anon"; @@ -216,15 +216,15 @@ public void write(final OutputStream os) throws IOException { @WriteAPI @DELETE public Response cellBulkDeletion( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { //If the specification of the X-Personium-Recursive header is not "true", it is an error if (!"true".equals(recursiveHeader)) { throw PersoniumCoreException.Misc.PRECONDITION_FAILED.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); } //Confirm the access authority //Unit Master, Unit User, Unit Local Unit User except authority error - String cellOwner = this.cell.getOwner(); + String cellOwner = this.cell.getOwnerNormalized(); checkAccessContextForCellBulkDeletion(cellOwner); String cellId = this.cell.getId(); @@ -275,19 +275,19 @@ private void checkAccessContextForCellBulkDeletion(String cellOwner) { */ @Path("__ctl") public CellCtlResource ctl( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL) final String pCredHeader) { + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL) final String pCredHeader) { return new CellCtlResource(this.accessContext, pCredHeader, this.cellRsCmp); } /** - * Endpoint of password change API. + * Endpoint of my password change API. * @param pCredHeader pCredHeader * @return Response */ @Path("__mypassword") - public PasswordResource mypassword( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL) final String pCredHeader) { - return new PasswordResource(this.accessContext, pCredHeader, this.cell, this.cellRsCmp); + public MyPasswordResource mypassword( + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL) final String pCredHeader) { + return new MyPasswordResource(this.accessContext, pCredHeader, this.cell, this.cellRsCmp); } /** @@ -379,13 +379,13 @@ public RuleResource rule() { } /** - * Access to the default box. + * Access to the main box. * @param jaxRsRequest HTTP request for JAX-RS * @return BoxResource Object */ @Path("__") public BoxResource box(@Context final Request jaxRsRequest) { - return new BoxResource(this.cell, Box.DEFAULT_BOX_NAME, this.accessContext, + return new BoxResource(this.cell, Box.MAIN_BOX_NAME, this.accessContext, this.cellRsCmp, jaxRsRequest); } @@ -460,11 +460,11 @@ public BoxResource box( */ @PROPFIND public Response propfind(final Reader requestBodyXml, - @DefaultValue("0") @HeaderParam(PersoniumCoreUtils.HttpHeaders.DEPTH) final String depth, + @DefaultValue("0") @HeaderParam(CommonUtils.HttpHeaders.DEPTH) final String depth, @HeaderParam(HttpHeaders.CONTENT_LENGTH) final Long contentLength, @HeaderParam("Transfer-Encoding") final String transferEncoding) { // Access Control - this.cellRsCmp.checkAccessContext(this.cellRsCmp.getAccessContext(), CellPrivilege.PROPFIND); + this.cellRsCmp.checkAccessContext(CellPrivilege.PROPFIND); Response response = this.cellRsCmp.doPropfind(requestBodyXml, depth, contentLength, @@ -536,7 +536,7 @@ public Response proppatch(final Reader requestBodyXml) { @ACL public Response acl(final Reader reader) { //Access control - this.cellRsCmp.checkAccessContext(this.cellRsCmp.getAccessContext(), CellPrivilege.ACL); + this.cellRsCmp.checkAccessContext(CellPrivilege.ACL); Response response = this.cellRsCmp.doAcl(reader); // post event to EventBus @@ -562,10 +562,10 @@ public Response acl(final Reader reader) { @OPTIONS public Response options() { //Access control - this.cellRsCmp.checkAccessContext(this.cellRsCmp.getAccessContext(), CellPrivilege.SOCIAL_READ); + this.cellRsCmp.checkAccessContext(CellPrivilege.SOCIAL_READ); return ResourceUtils.responseBuilderForOptions( HttpMethod.POST, - PersoniumCoreUtils.HttpMethod.PROPFIND + CommonUtils.HttpMethod.PROPFIND ).build(); } diff --git a/src/main/java/io/personium/core/rs/cell/CellSnapshotDavFileResource.java b/src/main/java/io/personium/core/rs/cell/CellSnapshotDavFileResource.java index f1507d1c1..27f2adce4 100644 --- a/src/main/java/io/personium/core/rs/cell/CellSnapshotDavFileResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellSnapshotDavFileResource.java @@ -29,7 +29,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.annotations.PROPFIND; import io.personium.core.annotations.REPORT; @@ -70,7 +70,7 @@ public Response get( // Check exist checkFileExists(); // Access Control - davRsCmp.getParent().checkAccessContext(davRsCmp.getAccessContext(), CellPrivilege.ROOT); + davRsCmp.getParent().checkAccessContext(CellPrivilege.ROOT); ResponseBuilder rb = davRsCmp.get(ifNoneMatch, null); return rb.build(); } @@ -94,7 +94,7 @@ public Response put(@HeaderParam(HttpHeaders.CONTENT_TYPE) final String contentT @HeaderParam(HttpHeaders.IF_MATCH) final String ifMatch, final InputStream inputStream) { // Access Control - davRsCmp.getParent().checkAccessContext(davRsCmp.getAccessContext(), CellPrivilege.ROOT); + davRsCmp.getParent().checkAccessContext(CellPrivilege.ROOT); ResponseBuilder rb = davRsCmp.getDavCmp().putForUpdate(contentType, inputStream, ifMatch); return rb.build(); @@ -111,7 +111,7 @@ public Response delete(@HeaderParam(HttpHeaders.IF_MATCH) final String ifMatch) // Check exist checkFileExists(); // Access Control - davRsCmp.getParent().checkAccessContext(davRsCmp.getAccessContext(), CellPrivilege.ROOT); + davRsCmp.getParent().checkAccessContext(CellPrivilege.ROOT); ResponseBuilder rb = davRsCmp.getDavCmp().delete(ifMatch, false); return rb.build(); } @@ -126,13 +126,13 @@ public Response delete(@HeaderParam(HttpHeaders.IF_MATCH) final String ifMatch) */ @PROPFIND public Response propfind(final Reader requestBodyXml, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.DEPTH) final String depth, + @HeaderParam(CommonUtils.HttpHeaders.DEPTH) final String depth, @HeaderParam(HttpHeaders.CONTENT_LENGTH) final Long contentLength, @HeaderParam("Transfer-Encoding") final String transferEncoding) { // Check exist checkFileExists(); // Access Control - davRsCmp.getParent().checkAccessContext(davRsCmp.getAccessContext(), CellPrivilege.ROOT); + davRsCmp.getParent().checkAccessContext(CellPrivilege.ROOT); return davRsCmp.doPropfind(requestBodyXml, depth, contentLength, transferEncoding, CellPrivilege.ROOT); } @@ -154,12 +154,12 @@ public Response options() { // Check exist checkFileExists(); // Access Control - davRsCmp.getParent().checkAccessContext(davRsCmp.getAccessContext(), CellPrivilege.ROOT); + davRsCmp.getParent().checkAccessContext(CellPrivilege.ROOT); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE, - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND + io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND ).build(); } diff --git a/src/main/java/io/personium/core/rs/cell/CellSnapshotResource.java b/src/main/java/io/personium/core/rs/cell/CellSnapshotResource.java index bd5cec021..8b29faf41 100644 --- a/src/main/java/io/personium/core/rs/cell/CellSnapshotResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellSnapshotResource.java @@ -25,7 +25,7 @@ import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.annotations.PROPFIND; import io.personium.core.auth.CellPrivilege; import io.personium.core.model.CellRsCmp; @@ -75,11 +75,11 @@ public Object nextPath(@PathParam("nextPath") final String nextPath) { */ @PROPFIND public Response propfind(Reader requestBodyXml, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.DEPTH) String depth, + @HeaderParam(CommonUtils.HttpHeaders.DEPTH) String depth, @HeaderParam(HttpHeaders.CONTENT_LENGTH) Long contentLength, @HeaderParam("Transfer-Encoding") String transferEncoding) { // Access Control - cellSnapshotCellRsCmp.checkAccessContext(cellSnapshotCellRsCmp.getAccessContext(), CellPrivilege.ROOT); + cellSnapshotCellRsCmp.checkAccessContext(CellPrivilege.ROOT); return cellSnapshotCellRsCmp.doPropfind(requestBodyXml, depth, contentLength, transferEncoding, CellPrivilege.ROOT); } @@ -91,9 +91,9 @@ public Response propfind(Reader requestBodyXml, @OPTIONS public Response options() { // Access Control - cellSnapshotCellRsCmp.checkAccessContext(cellSnapshotCellRsCmp.getAccessContext(), CellPrivilege.ROOT); + cellSnapshotCellRsCmp.checkAccessContext(CellPrivilege.ROOT); return ResourceUtils.responseBuilderForOptions( - io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND + io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND ).build(); } diff --git a/src/main/java/io/personium/core/rs/cell/ErrorHtmlResource.java b/src/main/java/io/personium/core/rs/cell/ErrorHtmlResource.java index ed7cc7581..cfddbc077 100644 --- a/src/main/java/io/personium/core/rs/cell/ErrorHtmlResource.java +++ b/src/main/java/io/personium/core/rs/cell/ErrorHtmlResource.java @@ -31,7 +31,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreMessageUtils; import io.personium.core.auth.OAuth2Helper.Key; @@ -73,7 +73,7 @@ private String htmlForCode(String code) { msg = PersoniumCoreMessageUtils.getMessage("PS-ER-0002"); } - String html = PersoniumCoreUtils.readStringResource("html/error.html", CharEncoding.UTF_8); + String html = CommonUtils.readStringResource("html/error.html", CharEncoding.UTF_8); html = MessageFormat.format(html, title, msg); return html; } diff --git a/src/main/java/io/personium/core/rs/cell/EventResource.java b/src/main/java/io/personium/core/rs/cell/EventResource.java index a5077b27f..b873fd48e 100644 --- a/src/main/java/io/personium/core/rs/cell/EventResource.java +++ b/src/main/java/io/personium/core/rs/cell/EventResource.java @@ -68,7 +68,7 @@ public EventResource(final Cell cell, final AccessContext accessContext, final D @POST public final Response receiveEvent(final Reader reader) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), CellPrivilege.EVENT); + this.davRsCmp.checkAccessContext(CellPrivilege.EVENT); //Analyze the request body and obtain the Event object PersoniumEvent event = getRequestBody(reader); diff --git a/src/main/java/io/personium/core/rs/cell/IntrospectionEndPointResource.java b/src/main/java/io/personium/core/rs/cell/IntrospectionEndPointResource.java index 2c1620117..f5be1cd22 100644 --- a/src/main/java/io/personium/core/rs/cell/IntrospectionEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/IntrospectionEndPointResource.java @@ -34,13 +34,13 @@ import org.slf4j.LoggerFactory; import io.personium.common.auth.token.AbstractOAuth2Token; -import io.personium.common.auth.token.AccountAccessToken; -import io.personium.common.auth.token.CellLocalAccessToken; -import io.personium.common.auth.token.CellLocalRefreshToken; import io.personium.common.auth.token.IAccessToken; +import io.personium.common.auth.token.ResidentLocalAccessToken; +import io.personium.common.auth.token.ResidentRefreshToken; import io.personium.common.auth.token.TransCellAccessToken; -import io.personium.common.auth.token.TransCellRefreshToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.auth.token.VisitorLocalAccessToken; +import io.personium.common.auth.token.VisitorRefreshToken; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreAuthzException; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; @@ -105,7 +105,7 @@ public final Response introspect(@Context final UriInfo uriInfo, String schema; if (AccessContext.TYPE_INVALID.equals(accessContext.getType())) { - String[] idpw = PersoniumCoreUtils.parseBasicAuthzHeader(authzHeader); + String[] idpw = CommonUtils.parseBasicAuthzHeader(authzHeader); if (idpw != null) { String username = PersoniumUnitConfig.getIntrospectUsername(); String password = PersoniumUnitConfig.getIntrospectPassword(); @@ -146,8 +146,8 @@ public final Response introspect(@Context final UriInfo uriInfo, if (!tk.isExpired() && (schema == null || schema != null && schema.equals(tk.getSchema()))) { String issuer = tk.getIssuer(); int expirationTime = tk.getIssuedAt() + tk.expiresIn(); - if (tk instanceof AccountAccessToken - || tk instanceof CellLocalRefreshToken) { + if (tk instanceof ResidentLocalAccessToken + || tk instanceof ResidentRefreshToken) { if (issuer.equals(this.cell.getUrl())) { map.put(RESP_ACTIVE, true); map.put(RESP_CLIENT_ID, tk.getSchema()); @@ -158,8 +158,8 @@ public final Response introspect(@Context final UriInfo uriInfo, map.put(RESP_EXT_ROLES, tk.getRoles().stream().map(role -> role.createUrl()).collect(Collectors.toList())); } - } else if (tk instanceof CellLocalAccessToken - || tk instanceof TransCellRefreshToken + } else if (tk instanceof VisitorLocalAccessToken + || tk instanceof VisitorRefreshToken || tk instanceof TransCellAccessToken) { IAccessToken iat = (IAccessToken) tk; String audience = iat.getTarget(); @@ -192,7 +192,7 @@ public final Response introspect(@Context final UriInfo uriInfo, @OPTIONS public Response options() { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), CellPrivilege.AUTH_READ); + this.davRsCmp.checkAccessContext(CellPrivilege.AUTH_READ); return ResourceUtils.responseBuilderForOptions(HttpMethod.POST) .build(); } diff --git a/src/main/java/io/personium/core/rs/cell/LogResource.java b/src/main/java/io/personium/core/rs/cell/LogResource.java index 946be474d..e80d4a42f 100644 --- a/src/main/java/io/personium/core/rs/cell/LogResource.java +++ b/src/main/java/io/personium/core/rs/cell/LogResource.java @@ -57,7 +57,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.core.annotations.PROPFIND; @@ -129,11 +129,11 @@ public final Response archivePropfind(final Reader requestBodyXml, @Context UriInfo uriInfo, @HeaderParam(HttpHeaders.CONTENT_LENGTH) final Long contentLength, @HeaderParam("Transfer-Encoding") final String transferEncoding, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.DEPTH) final String depth + @HeaderParam(CommonUtils.HttpHeaders.DEPTH) final String depth ) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), CellPrivilege.LOG_READ); + this.davRsCmp.checkAccessContext(CellPrivilege.LOG_READ); //Valid values ​​of Depth header are 0, 1 //Since it does not support when infinity, return it with 403 @@ -266,7 +266,7 @@ public final Response getLogFile(@HeaderParam(HttpHeaders.IF_NONE_MATCH) final S @PathParam("filename") final String fileName) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), CellPrivilege.LOG_READ); + this.davRsCmp.checkAccessContext(CellPrivilege.LOG_READ); //Check the collection name of the event log if (!isValidLogCollection(logCollection)) { @@ -279,7 +279,7 @@ public final Response getLogFile(@HeaderParam(HttpHeaders.IF_NONE_MATCH) final S } String cellId = davRsCmp.getCell().getId(); - String owner = davRsCmp.getCell().getOwner(); + String owner = davRsCmp.getCell().getOwnerNormalized(); //Get the path of the log file StringBuilder logFileName = EventUtils.getEventLogDir(cellId, owner); @@ -368,7 +368,7 @@ public final Response deleteLogFile(@PathParam("logCollection") final String log @PathParam("filename") final String fileName) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), CellPrivilege.LOG); + this.davRsCmp.checkAccessContext(CellPrivilege.LOG); //Check the collection name of the event log if (CURRENT_COLLECTION.equals(logCollection)) { @@ -383,7 +383,7 @@ public final Response deleteLogFile(@PathParam("logCollection") final String log } String cellId = davRsCmp.getCell().getId(); - String owner = davRsCmp.getCell().getOwner(); + String owner = davRsCmp.getCell().getOwnerNormalized(); //Delete event log file StringBuilder logFilePath = EventUtils.getEventLogDir(cellId, owner); diff --git a/src/main/java/io/personium/core/rs/cell/MessageResource.java b/src/main/java/io/personium/core/rs/cell/MessageResource.java index 150314f40..74a25038c 100644 --- a/src/main/java/io/personium/core/rs/cell/MessageResource.java +++ b/src/main/java/io/personium/core/rs/cell/MessageResource.java @@ -29,7 +29,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.annotations.WriteAPI; import io.personium.core.auth.AccessContext; import io.personium.core.auth.CellPrivilege; @@ -82,11 +82,11 @@ public AccessContext getAccessContext() { @POST @Path("send") public Response messages( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_VERSION) final String version, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_VERSION) final String version, @Context final UriInfo uriInfo, final Reader reader) { //Access control - this.davRsCmp.checkAccessContext(this.accessContext, CellPrivilege.MESSAGE); + this.davRsCmp.checkAccessContext(CellPrivilege.MESSAGE); //Data registration PersoniumODataProducer producer = ModelFactory.ODataCtl.message(this.accessContext.getCell(), this.davRsCmp); @@ -131,7 +131,7 @@ public Response messagesPort( public Response messagesApprove(@PathParam("key") final String key, final Reader reader) { //Access control - this.davRsCmp.checkAccessContext(this.accessContext, CellPrivilege.MESSAGE); + this.davRsCmp.checkAccessContext(CellPrivilege.MESSAGE); //Approve received messages PersoniumODataProducer producer = ModelFactory.ODataCtl.message(this.accessContext.getCell(), this.davRsCmp); diff --git a/src/main/java/io/personium/core/rs/cell/PasswordResource.java b/src/main/java/io/personium/core/rs/cell/MyPasswordResource.java similarity index 80% rename from src/main/java/io/personium/core/rs/cell/PasswordResource.java rename to src/main/java/io/personium/core/rs/cell/MyPasswordResource.java index 4e65734af..9713a2def 100644 --- a/src/main/java/io/personium/core/rs/cell/PasswordResource.java +++ b/src/main/java/io/personium/core/rs/cell/MyPasswordResource.java @@ -19,8 +19,6 @@ import javax.ws.rs.PUT; import javax.ws.rs.core.Response; -import org.odata4j.core.ODataConstants; -import org.odata4j.core.ODataVersion; import org.odata4j.core.OEntityKey; import org.odata4j.edm.EdmEntitySet; import org.slf4j.Logger; @@ -30,7 +28,7 @@ import io.personium.core.annotations.WriteAPI; import io.personium.core.auth.AccessContext; import io.personium.core.model.Cell; -import io.personium.core.model.DavRsCmp; +import io.personium.core.model.CellRsCmp; import io.personium.core.model.ModelFactory; import io.personium.core.model.ctl.Account; import io.personium.core.odata.PersoniumODataProducer; @@ -38,33 +36,33 @@ /** * JAX-RS resource that handles password change processing in resource class. */ -public class PasswordResource { +public class MyPasswordResource { String pCredHeader; AccessContext accessContext; Cell cell; - static Logger log = LoggerFactory.getLogger(PasswordResource.class); + static Logger log = LoggerFactory.getLogger(MyPasswordResource.class); private String key; private String keyString = null; private OEntityKey oEntityKey; - private DavRsCmp davRsCmp; + private CellRsCmp cellRsCmp; /** * constructor. * @param accessContext accessContext * @param pCredHeader pCredHeader * @param cell cell - * @param davRsCmp DavRsCmp + * @param cellRsCmp DavRsCmp */ - public PasswordResource(final AccessContext accessContext, + public MyPasswordResource(final AccessContext accessContext, final String pCredHeader, - Cell cell, DavRsCmp davRsCmp) { + Cell cell, CellRsCmp cellRsCmp) { this.accessContext = accessContext; this.pCredHeader = pCredHeader; this.cell = cell; - this.davRsCmp = davRsCmp; + this.cellRsCmp = cellRsCmp; } /** @@ -73,9 +71,9 @@ public PasswordResource(final AccessContext accessContext, */ @WriteAPI @PUT - public Response mypass() { + public Response put() { //Access control - this.accessContext.checkMyLocalOrPasswordChangeToken(cell, this.davRsCmp.getAcceptableAuthScheme()); + this.accessContext.checkResidentLocalOrPasswordChangeToken(this.cellRsCmp.getAcceptableAuthScheme()); //Get the Account name to change password from cell local token this.key = this.accessContext.getSubject(); String[] keyName; @@ -97,7 +95,6 @@ public Response mypass() { //Response return return Response.noContent() - .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataVersion.V2.asString) .build(); } } diff --git a/src/main/java/io/personium/core/rs/cell/RoleResource.java b/src/main/java/io/personium/core/rs/cell/RoleResource.java index 00c6f5ec0..caec7ccbd 100644 --- a/src/main/java/io/personium/core/rs/cell/RoleResource.java +++ b/src/main/java/io/personium/core/rs/cell/RoleResource.java @@ -68,7 +68,7 @@ public RoleResource(final Cell cell, final DavRsCmp davRsCmp) { public final Response list( @HeaderParam(HttpHeaders.AUTHORIZATION) final String authzHeader) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), CellPrivilege.AUTH_READ); + this.davRsCmp.checkAccessContext(CellPrivilege.AUTH_READ); EntitiesResponse er = op.getEntities(Box.EDM_TYPE_NAME, null); List loe = er.getEntities(); List sl = new ArrayList(); @@ -97,7 +97,7 @@ public final Response cellRole( @PathParam("box") String boxName, @HeaderParam(HttpHeaders.AUTHORIZATION) final String authzHeader) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), CellPrivilege.AUTH_READ); + this.davRsCmp.checkAccessContext(CellPrivilege.AUTH_READ); //If the Box path is Cell Level, search the Cell level role and return it as a list. if (BOX_PATH_CELL_LEVEL.equals(boxName)) { //Generation of TODO Body @@ -131,7 +131,7 @@ public final Response boxRole( @PathParam("role") String role, @HeaderParam(HttpHeaders.AUTHORIZATION) final String authzHeader) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), CellPrivilege.AUTH_READ); + this.davRsCmp.checkAccessContext(CellPrivilege.AUTH_READ); //If the Box pass is Cell Level, it is handled as Cell Level Roll. if (BOX_PATH_CELL_LEVEL.equals(boxName)) { //Generation of TODO Body diff --git a/src/main/java/io/personium/core/rs/cell/RuleResource.java b/src/main/java/io/personium/core/rs/cell/RuleResource.java index caf16cb55..9f8ec4949 100644 --- a/src/main/java/io/personium/core/rs/cell/RuleResource.java +++ b/src/main/java/io/personium/core/rs/cell/RuleResource.java @@ -19,8 +19,8 @@ import java.util.Map; import javax.ws.rs.GET; -import javax.ws.rs.OPTIONS; import javax.ws.rs.HttpMethod; +import javax.ws.rs.OPTIONS; import javax.ws.rs.core.Response; import io.personium.core.auth.AccessContext; @@ -58,7 +58,7 @@ public RuleResource(final Cell cell, final AccessContext accessContext, final Ce @GET public final Response list() { // access control - this.cellRsCmp.checkAccessContext(this.accessContext, CellPrivilege.RULE_READ); + this.cellRsCmp.checkAccessContext(CellPrivilege.RULE_READ); RuleManager rman = RuleManager.getInstance(); Map map = rman.getRules(this.cell); @@ -73,7 +73,7 @@ public final Response list() { @OPTIONS public Response options() { // Access Control - this.cellRsCmp.checkAccessContext(this.accessContext, CellPrivilege.RULE_READ); + this.cellRsCmp.checkAccessContext(CellPrivilege.RULE_READ); return ResourceUtils.responseBuilderForOptions(HttpMethod.GET) .build(); } diff --git a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java index bc2ac9667..029c8b45f 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -1,6 +1,6 @@ /** - * personium.io - * Copyright 2014 FUJITSU LIMITED + * Personium + * Copyright 2019 FUJITSU LIMITED * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,10 +18,14 @@ import java.net.MalformedURLException; import java.net.URL; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Set; import java.util.UUID; import javax.ws.rs.HeaderParam; @@ -48,20 +52,20 @@ import io.personium.common.auth.token.AbstractOAuth2Token.TokenDsigException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenRootCrtException; -import io.personium.common.auth.token.AccountAccessToken; -import io.personium.common.auth.token.CellLocalAccessToken; -import io.personium.common.auth.token.CellLocalRefreshToken; +import io.personium.common.auth.token.GrantCode; import io.personium.common.auth.token.IAccessToken; import io.personium.common.auth.token.IExtRoleContainingToken; import io.personium.common.auth.token.IRefreshToken; import io.personium.common.auth.token.IdToken; -import io.personium.common.auth.token.LocalToken; import io.personium.common.auth.token.PasswordChangeAccessToken; +import io.personium.common.auth.token.ResidentLocalAccessToken; +import io.personium.common.auth.token.ResidentRefreshToken; import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; -import io.personium.common.auth.token.TransCellRefreshToken; import io.personium.common.auth.token.UnitLocalUnitUserToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.auth.token.VisitorLocalAccessToken; +import io.personium.common.auth.token.VisitorRefreshToken; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreAuthnException; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; @@ -71,11 +75,11 @@ import io.personium.core.auth.AuthUtils; import io.personium.core.auth.OAuth2Helper; import io.personium.core.auth.OAuth2Helper.Key; +import io.personium.core.auth.ScopeArbitrator; import io.personium.core.model.Box; import io.personium.core.model.Cell; import io.personium.core.model.CellCmp; import io.personium.core.model.CellRsCmp; -import io.personium.core.model.DavRsCmp; import io.personium.core.model.ctl.Account; import io.personium.core.model.impl.fs.CellKeysFile; import io.personium.core.odata.OEntityWrapper; @@ -90,17 +94,13 @@ import io.personium.plugin.base.auth.AuthenticatedIdentity; /** - * JAX-RS Resource class for authentication. + * JAX-RS Resource class for Token Endpoint. */ public class TokenEndPointResource { - // core issue #223 - // "issuer" in the token may be interpreted by other units. - // For that reason, "path based cell url" is set for "issuer" regardless of unit property setting. - static Logger log = LoggerFactory.getLogger(TokenEndPointResource.class); private final Cell cell; - private final DavRsCmp davRsCmp; + private final CellRsCmp davRsCmp; private boolean issueCookie = false; private UriInfo requestURIInfo; //The UUID of the Account used for password authentication. It is used to update the last login time after password authentication. @@ -113,16 +113,17 @@ public class TokenEndPointResource { * @param cell Cell * @param davRsCmp davRsCmp */ - public TokenEndPointResource(final Cell cell, final DavRsCmp davRsCmp) { + public TokenEndPointResource(final Cell cell, final CellRsCmp davRsCmp) { this.cell = cell; this.davRsCmp = davRsCmp; } /** - * OAuth2.0 Token Endpoint.

Issue some kinds of tokens.

+ * OAuth2.0 Token Endpoint. + * Issues differnt kinds of tokens depending on the parameters. *
    - *
  • If URL is written in p_target, issue transCellToken as CELL of TARGET as its CELL. - *
  • Issue CellLocal if scope does not exist. + *
  • If p_target parameter exists, it issues Trans-Cell access token targeting at the specified URL. + *
  • If p_target parameter is not specified, it issues Cell-local access token. *
* @param uriInfo URI information * @param authzHeader Authorization Header @@ -147,16 +148,27 @@ public final Response token(@Context final UriInfo uriInfo, String code = formParams.getFirst(Key.CODE); String clientId = formParams.getFirst(Key.CLIENT_ID); String clientSecret = formParams.getFirst(Key.CLIENT_SECRET); + String clientAssertion = formParams.getFirst(Key.CLIENT_ASSERTION); + String clientAssertionType = formParams.getFirst(Key.CLIENT_ASSERTION_TYPE); String expiresInStr = formParams.getFirst(Key.EXPIRES_IN); String rTokenExpiresInStr = formParams.getFirst(Key.REFRESH_TOKEN_EXPIRES_IN); - String pCookie = formParams.getFirst("p_cookie"); + String pCookie = formParams.getFirst(Key.P_COOKIE); + String scopeStr = formParams.getFirst(Key.SCOPE); + + String[] scope = AbstractOAuth2Token.Scope.parse(scopeStr); + + // relsolve personium-localunit scheme url. + String target = UriUtils.convertSchemeFromLocalUnitToHttp(pTarget); - // Accept unit local scheme url. - String target = UriUtils.convertSchemeFromLocalUnitToHttp( - cell.getUnitUrl(), pTarget); - //If p_target is not a URL, it creates a vulnerability of header injection. (Such as a line feed code is included) - target = this.checkPTarget(target); + //Check the given target to prevent security attacks such as Header Injection. + //eg. If p_target is not a URL and include line feed code, it creates a vulnerability of header injection. + if (target != null) { + this.checkURL(target); + target = this.addTrainlingSlash(target); + // TODO should do more normalization. + } + // Do not issue cookie if p_target exists, regardless of the p_cookie parameter. if (null != pTarget) { issueCookie = false; } else { @@ -167,10 +179,12 @@ public final Response token(@Context final UriInfo uriInfo, this.ipaddress = xForwardedFor; String schema = null; - //First, check if you want to authenticate Client - //If neither Scope nor authzHeader nor clientId exists, it is assumed that Client authentication is not performed. - if (clientId != null || authzHeader != null) { - schema = clientAuth(clientId, clientSecret, authzHeader, cell.getUrl()); + // Authenticate client first if necessary. + // If neither authzHeader, clientAssertion nor clientId exists, + // client authentication is not performed. + if (clientId != null || authzHeader != null || clientAssertion != null || clientAssertionType != null) { + schema = clientAuth(clientId, clientSecret, clientAssertionType, clientAssertion, + authzHeader, cell.getUrl()); } // Check value of expires_in @@ -205,7 +219,7 @@ public final Response token(@Context final UriInfo uriInfo, if (OAuth2Helper.GrantType.PASSWORD.equals(grantType)) { //Regular password authentication Response response = this.handlePassword(target, pOwner, - schema, username, password, expiresIn, rTokenExpiresIn); + schema, username, password, expiresIn, rTokenExpiresIn, scope); return response; } else if (OAuth2Helper.GrantType.SAML2_BEARER.equals(grantType)) { return this.receiveSaml2(target, pOwner, schema, assertion, expiresIn, rTokenExpiresIn); @@ -216,7 +230,7 @@ public final Response token(@Context final UriInfo uriInfo, } else { // Call Auth Plugins return this.callAuthPlugins(grantType, formParams, target, pOwner, - schema, expiresIn, rTokenExpiresIn); + schema, expiresIn, rTokenExpiresIn, scope); } } @@ -240,7 +254,7 @@ private String getIssuerUrl() { * @return Response */ private Response callAuthPlugins(String grantType, MultivaluedMap params, - String target, String owner, String schema, long expiresIn, long rTokenExpiresIn) { + String target, String owner, String schema, long expiresIn, long rTokenExpiresIn, String[] requestScopes) { // Plugin manager. PluginManager pm = PersoniumCoreApplication.getPluginManager(); // Search target plugin. @@ -295,13 +309,15 @@ private Response callAuthPlugins(String grantType, MultivaluedMap roleList = cell.getRoleListForAccount(token.getSubject()); aToken = new TransCellAccessToken(issuedAt, expiresIn, getIssuerUrl(), - getIssuerUrl() + "#" + token.getSubject(), target, roleList, schema); + getIssuerUrl() + "#" + token.getSubject(), target, roleList, schema, token.getScope()); } // If scope is openid it returns id_token. IdToken idToken = null; - if (OAuth2Helper.Scope.OPENID.equals(token.getScope())) { + Set reqScopes = new HashSet<>(Arrays.asList(token.getScope())); + if (reqScopes.contains(OAuth2Helper.Scope.OPENID)) { CellCmp cellCmp = (CellCmp) davRsCmp.getDavCmp(); CellKeysFile cellKeysFile = cellCmp.getCellKeys().getCellKeysFile(); String subject = token.getSubject(); long issuedAtSec = issuedAt / AbstractOAuth2Token.MILLISECS_IN_A_SEC; - long expiryTime = issuedAtSec + AbstractOAuth2Token.SECS_IN_A_HOUR; + long expiryTime = issuedAtSec + AbstractOAuth2Token.SECS_IN_AN_HOUR; idToken = new IdToken( cellKeysFile.getKeyId(), AlgorithmUtils.RS_SHA_256_ALGO, getIssuerUrl(), subject, schema, expiryTime, issuedAtSec, cellKeysFile.getPrivateKey()); @@ -556,14 +608,17 @@ private Response receiveSaml2(final String target, final String owner, //Authentication is successful ------------------------------- - //Create a refresh token based on the authentication information + // Scope arbitration + String[] scopes = this.cell.getScopeArbitrator(schema, OAuth2Helper.GrantType.SAML2_BEARER).request(tcToken.getScope()).getResults(); + + // Create a refresh token based on the authentication information long issuedAt = new Date().getTime(); - TransCellRefreshToken rToken = new TransCellRefreshToken( + VisitorRefreshToken rToken = new VisitorRefreshToken( tcToken.getId(), //Save ID of received SAML issuedAt, rTokenExpiresIn, getIssuerUrl(), tcToken.getSubject(), tcToken.getIssuer(), //Save receipt of SAML's tcToken.getRoles(), //Save receipt of SAML's - schema); + schema, scopes); //Ask CELL to decide the role of you from the role of TC issuer. List rolesHere = cell.getRoleListHere(tcToken); @@ -575,12 +630,16 @@ issuedAt, rTokenExpiresIn, getIssuerUrl(), tcToken.getSubject(), //Authentication token issue processing //The target can be freely decided. IAccessToken aToken = null; + + // TODO + + if (target == null) { - aToken = new CellLocalAccessToken(issuedAt, expiresIn, getIssuerUrl(), - tcToken.getSubject(), rolesHere, schemaVerified); + aToken = new VisitorLocalAccessToken(issuedAt, expiresIn, getIssuerUrl(), + tcToken.getSubject(), rolesHere, schemaVerified, scopes); } else { aToken = new TransCellAccessToken(issuedAt, expiresIn, getIssuerUrl(), - tcToken.getSubject(), target, rolesHere, schemaVerified); + tcToken.getSubject(), target, rolesHere, schemaVerified, scopes); } return this.responseAuthSuccess(aToken, rToken, issuedAt); } @@ -627,12 +686,21 @@ private Response receiveRefresh(final String target, String owner, String schema if (token.isRefreshExpired()) { throw PersoniumCoreAuthnException.TOKEN_EXPIRED.realm(this.cell.getUrl()); } + String tSchema = token.getSchema(); + + + if (!(Objects.equals(schema, tSchema) || schema == null && StringUtils.isEmpty(tSchema))) { + if (schema == null) { + throw PersoniumCoreAuthnException.CLIENT_AUTH_REQUIRED; + } + throw PersoniumCoreAuthnException.CLIENT_MISMATCH_FOR_REFRESH.params(schema); + } long issuedAt = new Date().getTime(); if (Key.TRUE_STR.equals(owner)) { //You can be promoted only for your own cell refresh. - if (token.getClass() != CellLocalRefreshToken.class) { + if (token.getClass() != ResidentRefreshToken.class) { throw PersoniumCoreAuthnException.TC_ACCESS_REPRESENTING_OWNER.realm(this.cell.getUrl()); } //Check unit escalation privilege setting @@ -640,39 +708,41 @@ private Response receiveRefresh(final String target, String owner, String schema throw PersoniumCoreAuthnException.NOT_ALLOWED_REPRESENT_OWNER.realm(this.cell.getUrl()); } //Do not promote cells for which the owner of the cell is not set. - if (cell.getOwner() == null) { + if (cell.getOwnerNormalized() == null) { throw PersoniumCoreAuthnException.NO_CELL_OWNER.realm(this.cell.getUrl()); } //uluut issuance processing UnitLocalUnitUserToken uluut = new UnitLocalUnitUserToken(issuedAt, expiresIn, - cell.getOwner(), cell.getUnitUrl()); + cell.getOwnerNormalized(), cell.getUnitUrl()); return this.responseAuthSuccess(uluut, null, issuedAt); + } + + + + //Regenerate AccessToken and RefreshToken from received Refresh Token + IRefreshToken rToken = (IRefreshToken) token; + rToken = rToken.refreshRefreshToken(issuedAt, rTokenExpiresIn); + + IAccessToken aToken = null; + if (rToken instanceof ResidentRefreshToken) { + String subject = rToken.getSubject(); + List roleList = cell.getRoleListForAccount(subject); + aToken = rToken.refreshAccessToken(issuedAt, expiresIn, target, getIssuerUrl(), roleList); } else { - //Regenerate AccessToken and RefreshToken from received Refresh Token - IRefreshToken rToken = (IRefreshToken) token; - rToken = rToken.refreshRefreshToken(issuedAt, rTokenExpiresIn); - - IAccessToken aToken = null; - if (rToken instanceof CellLocalRefreshToken) { - String subject = rToken.getSubject(); - List roleList = cell.getRoleListForAccount(subject); - aToken = rToken.refreshAccessToken(issuedAt, expiresIn, target, getIssuerUrl(), roleList, schema); - } else { - //Ask CELL to determine the role of you from the role of the token issuer. - List rolesHere = cell.getRoleListHere((IExtRoleContainingToken) rToken); - aToken = rToken.refreshAccessToken(issuedAt, expiresIn, target, - getIssuerUrl(), rolesHere, schema); - } + //Ask CELL to determine the role of you from the role of the token issuer. + List rolesHere = cell.getRoleListHere((IExtRoleContainingToken) rToken); + aToken = rToken.refreshAccessToken(issuedAt, expiresIn, target, + getIssuerUrl(), rolesHere); + } - if (aToken instanceof TransCellAccessToken) { - log.debug("reissuing TransCell Token"); - // aToken.addRole("admin"); - // return this.responseAuthSuccess(tcToken); - } - return this.responseAuthSuccess(aToken, rToken, issuedAt); + if (aToken instanceof TransCellAccessToken) { + log.debug("reissuing TransCell Token"); + // aToken.addRole("admin"); + // return this.responseAuthSuccess(tcToken); } + return this.responseAuthSuccess(aToken, rToken, issuedAt); } private Response responseAuthSuccess(final IAccessToken accessToken, final IRefreshToken refreshToken, @@ -686,6 +756,9 @@ private Response responseAuthSuccess(IAccessToken accessToken, IRefreshToken ref JSONObject resp = new JSONObject(); resp.put(OAuth2Helper.Key.ACCESS_TOKEN, accessToken.toTokenString()); resp.put(OAuth2Helper.Key.EXPIRES_IN, accessToken.expiresIn()); + if (accessToken.getScope() != null && accessToken.getScope().length > 0) { + resp.put(OAuth2Helper.Key.SCOPE, AbstractOAuth2Token.Scope.toConcatValue(accessToken.getScope())); + } if (refreshToken != null) { resp.put(OAuth2Helper.Key.REFRESH_TOKEN, refreshToken.toTokenString()); resp.put(OAuth2Helper.Key.REFRESH_TOKEN_EXPIRES_IN, refreshToken.refreshExpiresIn()); @@ -701,14 +774,11 @@ private Response responseAuthSuccess(IAccessToken accessToken, IRefreshToken ref } if (issueCookie) { - String tokenString = accessToken.toTokenString(); //Set random UUID as p_cookie_peer String pCookiePeer = UUID.randomUUID().toString(); - String cookieValue = pCookiePeer + "\t" + tokenString; //The p_cookie value to return to the header is encrypted - String encodedCookieValue = LocalToken.encode(cookieValue, - UnitLocalUnitUserToken.getIvBytes(AccessContext - .getCookieCryptKey(requestURIInfo.getBaseUri().getHost()))); + String encodedCookieValue = accessToken.getCookieString(pCookiePeer, + AccessContext.getCookieCryptKey(requestURIInfo.getBaseUri().getHost())); //Specify cookie version (0) int version = 0; String path = getCookiePath(); @@ -755,7 +825,7 @@ private String getCookiePath() { private Response handlePassword(final String target, final String owner, final String schema, final String username, - final String password, long expiresIn, long rTokenExpiresIn) { + final String password, long expiresIn, long rTokenExpiresIn, String[] scope) { //Password check processing if (username == null) { @@ -793,7 +863,7 @@ private Response handlePassword(final String target, final String owner, } // Check if the target account records authentication history. - isRecordingAuthHistory = AuthResourceUtils.isRecordingAuthHistory((CellRsCmp) davRsCmp, accountId, username); + isRecordingAuthHistory = ((CellRsCmp) davRsCmp).isRecordingAuthHistory(accountId, username); //Check valid authentication interval if (isLockedInterval) { @@ -849,7 +919,7 @@ private Response handlePassword(final String target, final String owner, if (!accountActive) { if (passwordChangeRequired) { // Issue password change. - issuePasswordChange(schema, username, rTokenExpiresIn); + issuePasswordChange(schema, username, rTokenExpiresIn, scope); } else { AuthResourceUtils.registIntervalLock(accountId); AuthResourceUtils.countupFailedCount(accountId); @@ -861,8 +931,10 @@ private Response handlePassword(final String target, final String owner, throw PersoniumCoreAuthnException.AUTHN_FAILED.realm(this.cell.getUrl()); } } + ScopeArbitrator sa = this.cell.getScopeArbitrator(schema, OAuth2Helper.GrantType.PASSWORD); + String[] scopes = sa.request(scope).getResults(); - return issueToken(target, owner, schema, username, expiresIn, rTokenExpiresIn); + return issueToken(target, owner, schema, username, expiresIn, rTokenExpiresIn, scopes); } /** @@ -872,11 +944,11 @@ private Response handlePassword(final String target, final String owner, * @param username user name * @param expiresIn expires in */ - private void issuePasswordChange(final String schema, final String username, long expiresIn) { + private void issuePasswordChange(final String schema, final String username, long expiresIn, String[] scope) { // create account password change access token. long issuedAt = new Date().getTime(); PasswordChangeAccessToken aToken = new PasswordChangeAccessToken( - issuedAt, expiresIn, getIssuerUrl(), username, schema); + issuedAt, expiresIn, getIssuerUrl(), username, schema, scope); // get auth history. (non update auth history) AuthHistoryLastFile last = AuthResourceUtils.getAuthHistoryLast( @@ -892,7 +964,7 @@ private void issuePasswordChange(final String schema, final String username, lon } private Response issueToken(final String target, final String owner, - final String schema, final String username, long expiresIn, long rTokenExpiresIn) { + final String schema, final String username, long expiresIn, long rTokenExpiresIn, String[] scopes) { long issuedAt = new Date().getTime(); if (Key.TRUE_STR.equals(owner)) { @@ -902,23 +974,23 @@ private Response issueToken(final String target, final String owner, .realm(this.cell.getUrl()); } //Do not promote cells for which the owner of the cell is not set. - if (cell.getOwner() == null) { + if (cell.getOwnerNormalized() == null) { throw PersoniumCoreAuthnException.NO_CELL_OWNER.realm(this.cell.getUrl()); } //uluut issuance processing UnitLocalUnitUserToken uluut = new UnitLocalUnitUserToken(issuedAt, expiresIn, - cell.getOwner(), cell.getUnitUrl()); + cell.getOwnerNormalized(), cell.getUnitUrl()); return this.responseAuthSuccess(uluut, null, issuedAt); } - CellLocalRefreshToken rToken = new CellLocalRefreshToken(issuedAt, rTokenExpiresIn, - getIssuerUrl(), username, schema); + ResidentRefreshToken rToken = new ResidentRefreshToken(issuedAt, rTokenExpiresIn, + getIssuerUrl(), username, schema, scopes); //Create a response. if (target == null) { - AccountAccessToken localToken = new AccountAccessToken(issuedAt, expiresIn, - getIssuerUrl(), username, schema); + ResidentLocalAccessToken localToken = new ResidentLocalAccessToken(issuedAt, expiresIn, + getIssuerUrl(), username, schema, scopes); return this.responseAuthSuccess(localToken, rToken, issuedAt); } else { //Check that TODO SCHEMA is URL @@ -927,7 +999,7 @@ private Response issueToken(final String target, final String owner, List roleList = cell.getRoleListForAccount(username); TransCellAccessToken tcToken = new TransCellAccessToken(issuedAt, expiresIn, - getIssuerUrl(), getIssuerUrl() + "#" + username, target, roleList, schema); + getIssuerUrl(), getIssuerUrl() + "#" + username, target, roleList, schema, scopes); return this.responseAuthSuccess(tcToken, rToken, issuedAt); } } diff --git a/src/main/java/io/personium/core/rs/odata/ODataBatchResource.java b/src/main/java/io/personium/core/rs/odata/ODataBatchResource.java index d433a2716..bfd42f74e 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataBatchResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataBatchResource.java @@ -1374,13 +1374,14 @@ private void checkAccessContext(AccessContext ac) { * @param ac AccessContext * @param privilege Required privilege */ - private void checkAccessContextForMimePart(AccessContext ac, Privilege privilege) { + private void checkAccessContextForMimePart(Privilege privilege) { + AccessContext ac = this.odataResource.getAccessContext(); // Check UnitUser token. if (ac.isUnitUserToken(privilege)) { return; } - if (!this.odataResource.hasPrivilege(ac, privilege)) { + if (!this.odataResource.hasPrivilege(privilege)) { //Authentication processing has already been executed for the $ batch request, so we only decide authorization here throw PersoniumCoreException.Auth.NECESSARY_PRIVILEGE_LACKING; } @@ -1402,7 +1403,7 @@ private void checkWriteAccessContext(BatchBodyPart bodyPart) { batchAccess = new BatchAccess(); writeAccess.put(priv, batchAccess); try { - this.checkAccessContextForMimePart(this.odataResource.getAccessContext(), priv); + this.checkAccessContextForMimePart(priv); } catch (PersoniumCoreException ex) { batchAccess.setAccessContext(ex); } @@ -1426,7 +1427,7 @@ private void checkReadAccessContext(BatchBodyPart bodyPart) { batchAccess = new BatchAccess(); readAccess.put(priv, batchAccess); try { - this.checkAccessContextForMimePart(this.odataResource.getAccessContext(), priv); + this.checkAccessContextForMimePart(priv); } catch (PersoniumCoreException ex) { batchAccess.setAccessContext(ex); } diff --git a/src/main/java/io/personium/core/rs/odata/ODataEntitiesResource.java b/src/main/java/io/personium/core/rs/odata/ODataEntitiesResource.java index 63aed286f..051ca95b6 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataEntitiesResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataEntitiesResource.java @@ -55,7 +55,6 @@ import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.core.annotations.WriteAPI; -import io.personium.core.auth.AccessContext; import io.personium.core.event.PersoniumEventType; import io.personium.core.model.ctl.Common; import io.personium.core.model.ctl.ReceivedMessage; @@ -71,7 +70,6 @@ public final class ODataEntitiesResource extends AbstractODataResource { private static final int Q_MAX_LENGTH = Common.MAX_Q_VALUE_LENGTH; ODataResource odataResource; - AccessContext accessContext; /** * constructor. @@ -80,7 +78,6 @@ public final class ODataEntitiesResource extends AbstractODataResource { */ public ODataEntitiesResource(final ODataResource odataResource, final String entitySetName) { this.odataResource = odataResource; - this.accessContext = this.odataResource.getAccessContext(); setOdataProducer(this.odataResource.getODataProducer()); setEntitySetName(entitySetName); } @@ -104,7 +101,7 @@ public Response listEntities( @QueryParam("q") final String q) { //Access control - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryReadPrivilege(getEntitySetName())); //Ask Producer to get the request @@ -191,8 +188,7 @@ public Response post( checkNotAllowedMethod(uriInfo); //Access control - this.odataResource.checkAccessContext(this.accessContext, - this.odataResource.getNecessaryWritePrivilege(getEntitySetName())); + this.odataResource.checkAccessContext(this.odataResource.getNecessaryWritePrivilege(getEntitySetName())); UriInfo resUriInfo = UriUtils.createUriInfo(uriInfo, 1); @@ -281,8 +277,7 @@ static QueryInfo queryInfo(UriInfo uriInfo, String fullTextSearchKeyword) { @OPTIONS public Response options() { //Access control - this.odataResource.checkAccessContext(this.accessContext, - this.odataResource.getNecessaryReadPrivilege(getEntitySetName())); + this.odataResource.checkAccessContext(this.odataResource.getNecessaryReadPrivilege(getEntitySetName())); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, HttpMethod.POST diff --git a/src/main/java/io/personium/core/rs/odata/ODataEntityResource.java b/src/main/java/io/personium/core/rs/odata/ODataEntityResource.java index cb908dc72..9557719e4 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataEntityResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataEntityResource.java @@ -50,7 +50,7 @@ import org.odata4j.producer.EntityResponse; import org.odata4j.producer.resources.OptionsQueryParser; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.core.annotations.MERGE; @@ -74,13 +74,12 @@ public class ODataEntityResource extends AbstractODataResource { private final String keyString; private final ODataResource odataResource; - private final AccessContext accessContext; /** * @return AccessContext */ public AccessContext getAccessContext() { - return accessContext; + return this.odataResource.getAccessContext(); } /** @@ -112,7 +111,6 @@ public OEntityId getOEntityId() { */ public ODataEntityResource() { this.odataResource = null; - this.accessContext = null; this.keyString = null; this.oEntityKey = null; } @@ -125,7 +123,6 @@ public ODataEntityResource() { */ public ODataEntityResource(final ODataResource odataResource, final String entitySetName, final String key) { this.odataResource = odataResource; - this.accessContext = this.odataResource.accessContext; setOdataProducer(this.odataResource.getODataProducer()); setEntitySetName(entitySetName); @@ -162,7 +159,6 @@ public ODataEntityResource(final ODataResource odataResource, final String entit protected ODataEntityResource(final ODataResource odataResource, final String entitySetName, final String keyString, final OEntityKey oEntityKey) { this.odataResource = odataResource; - this.accessContext = this.odataResource.accessContext; setOdataProducer(this.odataResource.getODataProducer()); setEntitySetName(entitySetName); this.keyString = keyString; @@ -188,8 +184,7 @@ public Response get( @QueryParam("$expand") String expand, @QueryParam("$select") String select) { //Access control - this.odataResource.checkAccessContext(this.accessContext, - this.odataResource.getNecessaryReadPrivilege(getEntitySetName())); + this.odataResource.checkAccessContext(this.odataResource.getNecessaryReadPrivilege(getEntitySetName())); UriInfo resUriInfo = UriUtils.createUriInfo(uriInfo, 1); @@ -217,7 +212,7 @@ public Response get( OEntityWrapper oew = (OEntityWrapper) entity; //Determining accessibility for each entity - this.odataResource.checkAccessContextPerEntity(this.accessContext, oew); + this.odataResource.checkAccessContextPerEntity(this.getAccessContext(), oew); etag = oew.getEtag(); //Basically enter this IF statement. @@ -315,8 +310,7 @@ public Response put(Reader reader, checkNotAllowedMethod(); //Access control - this.odataResource.checkAccessContext(this.accessContext, - this.odataResource.getNecessaryWritePrivilege(getEntitySetName())); + this.odataResource.checkAccessContext(this.odataResource.getNecessaryWritePrivilege(getEntitySetName())); String etag; @@ -395,8 +389,7 @@ public Response delete( @HeaderParam(HttpHeaders.ACCEPT) final String accept, @HeaderParam(HttpHeaders.IF_MATCH) final String ifMatch) { //Access control - this.odataResource.checkAccessContext(this.accessContext, - this.odataResource.getNecessaryWritePrivilege(getEntitySetName())); + this.odataResource.checkAccessContext(this.odataResource.getNecessaryWritePrivilege(getEntitySetName())); deleteEntity(ifMatch); Response res = Response.noContent() @@ -495,13 +488,12 @@ public ODataPropertyResource getNavProperty(@PathParam("navProp") final String n @OPTIONS public Response options() { //Access control - this.odataResource.checkAccessContext(this.accessContext, - this.odataResource.getNecessaryReadPrivilege(getEntitySetName())); + this.odataResource.checkAccessContext(this.odataResource.getNecessaryReadPrivilege(getEntitySetName())); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, HttpMethod.PUT, - PersoniumCoreUtils.HttpMethod.MERGE, + CommonUtils.HttpMethod.MERGE, HttpMethod.DELETE ).build(); } diff --git a/src/main/java/io/personium/core/rs/odata/ODataLinksResource.java b/src/main/java/io/personium/core/rs/odata/ODataLinksResource.java index 73f2e7a28..5a58d5e32 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataLinksResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataLinksResource.java @@ -59,7 +59,6 @@ import io.personium.core.PersoniumCoreException; import io.personium.core.annotations.WriteAPI; -import io.personium.core.auth.AccessContext; import io.personium.core.event.PersoniumEventType; import io.personium.core.model.ctl.Account; import io.personium.core.model.ctl.Common; @@ -78,7 +77,6 @@ public final class ODataLinksResource { private final OEntityKey targetEntityKey; private final ODataResource odataResource; private final ODataProducer odataProducer; - private final AccessContext accessContext; /** * log. @@ -98,7 +96,6 @@ public ODataLinksResource( final String targetNavProp, final OEntityKey targetEntityKey) { this.odataResource = odataResource; - this.accessContext = this.odataResource.getAccessContext(); this.odataProducer = this.odataResource.getODataProducer(); this.sourceEntity = sourceEntity; this.targetNavProp = targetNavProp; @@ -406,8 +403,7 @@ public Response getLinks( public Response options() { //Access control - this.odataResource.checkAccessContext(this.accessContext, - this.odataResource.getNecessaryOptionsPrivilege()); + this.odataResource.checkAccessContext(this.odataResource.getNecessaryOptionsPrivilege()); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, @@ -456,12 +452,12 @@ private void checkWriteAccessContext() { String entitySetNameTo = targetNavProp; if (entitySetNameFrom.equals(ReceivedMessage.EDM_TYPE_NAME) || entitySetNameTo.equals(Account.EDM_NPNAME_FOR_RECEIVED_MESSAGE)) { - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryWritePrivilege(ReceivedMessage.EDM_TYPE_NAME)); } else { - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryWritePrivilege(entitySetNameFrom)); - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryWritePrivilege(entitySetNameTo.substring(1))); } } @@ -473,12 +469,12 @@ private void checkReadAccessContext() { String entitySetNameTo = targetNavProp; if (entitySetNameFrom.equals(ReceivedMessage.EDM_TYPE_NAME) || entitySetNameTo.equals(Account.EDM_NPNAME_FOR_RECEIVED_MESSAGE)) { - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryReadPrivilege(ReceivedMessage.EDM_TYPE_NAME)); } else { - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryReadPrivilege(entitySetNameFrom)); - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryReadPrivilege(entitySetNameTo.substring(1))); } } diff --git a/src/main/java/io/personium/core/rs/odata/ODataMergeResource.java b/src/main/java/io/personium/core/rs/odata/ODataMergeResource.java index 8c745e4ff..62168ace6 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataMergeResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataMergeResource.java @@ -93,7 +93,7 @@ public Response merge(Reader reader, checkNotAllowedMethod(); //Access control - getOdataResource().checkAccessContext(getAccessContext(), + getOdataResource().checkAccessContext( getOdataResource().getNecessaryWritePrivilege(getEntitySetName())); //Create an OEntityWrapper from the request. diff --git a/src/main/java/io/personium/core/rs/odata/ODataPropertyResource.java b/src/main/java/io/personium/core/rs/odata/ODataPropertyResource.java index 9e11e2a13..716c8c944 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataPropertyResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataPropertyResource.java @@ -52,10 +52,9 @@ import org.odata4j.producer.QueryInfo; import io.personium.common.es.util.PersoniumUUID; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.annotations.WriteAPI; -import io.personium.core.auth.AccessContext; import io.personium.core.event.PersoniumEventType; import io.personium.core.odata.OEntityWrapper; import io.personium.core.odata.PersoniumFormatWriterFactory; @@ -72,7 +71,6 @@ public class ODataPropertyResource extends AbstractODataResource { private final OEntityId sourceEntityId; private final String targetNavProp; private final EdmEntitySet targetEntitySet; - private final AccessContext accessContext; private final ODataResource odataResource; /** @@ -87,7 +85,6 @@ public ODataPropertyResource( this.sourceOData = entityResource.getOdataResource(); this.sourceEntityId = entityResource.getOEntityId(); setOdataProducer(entityResource.getOdataProducer()); - this.accessContext = entityResource.getAccessContext(); this.odataResource = entityResource.getOdataResource(); //Confirm existence of Navigation property on schema EdmEntitySet eSet = getOdataProducer().getMetadata().findEdmEntitySet(this.sourceEntityId.getEntitySetName()); @@ -114,7 +111,7 @@ public ODataPropertyResource( public final Response postEntity( @Context final UriInfo uriInfo, @HeaderParam(HttpHeaders.ACCEPT) final String accept, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY) String requestKey, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY) String requestKey, @DefaultValue(FORMAT_JSON) @QueryParam("$format") final String format, final Reader reader) { //Access control @@ -242,7 +239,7 @@ EntityResponse createEntity(OEntityWrapper oew) { public final Response getNavProperty( @Context final UriInfo uriInfo, @HeaderParam(HttpHeaders.ACCEPT) final String accept, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY) String requestKey, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY) String requestKey, @QueryParam("$callback") final String callback, @QueryParam("$skiptoken") final String skipToken, @QueryParam("q") final String q) { @@ -309,7 +306,7 @@ public final Response getNavProperty( @OPTIONS public Response options() { //Access control - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryOptionsPrivilege()); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, @@ -320,18 +317,18 @@ public Response options() { private void checkWriteAccessContext() { //Access control //The same process runs twice for TODO BOX level. Since it is useless, we need ingenuity such as passing Privilege as an array to checkAccessContext - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryWritePrivilege(this.sourceEntityId.getEntitySetName())); - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryWritePrivilege(targetNavProp.substring(1))); } private void checkReadAccessContext() { //Access control //The same process runs twice for TODO BOX level. Since it is useless, we need ingenuity such as passing Privilege as an array to checkAccessContext - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryReadPrivilege(this.sourceEntityId.getEntitySetName())); - this.odataResource.checkAccessContext(this.accessContext, + this.odataResource.checkAccessContext( this.odataResource.getNecessaryReadPrivilege(targetNavProp.substring(1))); } } diff --git a/src/main/java/io/personium/core/rs/odata/ODataResource.java b/src/main/java/io/personium/core/rs/odata/ODataResource.java index 3c300e77b..b701fea49 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataResource.java @@ -55,8 +55,15 @@ import io.personium.core.utils.UriUtils; /** - * Route of JAX-RS Resource resource providing OData service Unit control · Cell control · User OData Schema · User OData It is used for 4 kinds of usage. - * Create a subclass and give rootUrl and odataProducer in the constructor. This class finishes all processing that does not depend on back side implementation, such as schema checking. + * Route of JAX-RS Resource resource providing OData service + * 4 kinds of usages. + * 1. Unit control objects + * 2. Cell control objects + * 3. User OData Schema + * 4. User OData + * Create a subclass and give rootUrl and odataProducer in the constructor. + * This class finishes all processing that does not depend on back side implementation, + * such as schema checking. */ public abstract class ODataResource extends ODataCtlResource { @@ -97,7 +104,7 @@ public AccessContext getAccessContext() { * @param ac accessContext * @param privilege Privilege */ - public abstract void checkAccessContext(AccessContext ac, Privilege privilege); + public abstract void checkAccessContext(Privilege privilege); /** * Obtain Auth Scheme that can be used for authentication. @@ -111,7 +118,7 @@ public AccessContext getAccessContext() { * @param privilege privilege * @return Accessibility */ - public abstract boolean hasPrivilege(AccessContext ac, Privilege privilege); + public abstract boolean hasPrivilege(Privilege privilege); /** * Schema authentication check processing. @@ -151,7 +158,7 @@ public String defineAccessContextSearchContext(AccessContext ac) { // @Path("") public Response optionsRoot() { //Access control - this.checkAccessContext(this.getAccessContext(), BoxPrivilege.READ); + this.checkAccessContext(BoxPrivilege.READ); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET ).build(); @@ -190,7 +197,7 @@ public Response getRoot( @QueryParam("$format") final String format, @Context HttpHeaders httpHeaders) { //Access control - this.checkAccessContext(this.getAccessContext(), BoxPrivilege.READ); + this.checkAccessContext(BoxPrivilege.READ); StringWriter w = new StringWriter(); diff --git a/src/main/java/io/personium/core/rs/odata/ODataSentMessageResource.java b/src/main/java/io/personium/core/rs/odata/ODataSentMessageResource.java index 5acb3355a..62c5bee5a 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataSentMessageResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataSentMessageResource.java @@ -63,7 +63,7 @@ import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.auth.OAuth2Helper; import io.personium.core.event.PersoniumEventType; @@ -185,6 +185,7 @@ private OCollection.Builder requestReceivedMessage( String fromCellUrl = getMessageResource().getAccessContext().getCell().getUrl(); String schema = getMessageResource().getAccessContext().getSchema(); + String[] scope = getMessageResource().getAccessContext().getScope(); //Destination list creation List toList = createRequestUrl(); @@ -196,7 +197,7 @@ private OCollection.Builder requestReceivedMessage( //Create token for receive API call TransCellAccessToken token = new TransCellAccessToken( - fromCellUrl, fromCellUrl, toCellUrl, new ArrayList(), schema); + fromCellUrl, fromCellUrl, toCellUrl, new ArrayList(), schema, scope); //Extract ID from (ID) Pattern formatPattern = Pattern.compile("\\('(.+)'\\)"); @@ -445,7 +446,7 @@ private List> requestHttpReceivedMessage( } req.setEntity(body); - req.addHeader(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_VERSION, version); + req.addHeader(CommonUtils.HttpHeaders.X_PERSONIUM_VERSION, version); req.addHeader(HttpHeaders.AUTHORIZATION, OAuth2Helper.Scheme.BEARER_CREDENTIALS_PREFIX + token.toTokenString()); req.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); diff --git a/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java b/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java index 8ad6d33ad..98c11ee0f 100644 --- a/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java +++ b/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java @@ -67,7 +67,7 @@ public class UnitCtlResource extends ODataResource { * @param accessContext AccessContext */ public UnitCtlResource(AccessContext accessContext) { - super(accessContext, UriUtils.SCHEME_UNIT_URI + "__ctl/", + super(accessContext, UriUtils.SCHEME_LOCALUNIT + ":/__ctl/", ModelFactory.ODataCtl.unitCtl(accessContext)); checkReferenceMode(accessContext); } @@ -89,7 +89,8 @@ private void checkReferenceMode(AccessContext accessContext) { * {@inheritDoc} */ @Override - public void checkAccessContext(AccessContext ac, Privilege privilege) { + public void checkAccessContext(Privilege privilege) { + AccessContext ac = this.getAccessContext(); // Accept if UnitMaster, UnitAdmin, UnitUser, UnitLocal. if (AccessContext.TYPE_UNIT_MASTER.equals(ac.getType()) || AccessContext.TYPE_UNIT_ADMIN.equals(ac.getType()) @@ -117,7 +118,7 @@ public AcceptableAuthScheme getAcceptableAuthScheme() { } @Override - public boolean hasPrivilege(AccessContext ac, Privilege privilege) { + public boolean hasPrivilege(Privilege privilege) { return false; } @@ -135,7 +136,7 @@ public void beforeCreate(OEntityWrapper oEntityWrapper) { // If there is a Subject value in UnitUserToken, set that value to Owner. String subject = this.getAccessContext().getSubject(); if (subject != null) { - String owner = UriUtils.convertSchemeFromHttpToLocalUnit(getAccessContext().getBaseUri(), subject); + String owner = UriUtils.convertSchemeFromHttpToLocalUnit(subject); oEntityWrapper.put("Owner", owner); } } @@ -148,14 +149,10 @@ public void beforeCreate(OEntityWrapper oEntityWrapper) { */ @Override public void beforeUpdate(final OEntityWrapper oEntityWrapper, final OEntityKey oEntityKey) { - String entitySetName = oEntityWrapper.getEntitySet().getName(); - EntityResponse er = this.getODataProducer() .getEntity(entitySetName, oEntityKey, new EntityQueryInfo.Builder().build()); - OEntityWrapper oew = (OEntityWrapper) er.getEntity(); - //Determining accessibility for each entity this.checkAccessContextPerEntity(this.getAccessContext(), oew); } @@ -164,22 +161,17 @@ public void beforeUpdate(final OEntityWrapper oEntityWrapper, final OEntityKey o public void beforeDelete(final String entitySetName, final OEntityKey oEntityKey) { EntityResponse er = this.getODataProducer() .getEntity(entitySetName, oEntityKey, new EntityQueryInfo.Builder().build()); - OEntityWrapper oew = (OEntityWrapper) er.getEntity(); //Determining accessibility for each entity this.checkAccessContextPerEntity(this.getAccessContext(), oew); - if (Cell.EDM_TYPE_NAME.equals(entitySetName)) { String cellId = oew.getUuid(); cell = ModelFactory.cellFromId(cellId); - //409 error if Cell is not empty if (!cell.isEmpty()) { throw PersoniumCoreException.OData.CONFLICT_HAS_RELATED; } - - } } @@ -187,7 +179,7 @@ public void beforeDelete(final String entitySetName, final OEntityKey oEntityKey public void afterDelete(final String entitySetName, final OEntityKey oEntityKey) { if (Cell.EDM_TYPE_NAME.equals(entitySetName)) { //Delete event log if it exists under Cell - String owner = cell.getOwner(); + String owner = cell.getOwnerNormalized(); try { EventUtils.deleteEventLog(this.cell.getId(), owner); } catch (BinaryDataAccessException e) { @@ -236,7 +228,7 @@ public Response optionsMetadata() { @Override public void checkAccessContextPerEntity(AccessContext ac, OEntityWrapper oew) { Map meta = oew.getMetadata(); - String owner = UriUtils.convertSchemeFromLocalUnitToHttp(ac.getBaseUri(), (String) meta.get("Owner")); + String owner = UriUtils.convertSchemeFromLocalUnitToHttp((String) meta.get("Owner")); // In case of master token, no check is required. if (AccessContext.TYPE_UNIT_MASTER.equals(ac.getType()) diff --git a/src/main/java/io/personium/core/rs/unit/UnitResource.java b/src/main/java/io/personium/core/rs/unit/UnitResource.java index 1600b5a94..9e6d4269b 100644 --- a/src/main/java/io/personium/core/rs/unit/UnitResource.java +++ b/src/main/java/io/personium/core/rs/unit/UnitResource.java @@ -33,7 +33,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; @@ -110,10 +110,10 @@ public Response get(@Context HttpHeaders httpHeaders) { */ @Path("{cellName}") public final Object cell( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY) final String xPersoniumRequestKey, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_EVENTID) final String xPersoniumEventId, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RULECHAIN) final String xPersoniumRuleChain, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_VIA) final String xPersoniumVia, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY) final String xPersoniumRequestKey, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_EVENTID) final String xPersoniumEventId, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_RULECHAIN) final String xPersoniumRuleChain, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_VIA) final String xPersoniumVia, @Context HttpServletRequest httpServletRequest, @PathParam("cellName") String cellName) { @@ -163,7 +163,7 @@ public final StatusResource status() { return new StatusResource(); } - static final String CROSSDOMAIN_XML = PersoniumCoreUtils.readStringResource("crossdomain.xml", CharEncoding.UTF_8); + static final String CROSSDOMAIN_XML = CommonUtils.readStringResource("crossdomain.xml", CharEncoding.UTF_8); /** * Crossdomain.xmlを返します。 diff --git a/src/main/java/io/personium/core/rule/RuleManager.java b/src/main/java/io/personium/core/rule/RuleManager.java index d5483bab8..c12a1b7c0 100644 --- a/src/main/java/io/personium/core/rule/RuleManager.java +++ b/src/main/java/io/personium/core/rule/RuleManager.java @@ -784,7 +784,7 @@ private void setBoxInfo(Cell cell, Box box) { if (bi != null) { bi.name = box.getName(); String schema = box.getSchema(); - bi.schema = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), schema); + bi.schema = UriUtils.convertSchemeFromLocalUnitToHttp(schema); } } } @@ -853,7 +853,7 @@ private boolean registerRule(OEntity oEntity, Cell cell) { RuleInfo rule = createRuleInfo(oEntity); // Replace personium-localunit scheme to http scheme. - rule.subject = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), rule.subject); + rule.subject = UriUtils.convertSchemeFromLocalUnitToHttp(rule.subject); // Remove fragment from TargetUrl rule.targeturl = removeFragment(rule.targeturl); try { @@ -868,7 +868,7 @@ private boolean registerRule(OEntity oEntity, Cell cell) { list.remove(0); relative = list.stream().collect(Collectors.joining("/")); } - String turl = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), rule.targeturl); + String turl = UriUtils.convertSchemeFromLocalUnitToHttp(rule.targeturl); if (relative != null) { turl += "#" + relative; } @@ -904,7 +904,7 @@ private boolean registerRule(OEntity oEntity, Cell cell) { bi.id = box.getId(); bi.name = box.getName(); String schema = box.getSchema(); - bi.schema = UriUtils.convertSchemeFromLocalUnitToHttp(cell.getUnitUrl(), schema); + bi.schema = UriUtils.convertSchemeFromLocalUnitToHttp(schema); bi.count = 0; bmap.put(bi.id, bi); } diff --git a/src/main/java/io/personium/core/rule/action/HttpAction.java b/src/main/java/io/personium/core/rule/action/HttpAction.java index badd0f19d..c827ac186 100644 --- a/src/main/java/io/personium/core/rule/action/HttpAction.java +++ b/src/main/java/io/personium/core/rule/action/HttpAction.java @@ -23,7 +23,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.event.PersoniumEvent; import io.personium.core.model.Cell; import io.personium.core.rule.ActionInfo; @@ -62,11 +62,11 @@ protected void setCommonHeaders(HttpMessage req, PersoniumEvent event) { // set common headers // X-Personium-RequestKey, X-Personium-EventId, X-Personium-RuleChain, X-Personium-Via event.getRequestKey().ifPresent(requestKey -> - req.addHeader(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY, + req.addHeader(CommonUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY, requestKey)); - req.addHeader(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_EVENTID, eventId); - req.addHeader(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RULECHAIN, chain); - getVia(event).ifPresent(via -> req.addHeader(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_VIA, via)); + req.addHeader(CommonUtils.HttpHeaders.X_PERSONIUM_EVENTID, eventId); + req.addHeader(CommonUtils.HttpHeaders.X_PERSONIUM_RULECHAIN, chain); + getVia(event).ifPresent(via -> req.addHeader(CommonUtils.HttpHeaders.X_PERSONIUM_VIA, via)); } @Override diff --git a/src/main/java/io/personium/core/rule/action/LogAction.java b/src/main/java/io/personium/core/rule/action/LogAction.java index 0739da780..506353149 100644 --- a/src/main/java/io/personium/core/rule/action/LogAction.java +++ b/src/main/java/io/personium/core/rule/action/LogAction.java @@ -63,7 +63,7 @@ private LogAction() { */ public LogAction(final Cell cell, LEVEL level) { this(); - String unitUserName = getUnitUserName(Optional.ofNullable(cell.getOwner())); + String unitUserName = getUnitUserName(Optional.ofNullable(cell.getOwnerNormalized())); String prefix1 = cell.getId().substring(IDX_1ST_START, IDX_1ST_END); String prefix2 = cell.getId().substring(IDX_2ND_START, IDX_2ND_END); String path = new StringBuilder(unitUserName) diff --git a/src/main/java/io/personium/core/rule/action/TokenBuilder.java b/src/main/java/io/personium/core/rule/action/TokenBuilder.java index c2856db98..b80f33c1d 100644 --- a/src/main/java/io/personium/core/rule/action/TokenBuilder.java +++ b/src/main/java/io/personium/core/rule/action/TokenBuilder.java @@ -22,10 +22,10 @@ import java.util.Optional; import java.util.regex.Pattern; -import io.personium.common.auth.token.AccountAccessToken; -import io.personium.common.auth.token.CellLocalAccessToken; +import io.personium.common.auth.token.ResidentLocalAccessToken; import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; +import io.personium.common.auth.token.VisitorLocalAccessToken; /** * Create token string. @@ -36,6 +36,7 @@ public class TokenBuilder { private String subject; private String schema; private List roleList; + private String[] scope; /** * Constructor. @@ -83,6 +84,15 @@ public TokenBuilder schema(String schema) { // CHECKSTYLE IGNORE this.schema = schema; return this; } + /** + * Set scope. + * @param scope scope + * @return TokenBuilder + */ + public TokenBuilder scope(String[] scope) { // CHECKSTYLE IGNORE + this.scope = scope; + return this; + } /** * Set roleList. @@ -115,20 +125,23 @@ public Optional build() { subject = null; } // AccountAccessToken - AccountAccessToken token = - new AccountAccessToken(new Date().getTime(), - cellUrl, - subject, - schema); + ResidentLocalAccessToken token = + new ResidentLocalAccessToken(new Date().getTime(), + this.cellUrl, + this.subject, + this.schema, + this.scope); accessToken = token.toTokenString(); } else { // CellLocalAccessToken - CellLocalAccessToken token = - new CellLocalAccessToken(new Date().getTime(), - cellUrl, - subject, - roleList, - schema); + VisitorLocalAccessToken token = + new VisitorLocalAccessToken(new Date().getTime(), + VisitorLocalAccessToken.ACCESS_TOKEN_EXPIRES_MILLISECS, + this.cellUrl, + this.subject, + this.roleList, + this.schema, + this.scope); accessToken = token.toTokenString(); } } else { @@ -139,7 +152,7 @@ public Optional build() { subject, targetCellUrl, roleList, - schema); + schema, scope); accessToken = token.toTokenString(); } diff --git a/src/main/java/io/personium/core/snapshot/SnapshotFileImportRunner.java b/src/main/java/io/personium/core/snapshot/SnapshotFileImportRunner.java index 39afac4b2..24c680993 100644 --- a/src/main/java/io/personium/core/snapshot/SnapshotFileImportRunner.java +++ b/src/main/java/io/personium/core/snapshot/SnapshotFileImportRunner.java @@ -234,7 +234,7 @@ private void modifyCellInfo(SnapshotFile snapshotFile) { Map s = (Map) map.get(OEntityDocHandler.KEY_STATIC_FIELDS); s.put("Name", targetCell.getName()); Map h = (Map) map.get(OEntityDocHandler.KEY_HIDDEN_FIELDS); - String owner = UriUtils.convertSchemeFromHttpToLocalUnit(targetCell.getUnitUrl(), targetCell.getOwner()); + String owner = UriUtils.convertSchemeFromHttpToLocalUnit(targetCell.getOwnerNormalized()); h.put("Owner", owner); map.put(OEntityDocHandler.KEY_UPDATED, System.currentTimeMillis()); diff --git a/src/main/java/io/personium/core/utils/ODataUtils.java b/src/main/java/io/personium/core/utils/ODataUtils.java index 1fe395dd7..1abe657e2 100644 --- a/src/main/java/io/personium/core/utils/ODataUtils.java +++ b/src/main/java/io/personium/core/utils/ODataUtils.java @@ -360,17 +360,6 @@ private static boolean isValidSchemaUrlScheme(String scheme) { return isValidUrnScheme(scheme) || isValidCellUrlScheme(scheme); } - private static boolean isValidLocalUnitUrlScheme(String scheme) { - return UriUtils.SCHEME_LOCALUNIT.equals(scheme); - } - - private static boolean isValidLocalCellUrlScheme(String scheme) { - return UriUtils.SCHEME_LOCALCELL.equals(scheme); - } - - private static boolean isValidLocalBoxUrlScheme(String scheme) { - return UriUtils.SCHEME_LOCALBOX.equals(scheme); - } /** * Check if string is valid Uri. @@ -454,8 +443,10 @@ public static boolean isValidCellUrl(String str) { } String scheme = uri.getScheme(); boolean isValidScheme = isValidCellUrlScheme(scheme); - if (isValidScheme && isValidLocalUnitUrlScheme(scheme)) { - isValidScheme = validateLocalUnitUrl(str, Common.PATTERN_CELL_LOCALUNIT_PATH); + if (isValidScheme && UriUtils.SCHEME_LOCALUNIT.equals(scheme)) { + boolean b1 = validateLocalUnitUrl(str, Common.PATTERN_CELL_LOCALUNIT_PATH); + boolean b2 = UriUtils.REGEX_LOCALUNIT_DOUBLE_COLONS.matcher(str).matches(); + isValidScheme = b1 || b2; } boolean isNormalized = uri.normalize().toString().equals(str); boolean hasTrailingSlash = str.endsWith("/"); @@ -488,7 +479,7 @@ public static boolean isValidLocalCellUrl(String str) { return false; } String scheme = uri.getScheme(); - boolean isValidScheme = isValidLocalCellUrlScheme(scheme); + boolean isValidScheme = UriUtils.SCHEME_LOCALCELL.equals(scheme); boolean isNormalized = uri.normalize().toString().equals(str); return isValidLength && isValidScheme && isNormalized; } @@ -510,7 +501,7 @@ public static boolean isValidLocalBoxUrl(String str) { return false; } String scheme = uri.getScheme(); - boolean isValidScheme = isValidLocalBoxUrlScheme(scheme); + boolean isValidScheme = UriUtils.SCHEME_LOCALBOX.equals(scheme); boolean isNormalized = uri.normalize().toString().equals(str); return isValidLength && isValidScheme && isNormalized; } @@ -532,7 +523,7 @@ public static boolean isValidLocalUnitUrl(String str) { return false; } String scheme = uri.getScheme(); - boolean isValidScheme = isValidLocalUnitUrlScheme(scheme); + boolean isValidScheme = UriUtils.SCHEME_LOCALUNIT.equals(scheme); boolean isNormalized = uri.normalize().toString().equals(str); return isValidLength && isValidScheme && isNormalized; } @@ -561,7 +552,7 @@ private static boolean validateLocalUnitUrl(String str, String pFormat) { uri = new URI(str); String scheme = uri.getScheme(); // Scheme check - if (!isValidLocalUnitUrlScheme(scheme)) { + if (!UriUtils.SCHEME_LOCALUNIT.equals(scheme)) { return false; } // String length check diff --git a/src/main/java/io/personium/core/utils/ResourceUtils.java b/src/main/java/io/personium/core/utils/ResourceUtils.java index ea5313b06..30faf4243 100644 --- a/src/main/java/io/personium/core/utils/ResourceUtils.java +++ b/src/main/java/io/personium/core/utils/ResourceUtils.java @@ -40,7 +40,7 @@ import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; -import io.personium.common.utils.PersoniumCoreUtils.HttpHeaders; +import io.personium.common.utils.CommonUtils.HttpHeaders; import io.personium.core.PersoniumCoreException; /** diff --git a/src/main/java/io/personium/core/utils/UriUtils.java b/src/main/java/io/personium/core/utils/UriUtils.java index d5e2e7ac2..f1852fd60 100644 --- a/src/main/java/io/personium/core/utils/UriUtils.java +++ b/src/main/java/io/personium/core/utils/UriUtils.java @@ -20,6 +20,9 @@ import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; +import java.util.Objects; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; @@ -31,35 +34,46 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; /** - * Scheme Utilities. - * @author fjqs + * Utilities for handling URIs with personium-* scheme. + * @author fjqs, shimono * */ public class UriUtils { - /** PRTCOL HTTP. */ + /** Scheme string, "http". */ public static final String SCHEME_HTTP = "http"; - /** PRTCOL HTTPS. */ + /** Scheme string, "https". */ public static final String SCHEME_HTTPS = "https"; - /** SCHEME URN. */ + /** Scheme string, "urn". */ public static final String SCHEME_URN = "urn"; - /** LOCAL_UNIT. */ + /** Scheme string, "personium-localunit". */ public static final String SCHEME_LOCALUNIT = "personium-localunit"; - /** LOCAL_CELL. */ + /** Scheme string, "personium-localcell". */ public static final String SCHEME_LOCALCELL = "personium-localcell"; - /** LOCAL_BOX. */ + /** Scheme string, "personium-localbox". */ public static final String SCHEME_LOCALBOX = "personium-localbox"; - /** LOCAL_UNIT ADDITION. */ - public static final String SCHEME_UNIT_URI = "personium-localunit:/"; /** LOCAL_CELL ADDITION. */ - public static final String SCHEME_CELL_URI = "personium-localcell:/"; + public static final String SCHEME_CELL_URI = SCHEME_LOCALCELL + ":/"; /** LOCAL_BOX ADDITION. */ - public static final String SCHEME_BOX_URI = "personium-localbox:/"; + public static final String SCHEME_BOX_URI = SCHEME_LOCALBOX + ":/"; - /** SLASH. */ + + /** Regular expression for matching localunit scheme with single colon */ + public static final Pattern REGEX_LOCALUNIT_SINGLE_COLON + = Pattern.compile("^" + SCHEME_LOCALUNIT + ":(.*)$"); + + /** Regular expression for matching localunit scheme with double colons */ + public static final Pattern REGEX_LOCALUNIT_DOUBLE_COLONS + = Pattern.compile("^" + SCHEME_LOCALUNIT + ":(.+?):(.*)$"); + + /** Regular expression for matching Cell URL */ + public static final String REGEX_HTTP_SUBDOMAIN = "^(http|https):\\/\\/(.+?)\\.(.*)$"; + + /** String Slash. */ public static final String STRING_SLASH = "/"; /** @@ -73,15 +87,17 @@ private UriUtils() { * @param unitUrl String * @param url String * @return ArrayList + * @throws URISyntaxException */ - public static List getUrlVariations(String unitUrl, String url) { + public static List getUrlVariations(String url) throws PersoniumCoreException { List variations = new ArrayList(); + if (url == null) { + return variations; + } variations.add(url); - if (url != null && unitUrl != null) { - String substitute = getUrlSubstitute(unitUrl, url); - if (!url.equals(substitute)) { - variations.add(substitute); - } + String substitute = getUrlSubstitute(url); + if (!url.equals(substitute)) { + variations.add(substitute); } return variations; } @@ -91,14 +107,16 @@ public static List getUrlVariations(String unitUrl, String url) { * @param unitUrl String * @param url String * @return utl String + * @throws URISyntaxException */ - public static String getUrlSubstitute(String unitUrl, String url) { - if (url != null && unitUrl != null) { - if (url.startsWith(SCHEME_UNIT_URI)) { - url = convertSchemeFromLocalUnitToHttp(unitUrl, url); - } else { - url = convertSchemeFromHttpToLocalUnit(unitUrl, url); - } + public static String getUrlSubstitute(String url) { + if (url == null) { + throw PersoniumCoreException.Common.INVALID_URL.params("null"); + } + if (url.startsWith(SCHEME_LOCALUNIT)) { + url = convertSchemeFromLocalUnitToHttp(url); + } else { + url = convertSchemeFromHttpToLocalUnit(url); } return url; } @@ -117,54 +135,110 @@ public static boolean isLocalUnitUrl(String targetUrl) { /** * Convert scheme from LocalUnit to http(s). - * @param unitUrl unit url + * If the he given value does not match localunit schem, the given value is returned as-is. * @param localUnitSchemeUrl local unit url * @return url string with http(s) scheme */ - public static String convertSchemeFromLocalUnitToHttp(String unitUrl, String localUnitSchemeUrl) { - if (localUnitSchemeUrl != null && localUnitSchemeUrl.startsWith(SCHEME_UNIT_URI)) { - String pathBased = localUnitSchemeUrl.replaceFirst(SCHEME_UNIT_URI, unitUrl); - if (PersoniumUnitConfig.isPathBasedCellUrlEnabled()) { - return pathBased; - } else { - try { - return convertPathBaseToFqdnBase(pathBased); - } catch (URISyntaxException e) { - return localUnitSchemeUrl; - } + public static String convertSchemeFromLocalUnitToHttp(String localUnitSchemeUrl) { + if (localUnitSchemeUrl == null) { + return null; + } + String unitUrl = PersoniumUnitConfig.getBaseUrl(); + Matcher localUnitDoubleColons = REGEX_LOCALUNIT_DOUBLE_COLONS.matcher(localUnitSchemeUrl); + Matcher localUnitSingleColon = REGEX_LOCALUNIT_SINGLE_COLON.matcher(localUnitSchemeUrl); + String pathBased = localUnitSchemeUrl; + if (localUnitDoubleColons.matches()) { + // when detected personium-localunit scheme with double colons + String cellName = localUnitDoubleColons.group(1); + String path = localUnitDoubleColons.group(2); + StringBuilder sb = new StringBuilder(unitUrl); + sb.append(cellName); + if (!path.startsWith(STRING_SLASH)) { + sb.append(STRING_SLASH); + } + sb.append(path); + pathBased = sb.toString(); + } else if (localUnitSingleColon.matches()) { + // when detected personium-localunit scheme with single colon + String path = localUnitSingleColon.group(1); + if (path.startsWith(STRING_SLASH) && unitUrl.endsWith(STRING_SLASH)) { + unitUrl = unitUrl.replaceFirst("/*$", ""); + } + StringBuilder sb = new StringBuilder(unitUrl); + sb.append(path); + pathBased = sb.toString(); + } + if (PersoniumUnitConfig.isPathBasedCellUrlEnabled()) { + return pathBased; + } else { + try { + return convertPathBaseToFqdnBase(pathBased); + } catch (URISyntaxException e) { + return localUnitSchemeUrl; } } - return localUnitSchemeUrl; } /** * Convert scheme from http(s) to LocalUnit. - * Convert only if the target URL matches UnitURL. + * Convert only if the target URL matches UnitURL, otherwise just return the given value as-is. * @param unitUrl unit url * @param url target url * @return url string with local unit scheme */ - public static String convertSchemeFromHttpToLocalUnit(String unitUrl, String url) { + public static String convertSchemeFromHttpToLocalUnit(String url) { if (url == null) { - return url; - } - if (url.startsWith(unitUrl)) { - return url.replaceFirst(unitUrl, SCHEME_UNIT_URI); - } - - // convert to path based url - String pathBased; - try { - pathBased = convertFqdnBaseToPathBase(url); - } catch (URISyntaxException e) { - return url; - } - - if (pathBased != null && pathBased.startsWith(unitUrl)) { - return pathBased.replaceFirst(unitUrl, SCHEME_UNIT_URI); + return null; + } + String unitUrl = PersoniumUnitConfig.getBaseUrl(); + if (PersoniumUnitConfig.isPathBasedCellUrlEnabled()) { + // path based + if (!url.startsWith(unitUrl)) { + // return as-is when url is foreign + return url; + } + // convert when url is localunit + String ret = url.replaceFirst(unitUrl, SCHEME_LOCALUNIT + ":/"); + ret = ret.replaceFirst("\\:\\/(.+?)\\/", ":$1:/"); + return ret; + } else { + // return with single colon syntax when url is unit level. + if (url.startsWith(unitUrl)) { + // convert when url is localunit + return url.replaceFirst(unitUrl, SCHEME_LOCALUNIT + ":/"); + } + // return with double colon syntax when url is cell level. + URI uri; + try { + uri = new URI(url); + } catch (URISyntaxException e) { + throw PersoniumCoreException.Common.INVALID_URL.params(url).reason(e); + } + URI unitUri; + try { + unitUri = new URI(unitUrl); + } catch (URISyntaxException e) { + throw PersoniumCoreException.Common.INVALID_URL.params(unitUrl).reason(e); + } + if (uri.getHost() == null) { + return url; + } + String host = uri.getHost(); + String cellName = host.split("\\.")[0]; + String unitDomain = host.replaceFirst(cellName + "\\.", ""); + if (uri.getHost() == null) { + return url; + } + String unitHost = unitUri.getHost(); + if (!unitDomain.contentEquals(unitHost)) { + // foreign URL + return url; + } + StringBuilder sb = new StringBuilder(SCHEME_LOCALUNIT); + sb.append(":").append(cellName).append(":"); + sb.append(uri.getPath()); + return sb.toString(); } - - return url; } /** @@ -445,4 +519,34 @@ public URI relativize(URI uri) { return this.core.relativize(uri); } } + + public static boolean equalIgnoringPort(String url1, String url2) { + + try { + URI u1 = new URI(url1); + URI u2 = new URI(url2); + if (!Objects.equals(u1.getHost(), u2.getHost())) { + return false; + } + if (!Objects.equals(u1.getScheme(), u2.getScheme())) { + return false; + } + if (!Objects.equals(u1.getPath(), u2.getPath())) { + return false; + } + if (!Objects.equals(u1.getFragment(), u2.getFragment())) { + return false; + } + if (!Objects.equals(u1.getQuery(), u2.getQuery())) { + return false; + } + return true; + } catch (URISyntaxException e) { + return false; + } + } + + public static String resolveLocalUnit(String url) { + return UriUtils.convertSchemeFromLocalUnitToHttp(url); + } } diff --git a/src/main/java/io/personium/core/ws/StreamEndpoint.java b/src/main/java/io/personium/core/ws/StreamEndpoint.java index df242e6f8..b863125c5 100644 --- a/src/main/java/io/personium/core/ws/StreamEndpoint.java +++ b/src/main/java/io/personium/core/ws/StreamEndpoint.java @@ -60,7 +60,7 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.core.stream.DataSubscriber; import io.personium.core.stream.IDataListener; @@ -384,7 +384,7 @@ private boolean checkTopic(String token, String topic) { } req.addHeader(HttpHeaders.AUTHORIZATION, - PersoniumCoreUtils.createBearerAuthzHeader(token)); + CommonUtils.createBearerAuthzHeader(token)); req.addHeader(HttpHeaders.DEPTH, "0"); req.addHeader(HttpHeaders.ACCEPT, "application/xml"); @@ -420,19 +420,19 @@ private boolean checkTopic(String token, String topic) { } Element resourcetypeElem = (Element) resourcetypeList.item(0); NodeList streamList; - streamList = resourcetypeElem.getElementsByTagNameNS(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, + streamList = resourcetypeElem.getElementsByTagNameNS(CommonUtils.XmlConst.NS_PERSONIUM, "stream"); if (streamList.getLength() != 1) { break; } // check topics NodeList topicsList; - topicsList = propstatElem.getElementsByTagNameNS(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, + topicsList = propstatElem.getElementsByTagNameNS(CommonUtils.XmlConst.NS_PERSONIUM, "topics"); for (int j = 0; j < topicsList.getLength(); j++) { Element topicElem = (Element) topicsList.item(j); NodeList topicList; - topicList = topicElem.getElementsByTagNameNS(PersoniumCoreUtils.XmlConst.NS_PERSONIUM, + topicList = topicElem.getElementsByTagNameNS(CommonUtils.XmlConst.NS_PERSONIUM, "topic"); for (int k = 0; k < topicList.getLength(); k++) { if (topicName.equals(topicList.item(k).getTextContent())) { @@ -496,7 +496,7 @@ private boolean checkPrivilege(String token, String topic) { } req.addHeader(HttpHeaders.AUTHORIZATION, - PersoniumCoreUtils.createBearerAuthzHeader(token)); + CommonUtils.createBearerAuthzHeader(token)); try (CloseableHttpClient client = HttpClientFactory.create(HttpClientFactory.TYPE_INSECURE); CloseableHttpResponse response = client.execute(req)) { @@ -537,7 +537,7 @@ private long getExpirationTime(String token, String topic) { params.add(new BasicNameValuePair("token", token)); req.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); req.addHeader(HttpHeaders.AUTHORIZATION, - PersoniumCoreUtils.createBasicAuthzHeader(PersoniumUnitConfig.getIntrospectUsername(), + CommonUtils.createBasicAuthzHeader(PersoniumUnitConfig.getIntrospectUsername(), PersoniumUnitConfig.getIntrospectPassword())); } catch (Exception e) { return result; diff --git a/src/main/java/io/personium/core/ws/WebSocketService.java b/src/main/java/io/personium/core/ws/WebSocketService.java index 23994024a..a9b19df0c 100644 --- a/src/main/java/io/personium/core/ws/WebSocketService.java +++ b/src/main/java/io/personium/core/ws/WebSocketService.java @@ -455,7 +455,7 @@ private void onReceiveExEvent(Session session, JSONObject event) { CellCmp cellCmp = ModelFactory.cellCmp(cell); if (cellCmp.exists()) { CellRsCmp cellRsCmp = new CellRsCmp(cellCmp, cell, ac); - cellRsCmp.checkAccessContext(ac, CellPrivilege.EVENT); + cellRsCmp.checkAccessContext(CellPrivilege.EVENT); PersoniumEvent pEvent = new PersoniumEvent.Builder() .external() .type((String) event.get("Type")) @@ -735,7 +735,7 @@ private static boolean checkPrivilege(String accessToken, String cellId) { result = false; } CellRsCmp cellRsCmp = new CellRsCmp(cellCmp, cell, ac); - cellRsCmp.checkAccessContext(ac, CellPrivilege.EVENT_READ); + cellRsCmp.checkAccessContext(CellPrivilege.EVENT_READ); } catch (Exception e) { e.printStackTrace(); result = false; diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml index e4355ecfb..521773893 100644 --- a/src/main/resources/logback.xml +++ b/src/main/resources/logback.xml @@ -86,7 +86,7 @@ - + diff --git a/src/main/resources/personium-log-level.properties b/src/main/resources/personium-log-level.properties index b5daac350..52ab1a737 100644 --- a/src/main/resources/personium-log-level.properties +++ b/src/main/resources/personium-log-level.properties @@ -73,7 +73,7 @@ io.personium.core.loglevel.PL-SC-0002=info # Elastic Search io.personium.core.loglevel.PL-ES-0001=info -io.personium.core.loglevel.PL-ES-0002=info +io.personium.core.loglevel.PL-ES-0002=debug io.personium.core.loglevel.PL-ES-0003=info io.personium.core.loglevel.PL-ES-0004=info io.personium.core.loglevel.PL-ES-0005=debug diff --git a/src/main/resources/personium-messages.properties b/src/main/resources/personium-messages.properties index 12dde289e..dfc3b03e0 100644 --- a/src/main/resources/personium-messages.properties +++ b/src/main/resources/personium-messages.properties @@ -200,6 +200,7 @@ io.personium.core.msg.PR403-AU-0003=This resource can not be accessed by the Uni io.personium.core.msg.PR403-AU-0004=Schema authentication is required to access this resource. io.personium.core.msg.PR403-AU-0005=This resource can not be accessed with the schema that has been authenticated. io.personium.core.msg.PR403-AU-0006=Insufficient schema authorization level. +io.personium.core.msg.PR403-AU-0007=Insufficient scope is granted for the access token. [{0}] Privilege is required. ## Authn # PR400-AN @@ -207,7 +208,7 @@ io.personium.core.msg.PR400-AN-0001=Unsupported grant type.{0} io.personium.core.msg.PR400-AN-0002=Invalid p_target. # client authn error -io.personium.core.msg.PR400-AN-0003=Failed to parse client secret. +io.personium.core.msg.PR400-AN-0003=Failed to parse client assertion. io.personium.core.msg.PR400-AN-0004=Client secret is expired and invalid. io.personium.core.msg.PR400-AN-0005=Client secret dsig is invalid. io.personium.core.msg.PR400-AN-0006=Client secret issuer does not match the client_id. @@ -228,6 +229,9 @@ io.personium.core.msg.PR400-AN-0016=Required parameter [{0}] missing. io.personium.core.msg.PR400-AN-0017=Authentication failed. io.personium.core.msg.PR400-AN-0018=Authorization header is invalid. +io.personium.core.msg.PR401-AN-0020=Client mismatch for refresh token. [{0}] +io.personium.core.msg.PR401-AN-0021=Client Auth is required. +io.personium.core.msg.PR400-AN-0022=Invalid Client Assertion Type. Acceptable Value is [{0}]. io.personium.core.msg.PR401-AN-0001=The password should be changed. @@ -370,6 +374,7 @@ io.personium.core.msg.PR409-CM-0002=Because [{0}] is being executed, writing to io.personium.core.msg.PR500-CM-0001=Failed to load the request body for some reason. io.personium.core.msg.PR500-CM-0002=Files I/O error caused [{0}] to fail. +io.personium.core.msg.PR500-CM-0003=Invalid URL [{0}] is used internally. ## Plugin # PR500-PL diff --git a/src/main/resources/personium-unit-config-default.properties b/src/main/resources/personium-unit-config-default.properties index 970c9034a..1bf46bea6 100644 --- a/src/main/resources/personium-unit-config-default.properties +++ b/src/main/resources/personium-unit-config-default.properties @@ -1,6 +1,8 @@ # -# personium.io -# Copyright 2018 FUJITSU LIMITED +# Personium +# Copyright 2019 Personium Project +# - FUJITSU LIMITED +# - (Add Authorss here) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -18,12 +20,12 @@ ################################################# # personium-core default configurations # -# DO NOT CHANGE CONFIGURATIONS BELOW. +# DO NOT CHANGE THE CONTENTS OF THIS FILE BELOW. # USE "personium-unit-config.properties" TO CHANGE CONFIGURATIONS. ################################################# # core version -io.personium.core.version=1.7.17 +io.personium.core.version=1.7.18 # thread pool num. io.personium.core.thread.pool.num.io.cell=10 @@ -44,7 +46,7 @@ io.personium.core.engine.host=localhost io.personium.core.engine.port=8080 io.personium.core.engine.path=personium-engine -# cell configurations +# cell GUI configurations #io.personium.core.cell.relayhtmlurl.default=https://demo.personium.io/app-cc-home/__/index.html #io.personium.core.cell.authorizationhtmlurl.default= #io.personium.core.cell.authorizationpasswordchangehtmlurl.default= @@ -76,7 +78,7 @@ io.personium.core.cache.box.enabled=true io.personium.core.cache.schema.enabled=true io.personium.core.cache.memcached.expiresin=86400 -# BinaryData configurations +# File Data Store configurations io.personium.core.binaryData.physical.delete.mode=true io.personium.core.binaryData.fsync.enabled=false io.personium.core.binaryData.dav.retry.count=100 @@ -84,7 +86,7 @@ io.personium.core.binaryData.dav.retry.interval=50 # blob store configurations io.personium.core.blobStore.root=/personium_nfs/personium-core/dav -# elasticsearch configurations +# Elasticsearch configurations io.personium.core.es.hosts=localhost:9300 io.personium.core.es.cluster.name=clusterpersonium io.personium.core.es.unitPrefix=u0 @@ -97,11 +99,8 @@ io.personium.core.es.index.numberOfReplicas=0 io.personium.core.es.index.maxResultWindow=150000 #io.personium.core.es.index.merge.scheduler.maxThreadCount= -# security configurations -# You must set these properties to personium-unit-config.properties file. +# Security configurations io.personium.core.masterToken= -#io.personium.core.security.secret16=changeme -#io.personium.core.security.auth.password.salt=changeme io.personium.core.security.auth.password.regex=^[a-zA-Z0-9-_!$*=^`{|}~.@]{6,32}$ io.personium.core.security.auth.password.hashAlgorithm=scrypt io.personium.core.security.auth.password.scrypt.cpuCost=16384 @@ -109,8 +108,18 @@ io.personium.core.security.auth.password.scrypt.memoryCost=8 io.personium.core.security.auth.password.scrypt.parallelization=1 io.personium.core.security.auth.password.scrypt.keyLength=32 io.personium.core.security.auth.password.scrypt.saltLength=64 +#io.personium.core.security.secret16=changeme +#io.personium.core.security.auth.password.salt=changeme io.personium.core.security.dav.encrypt.enabled=false +# Default token scope for various grant types +# "root" scope will be given as default for compatibility reason. +# Change these settings to make your unit more secure +io.personium.core.security.token.defaultScope.ropc=root +io.personium.core.security.token.defaultScope.assertion=root +io.personium.core.security.token.defaultScope.grant_code=root + + # X509 Certificate file in PEM format # io.personium.core.x509.crt=/opt/x509/localhost.crt # X509 RSA PrivateKey file in PEM format diff --git a/src/test/java/io/personium/core/PersoniumReadDeleteModeManagerTest.java b/src/test/java/io/personium/core/PersoniumReadDeleteModeManagerTest.java index 522e945c1..c886045e9 100644 --- a/src/test/java/io/personium/core/PersoniumReadDeleteModeManagerTest.java +++ b/src/test/java/io/personium/core/PersoniumReadDeleteModeManagerTest.java @@ -32,7 +32,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.model.lock.ReadDeleteModeLockManager; /** @@ -85,7 +85,7 @@ public class PersoniumReadDeleteModeManagerTest { List pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" }); try { PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode( - PersoniumCoreUtils.HttpMethod.PROPFIND, pathSegment); + CommonUtils.HttpMethod.PROPFIND, pathSegment); } catch (PersoniumCoreException e) { fail(e.getMessage()); } @@ -172,7 +172,7 @@ public class PersoniumReadDeleteModeManagerTest { PowerMockito.spy(ReadDeleteModeLockManager.class); PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(true); List pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" }); - PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(PersoniumCoreUtils.HttpMethod.MERGE, + PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(CommonUtils.HttpMethod.MERGE, pathSegment); } @@ -185,7 +185,7 @@ public class PersoniumReadDeleteModeManagerTest { PowerMockito.spy(ReadDeleteModeLockManager.class); PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(true); List pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" }); - PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(PersoniumCoreUtils.HttpMethod.MKCOL, + PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(CommonUtils.HttpMethod.MKCOL, pathSegment); } @@ -198,7 +198,7 @@ public class PersoniumReadDeleteModeManagerTest { PowerMockito.spy(ReadDeleteModeLockManager.class); PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(true); List pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" }); - PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(PersoniumCoreUtils.HttpMethod.PROPPATCH, + PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(CommonUtils.HttpMethod.PROPPATCH, pathSegment); } @@ -211,7 +211,7 @@ public class PersoniumReadDeleteModeManagerTest { PowerMockito.spy(ReadDeleteModeLockManager.class); PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(true); List pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" }); - PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(PersoniumCoreUtils.HttpMethod.ACL, + PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(CommonUtils.HttpMethod.ACL, pathSegment); } @@ -257,7 +257,7 @@ public class PersoniumReadDeleteModeManagerTest { PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(false); List pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" }); try { - PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(PersoniumCoreUtils.HttpMethod.MERGE, + PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(CommonUtils.HttpMethod.MERGE, pathSegment); } catch (PersoniumCoreException e) { fail(e.getMessage()); @@ -274,7 +274,7 @@ public class PersoniumReadDeleteModeManagerTest { PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(false); List pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" }); try { - PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(PersoniumCoreUtils.HttpMethod.MKCOL, + PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(CommonUtils.HttpMethod.MKCOL, pathSegment); } catch (PersoniumCoreException e) { fail(e.getMessage()); @@ -292,7 +292,7 @@ public class PersoniumReadDeleteModeManagerTest { List pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" }); try { PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode( - PersoniumCoreUtils.HttpMethod.PROPPATCH, pathSegment); + CommonUtils.HttpMethod.PROPPATCH, pathSegment); } catch (PersoniumCoreException e) { fail(e.getMessage()); } @@ -308,7 +308,7 @@ public class PersoniumReadDeleteModeManagerTest { PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(false); List pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" }); try { - PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(PersoniumCoreUtils.HttpMethod.ACL, + PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(CommonUtils.HttpMethod.ACL, pathSegment); } catch (PersoniumCoreException e) { fail(e.getMessage()); diff --git a/src/test/java/io/personium/core/PersoniumUnitConfigTest.java b/src/test/java/io/personium/core/PersoniumUnitConfigTest.java index 0c02c41f7..7d14ea703 100644 --- a/src/test/java/io/personium/core/PersoniumUnitConfigTest.java +++ b/src/test/java/io/personium/core/PersoniumUnitConfigTest.java @@ -19,15 +19,14 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.test.categories.Unit; /** @@ -36,7 +35,7 @@ @Category({ Unit.class }) @RunWith(PowerMockRunner.class) -@PrepareForTest({ PersoniumCoreUtils.class, PersoniumUnitConfig.class }) +@PrepareForTest({ CommonUtils.class, PersoniumUnitConfig.class }) public class PersoniumUnitConfigTest { /** @@ -46,30 +45,30 @@ public class PersoniumUnitConfigTest { */ @Test public void getBaseUrl_Noraml() throws Exception { - PowerMockito.spy(PersoniumCoreUtils.class); + PowerMockito.spy(CommonUtils.class); PowerMockito.spy(PersoniumUnitConfig.class); - PowerMockito.doReturn("host.domain").when(PersoniumCoreUtils.class, "getFQDN"); + PowerMockito.doReturn("host.domain").when(CommonUtils.class, "getFQDN"); PowerMockito.doReturn("https").when(PersoniumUnitConfig.class, "getUnitScheme"); - PowerMockito.doReturn(-1).when(PersoniumUnitConfig.class, "getUnitPort"); - assertThat(PersoniumUnitConfig.getBaseUrl(), is("https://host.domain/")); + PowerMockito.doReturn(9998).when(PersoniumUnitConfig.class, "getUnitPort"); + assertThat(PersoniumUnitConfig.getBaseUrl(), is("https://host.domain:9998/")); - PowerMockito.doReturn("host.domain").when(PersoniumCoreUtils.class, "getFQDN"); + PowerMockito.doReturn("host.domain").when(CommonUtils.class, "getFQDN"); PowerMockito.doReturn("http").when(PersoniumUnitConfig.class, "getUnitScheme"); PowerMockito.doReturn(-1).when(PersoniumUnitConfig.class, "getUnitPort"); assertThat(PersoniumUnitConfig.getBaseUrl(), is("http://host.domain/")); - PowerMockito.doReturn("host.domain").when(PersoniumCoreUtils.class, "getFQDN"); + PowerMockito.doReturn("host.domain").when(CommonUtils.class, "getFQDN"); PowerMockito.doReturn("https").when(PersoniumUnitConfig.class, "getUnitScheme"); PowerMockito.doReturn(443).when(PersoniumUnitConfig.class, "getUnitPort"); assertThat(PersoniumUnitConfig.getBaseUrl(), is("https://host.domain:443/")); - PowerMockito.doReturn("localhost").when(PersoniumCoreUtils.class, "getFQDN"); + PowerMockito.doReturn("localhost").when(CommonUtils.class, "getFQDN"); PowerMockito.doReturn("https").when(PersoniumUnitConfig.class, "getUnitScheme"); PowerMockito.doReturn(-1).when(PersoniumUnitConfig.class, "getUnitPort"); assertThat(PersoniumUnitConfig.getBaseUrl(), is("https://localhost/")); - PowerMockito.doReturn("192.168.1.10").when(PersoniumCoreUtils.class, "getFQDN"); + PowerMockito.doReturn("192.168.1.10").when(CommonUtils.class, "getFQDN"); PowerMockito.doReturn("https").when(PersoniumUnitConfig.class, "getUnitScheme"); PowerMockito.doReturn(-1).when(PersoniumUnitConfig.class, "getUnitPort"); assertThat(PersoniumUnitConfig.getBaseUrl(), is("https://192.168.1.10/")); diff --git a/src/test/java/io/personium/core/auth/AccessContextTest.java b/src/test/java/io/personium/core/auth/AccessContextTest.java index 6b2869d7c..3c690a4f5 100644 --- a/src/test/java/io/personium/core/auth/AccessContextTest.java +++ b/src/test/java/io/personium/core/auth/AccessContextTest.java @@ -24,6 +24,7 @@ import java.net.URI; import java.net.URISyntaxException; +import java.util.Date; import java.util.List; import java.util.UUID; @@ -39,10 +40,9 @@ import org.junit.runner.RunWith; import org.mockito.Matchers; -import io.personium.common.auth.token.CellLocalAccessToken; -import io.personium.common.auth.token.LocalToken; import io.personium.common.auth.token.UnitLocalUnitUserToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.auth.token.VisitorLocalAccessToken; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.core.model.Cell; import io.personium.core.odata.OEntityWrapper; @@ -51,14 +51,14 @@ import io.personium.test.unit.core.UrlUtils; /** - * AccessContext ユニットテストクラス. + * Unit test class for AccessContext. */ @RunWith(PersoniumIntegTestRunner.class) @Category({ Unit.class }) public class AccessContextTest { /** - * マスタートークン. + * Master Token. */ public static final String MASTER_TOKEN = PersoniumUnitConfig.getMasterToken(); @@ -155,7 +155,7 @@ public void testCreate() { @Ignore public void testCreateBasic() { String auth = "Basic " - + PersoniumCoreUtils.encodeBase64Url("user:pass".getBytes()); + + CommonUtils.encodeBase64Url("user:pass".getBytes()); Cell cell = (Cell) mock(Cell.class); when(cell.authenticateAccount((OEntityWrapper) Matchers.any(), Matchers.anyString())).thenReturn(true); // 第1引数は AuthHeader, 第2引数は UriInfo, 第3引数は cookie_peer, 第4引数は cookie内の暗号化されたトークン情報 @@ -171,7 +171,7 @@ public void testCreateBasic() { @Test public void testCreateBasicINVALID() { String auth = "Basic " - + PersoniumCoreUtils.encodeBase64Url("user:pass".getBytes()); + + CommonUtils.encodeBase64Url("user:pass".getBytes()); Cell cell = (Cell) mock(Cell.class); when(cell.authenticateAccount((OEntityWrapper) Matchers.any(), Matchers.anyString())).thenReturn(false); // 第1引数は AuthHeader, 第2引数は UriInfo, 第3引数は cookie_peer, 第4引数は cookie内の暗号化されたトークン情報 @@ -241,7 +241,7 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { public void AuthorizationHeaderなしでのULUUTのcookie認証によるAccessContext生成の正常系テスト() { Cell cell = (Cell) mock(Cell.class); when(cell.authenticateAccount((OEntityWrapper) Matchers.any(), Matchers.anyString())).thenReturn(true); - when(cell.getOwner()).thenReturn("cellowner"); + when(cell.getOwnerNormalized()).thenReturn("cellowner"); when(cell.getUrl()).thenReturn(UrlUtils.getBaseUrl() + "/cellowner"); when(cell.getUnitUrl()).thenReturn(UrlUtils.getBaseUrl()); @@ -250,15 +250,13 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { // uluut発行処理 UnitLocalUnitUserToken uluut = new UnitLocalUnitUserToken( System.currentTimeMillis(), UnitLocalUnitUserToken.ACCESS_TOKEN_EXPIRES_HOUR * MILLISECS_IN_AN_HOUR, - cell.getOwner(), UrlUtils.getBaseUrl()); + cell.getOwnerNormalized(), UrlUtils.getBaseUrl()); - String tokenString = uluut.toTokenString(); // p_cookie_peerとして、ランダムなUUIDを設定する String dcCookiePeer = UUID.randomUUID().toString(); - String cookieValue = dcCookiePeer + "\t" + tokenString; // ヘッダに返却するdc-cookie値は、暗号化する - String encodedCookieValue = LocalToken.encode(cookieValue, - UnitLocalUnitUserToken.getIvBytes(AccessContext.getCookieCryptKey(uriInfo.getBaseUri().getHost()))); + String encodedCookieValue = uluut.getCookieString(dcCookiePeer, + AccessContext.getCookieCryptKey(uriInfo.getBaseUri().getHost())); // 第1引数は AuthHeader, 第2引数は UriInfo, 第3引数は cookie_peer, 第4引数は cookie内の暗号化されたトークン情報 AccessContext accessContext = AccessContext.create(null, uriInfo, dcCookiePeer, encodedCookieValue, @@ -275,27 +273,30 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { Cell cell = (Cell) mock(Cell.class); when(cell.authenticateAccount((OEntityWrapper) Matchers.any(), Matchers.anyString())).thenReturn(true); - when(cell.getOwner()).thenReturn("cellowner"); + when(cell.getOwnerNormalized()).thenReturn("cellowner"); when(cell.getUrl()).thenReturn(UrlUtils.getBaseUrl() + "/cellowner"); when(cell.getUnitUrl()).thenReturn(UrlUtils.getBaseUrl()); // Token発行処理 - CellLocalAccessToken token = new CellLocalAccessToken( - UrlUtils.getBaseUrl() + "/cellowner", cell.getOwner(), null, - UrlUtils.getBaseUrl() + "/cellowner"); + VisitorLocalAccessToken token = new VisitorLocalAccessToken( + new Date().getTime(), + VisitorLocalAccessToken.ACCESS_TOKEN_EXPIRES_MILLISECS, + UrlUtils.getBaseUrl() + "/cellowner", + cell.getOwnerNormalized(), + null, + UrlUtils.getBaseUrl() + "/cellowner", + new String[] {"scope"}); - String tokenString = token.toTokenString(); // p_cookie_peerとして、ランダムなUUIDを設定する String dcCookiePeer = UUID.randomUUID().toString(); - String cookieValue = dcCookiePeer + "\t" + tokenString; // ヘッダに返却するdc-cookie値は、暗号化する - String encodedCookieValue = LocalToken.encode(cookieValue, - UnitLocalUnitUserToken.getIvBytes(AccessContext.getCookieCryptKey(uriInfo.getBaseUri().getHost()))); + String encodedCookieValue = token.getCookieString(dcCookiePeer, + AccessContext.getCookieCryptKey(uriInfo.getBaseUri().getHost())); // 第1引数は AuthHeader, 第2引数は UriInfo, 第3引数は cookie_peer, 第4引数は cookie内の暗号化されたトークン情報 AccessContext accessContext = AccessContext.create(null, uriInfo, dcCookiePeer, encodedCookieValue, cell, BASE_URL, UrlUtils.getHost(), OWNER); - assertEquals(AccessContext.TYPE_LOCAL, accessContext.getType()); + assertEquals(AccessContext.TYPE_VISITOR, accessContext.getType()); } /** @@ -305,28 +306,26 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { public void BASIC認証AuthorizationHeaderとcookie認証情報が同時に指定された場合のAccessContext生成の正常系テスト() { Cell cell = (Cell) mock(Cell.class); when(cell.authenticateAccount((OEntityWrapper) Matchers.any(), Matchers.anyString())).thenReturn(true); - when(cell.getOwner()).thenReturn("cellowner"); + when(cell.getOwnerNormalized()).thenReturn("cellowner"); UriInfo uriInfo = new TestUriInfo(); // uluut発行処理 UnitLocalUnitUserToken uluut = new UnitLocalUnitUserToken( System.currentTimeMillis(), UnitLocalUnitUserToken.ACCESS_TOKEN_EXPIRES_HOUR * MILLISECS_IN_AN_HOUR, - cell.getOwner(), uriInfo.getBaseUri().getHost() + ":" + uriInfo.getBaseUri().getPort()); + cell.getOwnerNormalized(), uriInfo.getBaseUri().getHost() + ":" + uriInfo.getBaseUri().getPort()); - String tokenString = uluut.toTokenString(); // p_cookie_peerとして、ランダムなUUIDを設定する - String dcCookiePeer = UUID.randomUUID().toString(); - String cookieValue = dcCookiePeer + "\t" + tokenString; + String pCookiePeer = UUID.randomUUID().toString(); // ヘッダに返却するdc-cookie値は、暗号化する - String encodedCookieValue = LocalToken.encode(cookieValue, - UnitLocalUnitUserToken.getIvBytes(AccessContext.getCookieCryptKey(uriInfo.getBaseUri().getHost()))); + String encodedCookieValue = uluut.getCookieString(pCookiePeer, + AccessContext.getCookieCryptKey(uriInfo.getBaseUri().getHost())); String basicAuth = "Basic " - + PersoniumCoreUtils.encodeBase64Url("user:pass".getBytes()); + + CommonUtils.encodeBase64Url("user:pass".getBytes()); // 第1引数は AuthHeader, 第2引数は UriInfo, 第3引数は cookie_peer, 第4引数は cookie内の暗号化されたトークン情報 - AccessContext accessContext = AccessContext.create(basicAuth, uriInfo, dcCookiePeer, encodedCookieValue, + AccessContext accessContext = AccessContext.create(basicAuth, uriInfo, pCookiePeer, encodedCookieValue, cell, BASE_URL, UrlUtils.getHost(), OWNER); assertEquals(AccessContext.TYPE_INVALID, accessContext.getType()); } @@ -339,27 +338,25 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { public void マスタトークン認証AuthorizationHeaderとcookie認証情報が同時に指定された場合のAccessContext生成の正常系テスト() { Cell cell = (Cell) mock(Cell.class); when(cell.authenticateAccount((OEntityWrapper) Matchers.any(), Matchers.anyString())).thenReturn(true); - when(cell.getOwner()).thenReturn("cellowner"); + when(cell.getOwnerNormalized()).thenReturn("cellowner"); UriInfo uriInfo = new TestUriInfo(); // uluut発行処理 UnitLocalUnitUserToken uluut = new UnitLocalUnitUserToken( System.currentTimeMillis(), UnitLocalUnitUserToken.ACCESS_TOKEN_EXPIRES_HOUR * MILLISECS_IN_AN_HOUR, - cell.getOwner(), uriInfo.getBaseUri().getHost() + ":" + uriInfo.getBaseUri().getPort()); + cell.getOwnerNormalized(), uriInfo.getBaseUri().getHost() + ":" + uriInfo.getBaseUri().getPort()); - String tokenString = uluut.toTokenString(); // p_cookie_peerとして、ランダムなUUIDを設定する - String dcCookiePeer = UUID.randomUUID().toString(); - String cookieValue = dcCookiePeer + "\t" + tokenString; - // ヘッダに返却するdc-cookie値は、暗号化する - String encodedCookieValue = LocalToken.encode(cookieValue, - UnitLocalUnitUserToken.getIvBytes(AccessContext.getCookieCryptKey(uriInfo.getBaseUri().getHost()))); + String pCookiePeer = UUID.randomUUID().toString(); + // ヘッダに返却するp-cookie値は、暗号化する + String encodedCookieValue = uluut.getCookieString(pCookiePeer, + AccessContext.getCookieCryptKey(uriInfo.getBaseUri().getHost())); String masterTokenAuth = "Bearer " + MASTER_TOKEN; // 第1引数は AuthHeader, 第2引数は UriInfo, 第3引数は cookie_peer, 第4引数は cookie内の暗号化されたトークン情報 - AccessContext accessContext = AccessContext.create(masterTokenAuth, uriInfo, dcCookiePeer, encodedCookieValue, + AccessContext accessContext = AccessContext.create(masterTokenAuth, uriInfo, pCookiePeer, encodedCookieValue, cell, BASE_URL, UrlUtils.getHost(), OWNER); assertEquals(AccessContext.TYPE_UNIT_MASTER, accessContext.getType()); } diff --git a/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java b/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java new file mode 100644 index 000000000..5223df44f --- /dev/null +++ b/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java @@ -0,0 +1,76 @@ +package io.personium.core.auth; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +import org.apache.commons.lang.StringUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import io.personium.core.model.Box; +import io.personium.core.model.Cell; + +public class ScopeArbitratorTest { + Cell mockCell = mock(Cell.class); + Box mockBox = mock(Box.class); + @BeforeClass + public static void setUpClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + doReturn("https://personium.example/").when(mockCell).getUnitUrl(); +// PersoniumUnitConfig mock = PowerMockito.spy(PersoniumUnitConfig.class); +// PowerMockito.when(PersoniumUnitConfig.class, "getTokenDefaultScopeRopc").thenReturn("root"); +// PowerMockito.doReturn("").when(PersoniumUnitConfig.class, "getTokenDefaultScopeCode"); +// PowerMockito.doReturn("root").when(PersoniumUnitConfig.class, "getTokenDefaultScopeAssertion"); + + } + + @After + public void tearDown() throws Exception { + this.mockCell = null; + this.mockBox = null; + } + + /** + * When constructed with ROPC option, then any Cell level priviledge can be allowed. + */ + @Test + public void When_ROPC_Then_CellLevelPrivileges_CanBeAllowed () { + ScopeArbitrator sa = new ScopeArbitrator(this.mockCell, this.mockBox, OAuth2Helper.GrantType.PASSWORD); + sa.unitMaxScopePrivilege = Privilege.get(CellPrivilege.class, "root"); + sa.requestString("openid root root message foo https://personium.example/__role/__/someRole"); + String[] res = sa.getResults(); + System.out.println(StringUtils.join(sa.requestedScopes, " ")); + System.out.println(StringUtils.join(res, " ")); + assertEquals(3, res.length); + } + /** + * When constructed with ROPC option and no scope requested, then root is granted. + */ + @Test + public void When_ROPC_noScopeRequest_Then_RootGranted () { + ScopeArbitrator sa = new ScopeArbitrator(this.mockCell, this.mockBox, OAuth2Helper.GrantType.PASSWORD); + sa.unitMaxScopePrivilege = Privilege.get(CellPrivilege.class, "root"); + sa.requestString(null); + String[] res = sa.getResults(); + assertEquals("root", res[0]); + } + + /** + * When constructed with non-ROPC option, then any Cell level priviledge can not be allowed. + */ + @Test + public void When_NotROPC_Then_CellLevelPrivileges_CanNotBeAllowed () { + + ScopeArbitrator sa = new ScopeArbitrator(this.mockCell, this.mockBox, OAuth2Helper.GrantType.AUTHORIZATION_CODE); + sa.unitMaxScopePrivilege = Privilege.get(CellPrivilege.class, ""); + sa.requestString("root message-read"); + String[] res = sa.getResults(); + assertEquals(0, res.length); + } +} diff --git a/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java b/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java index fb889151c..287802827 100644 --- a/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java +++ b/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java @@ -64,7 +64,7 @@ public void checkAccessContext_Normal_unit_user_token() { Privilege privilege = null; // Mock settings - boxUrlRsCmp = spy(new BoxUrlRsCmp(new CellRsCmp(null, null, null), null, null, null)); + boxUrlRsCmp = spy(new BoxUrlRsCmp(new CellRsCmp(null, null, ac), null, ac, null)); doReturn(AcceptableAuthScheme.BEARER).when(boxUrlRsCmp).getAcceptableAuthScheme(); doReturn(true).when(ac).isUnitUserToken(privilege); @@ -72,7 +72,7 @@ public void checkAccessContext_Normal_unit_user_token() { // None. // Run method - boxUrlRsCmp.checkAccessContext(ac, privilege); + boxUrlRsCmp.checkAccessContext(privilege); } /** @@ -88,7 +88,7 @@ public void checkAccessContext_Normal_match_box_schema() throws Exception { Privilege privilege = null; // Mock settings - boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, null), null, null, null)); + boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, ac), null, ac, null)); doReturn(AcceptableAuthScheme.BEARER).when(boxUrlRsCmp).getAcceptableAuthScheme(); doReturn(false).when(ac).isUnitUserToken(privilege); doReturn("testSchema").when(ac).getSchema(); @@ -98,7 +98,7 @@ public void checkAccessContext_Normal_match_box_schema() throws Exception { // None. // Run method - boxUrlRsCmp.checkAccessContext(ac, privilege); + boxUrlRsCmp.checkAccessContext(privilege); } /** @@ -114,7 +114,7 @@ public void checkAccessContext_Normal_has_privilege() throws Exception { Privilege privilege = null; // Mock settings - boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, null), null, null, null)); + boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, ac), null, ac, null)); doReturn(AcceptableAuthScheme.BEARER).when(boxUrlRsCmp).getAcceptableAuthScheme(); doReturn(false).when(ac).isUnitUserToken(privilege); @@ -127,13 +127,13 @@ public void checkAccessContext_Normal_has_privilege() throws Exception { doNothing().when(ac).updateBasicAuthenticationStateForResource(null); - doReturn(true).when(boxUrlRsCmp).hasPrivilege(ac, privilege); + doReturn(true).when(boxUrlRsCmp).hasSubjectPrivilege(privilege); // Expected result // None. // Run method - boxUrlRsCmp.checkAccessContext(ac, privilege); + boxUrlRsCmp.checkAccessContext(privilege); } /** @@ -150,7 +150,7 @@ public void checkAccessContext_Error_not_has_privilege_type_invalid() throws Exc Privilege privilege = null; // Mock settings - boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, null), null, null, null)); + boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, ac), null, ac, null)); doReturn(AcceptableAuthScheme.BEARER).when(boxUrlRsCmp).getAcceptableAuthScheme(); doReturn(false).when(ac).isUnitUserToken(privilege); @@ -163,7 +163,7 @@ public void checkAccessContext_Error_not_has_privilege_type_invalid() throws Exc doNothing().when(ac).updateBasicAuthenticationStateForResource(null); - doReturn(false).when(boxUrlRsCmp).hasPrivilege(ac, privilege); + doReturn(false).when(boxUrlRsCmp).hasSubjectPrivilege(privilege); doReturn(AccessContext.TYPE_INVALID).when(ac).getType(); doThrow(PersoniumCoreException.Server.UNKNOWN_ERROR).when(ac).throwInvalidTokenException( @@ -171,7 +171,7 @@ public void checkAccessContext_Error_not_has_privilege_type_invalid() throws Exc // Run method try { - boxUrlRsCmp.checkAccessContext(ac, privilege); + boxUrlRsCmp.checkAccessContext(privilege); fail("Not throws exception."); } catch (PersoniumCoreException e) { // Confirm result @@ -194,7 +194,7 @@ public void checkAccessContext_Error_not_has_privilege_type_anon() throws Except Privilege privilege = null; // Mock settings - boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, null), null, null, null)); + boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, ac), null, ac, null)); doReturn(AcceptableAuthScheme.BEARER).when(boxUrlRsCmp).getAcceptableAuthScheme(); doReturn(false).when(ac).isUnitUserToken(privilege); @@ -207,14 +207,14 @@ public void checkAccessContext_Error_not_has_privilege_type_anon() throws Except doNothing().when(ac).updateBasicAuthenticationStateForResource(null); - doReturn(false).when(boxUrlRsCmp).hasPrivilege(ac, privilege); + doReturn(false).when(boxUrlRsCmp).hasSubjectPrivilege(privilege); doReturn(AccessContext.TYPE_ANONYMOUS).when(ac).getType(); doReturn("https://personium/testcell").when(ac).getRealm(); // Run method try { - boxUrlRsCmp.checkAccessContext(ac, privilege); + boxUrlRsCmp.checkAccessContext(privilege); fail("Not throws exception."); } catch (PersoniumCoreException e) { // Confirm result @@ -239,7 +239,7 @@ public void checkAccessContext_Error_not_has_privilege_type_other() throws Excep Privilege privilege = null; // Mock settings - boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, null), null, null, null)); + boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, ac), null, ac, null)); doReturn(AcceptableAuthScheme.BEARER).when(boxUrlRsCmp).getAcceptableAuthScheme(); doReturn(false).when(ac).isUnitUserToken(privilege); @@ -252,13 +252,13 @@ public void checkAccessContext_Error_not_has_privilege_type_other() throws Excep doNothing().when(ac).updateBasicAuthenticationStateForResource(null); - doReturn(false).when(boxUrlRsCmp).hasPrivilege(ac, privilege); + doReturn(false).when(boxUrlRsCmp).hasSubjectPrivilege(privilege); - doReturn(AccessContext.TYPE_LOCAL).when(ac).getType(); + doReturn(AccessContext.TYPE_VISITOR).when(ac).getType(); // Run method try { - boxUrlRsCmp.checkAccessContext(ac, privilege); + boxUrlRsCmp.checkAccessContext(privilege); fail("Not throws exception."); } catch (PersoniumCoreException e) { // Confirm result diff --git a/src/test/java/io/personium/core/model/impl/es/odata/MessageODataProducerTest.java b/src/test/java/io/personium/core/model/impl/es/odata/MessageODataProducerTest.java index 7fd5a206d..afe293409 100644 --- a/src/test/java/io/personium/core/model/impl/es/odata/MessageODataProducerTest.java +++ b/src/test/java/io/personium/core/model/impl/es/odata/MessageODataProducerTest.java @@ -69,7 +69,7 @@ import io.personium.test.categories.Unit; /** - * MessageODataProducerユニットテストクラス. + * MessageODataProducer unit tests. */ @RunWith(PowerMockRunner.class) @PrepareForTest({ MessageODataProducer.class, Box.class, UriUtils.class }) @@ -820,7 +820,7 @@ public void getNameFromRequestRelation_Normal_requestRelation_is_classURL() thro PowerMockito.mockStatic(UriUtils.class); PowerMockito.doReturn("http://personium/dummyAppCell/__relation/__/dummyRelation").when( - UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation); + UriUtils.class, "convertSchemeFromLocalUnitToHttp", requestRelation); // -------------------- // Expected result @@ -862,7 +862,7 @@ public void getNameFromRequestRelation_Normal_requestRelation_is_name() throws E PowerMockito.mockStatic(UriUtils.class); PowerMockito.doReturn(requestRelation).when( - UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation); + UriUtils.class, "convertSchemeFromLocalUnitToHttp", requestRelation); // -------------------- // Expected result @@ -904,7 +904,7 @@ public void getBoxNameFromRequestRelation_Normal_requestRelation_is_classURL() t PowerMockito.mockStatic(UriUtils.class); PowerMockito.doReturn("http://personium/dummyAppCell/__relation/__/dummyRelation").when( - UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation); + UriUtils.class, "convertSchemeFromLocalUnitToHttp", requestRelation); Box mockBox = PowerMockito.mock(Box.class); doReturn("dummyBoxName").when(mockBox).getName(); @@ -950,7 +950,7 @@ public void getBoxNameFromRequestRelation_Normal_requestRelation_is_name() throw PowerMockito.mockStatic(UriUtils.class); PowerMockito.doReturn(requestRelation).when( - UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation); + UriUtils.class, "convertSchemeFromLocalUnitToHttp", requestRelation); // -------------------- // Expected result @@ -992,7 +992,7 @@ public void getBoxNameFromRequestRelation_Error_box_associated_with_classURL_doe PowerMockito.mockStatic(UriUtils.class); PowerMockito.doReturn("http://personium/dummyAppCell/__relation/__/dummyRelation").when( - UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation); + UriUtils.class, "convertSchemeFromLocalUnitToHttp", requestRelation); doReturn(null).when(mockCell).getBoxForSchema("http://personium/dummyAppCell/"); diff --git a/src/test/java/io/personium/core/model/impl/es/odata/UnitCtlODataProducerTest.java b/src/test/java/io/personium/core/model/impl/es/odata/UnitCtlODataProducerTest.java index f4be84980..a9d106c31 100644 --- a/src/test/java/io/personium/core/model/impl/es/odata/UnitCtlODataProducerTest.java +++ b/src/test/java/io/personium/core/model/impl/es/odata/UnitCtlODataProducerTest.java @@ -84,7 +84,7 @@ public void getImplicitFilters_Normal_type_unituser() throws Exception { doReturn("http://personiumunit/admincell/#admin").when(accessContext).getSubject(); PowerMockito.mockStatic(UriUtils.class); PowerMockito.doReturn("personium-localunit:/admincell/#admin").when(UriUtils.class, - "convertSchemeFromHttpToLocalUnit", "http://personiumunit/", "http://personiumunit/admincell/#admin"); + "convertSchemeFromHttpToLocalUnit", "http://personiumunit/admincell/#admin"); Map term1 = new HashMap<>(); Map term2 = new HashMap<>(); diff --git a/src/test/java/io/personium/core/model/impl/fs/DavCmpFsImplTest.java b/src/test/java/io/personium/core/model/impl/fs/DavCmpFsImplTest.java index ccb4d91cc..81ec22a0c 100644 --- a/src/test/java/io/personium/core/model/impl/fs/DavCmpFsImplTest.java +++ b/src/test/java/io/personium/core/model/impl/fs/DavCmpFsImplTest.java @@ -63,7 +63,7 @@ import org.powermock.reflect.Whitebox; import io.personium.common.es.EsClient; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; @@ -626,7 +626,7 @@ public void get_Normal_encrypt_false() throws Exception { ResponseBuilder expected = Response.ok().header(HttpHeaders.CONTENT_LENGTH, 98L) .header(HttpHeaders.CONTENT_TYPE, "text/plain") .header(ETAG, "\"1-1487652733383\"") - .header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); + .header(CommonUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); // -------------------- // Run method @@ -691,7 +691,7 @@ public void get_Normal_encrypt_true() throws Exception { ResponseBuilder expected = Response.ok().header(HttpHeaders.CONTENT_LENGTH, 98L) .header(HttpHeaders.CONTENT_TYPE, "text/plain") .header(ETAG, "\"1-1487652733383\"") - .header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); + .header(CommonUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); // -------------------- // Run method @@ -754,11 +754,11 @@ public void get_Normal_range_encrypt_false() throws Exception { // -------------------- String sourceFileMD5 = md5Hex(getSystemResourceAsStream("davFile/range01.txt")); ResponseBuilder expected = Response.status(HttpStatus.SC_PARTIAL_CONTENT) - .header(PersoniumCoreUtils.HttpHeaders.CONTENT_RANGE, "bytes 10-40/98") + .header(CommonUtils.HttpHeaders.CONTENT_RANGE, "bytes 10-40/98") .header(HttpHeaders.CONTENT_LENGTH, 31L) .header(HttpHeaders.CONTENT_TYPE, "text/plain") .header(ETAG, "\"1-1487652733383\"") - .header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); + .header(CommonUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); // -------------------- // Run method @@ -822,11 +822,11 @@ public void get_Normal_range_encrypt_true() throws Exception { // -------------------- String sourceFileMD5 = md5Hex(getSystemResourceAsStream("davFile/range01.txt")); ResponseBuilder expected = Response.status(HttpStatus.SC_PARTIAL_CONTENT) - .header(PersoniumCoreUtils.HttpHeaders.CONTENT_RANGE, "bytes 10-40/98") + .header(CommonUtils.HttpHeaders.CONTENT_RANGE, "bytes 10-40/98") .header(HttpHeaders.CONTENT_LENGTH, 31L) .header(HttpHeaders.CONTENT_TYPE, "text/plain") .header(ETAG, "\"1-1487652733383\"") - .header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); + .header(CommonUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); // -------------------- // Run method @@ -898,7 +898,7 @@ public void move_Normal_Dest_DavNode_not_exists() throws Exception { AccessContext accessContext = PowerMockito.mock(AccessContext.class); doReturn(accessContext).when(davRsCmp).getAccessContext(); doReturn(davRsCmp).when(davRsCmp).getParent(); - doNothing().when(davRsCmp).checkAccessContext(any(AccessContext.class), any(BoxPrivilege.class)); + doNothing().when(davRsCmp).checkAccessContext(any(BoxPrivilege.class)); doReturn(davRsCmp).when(davDestination).getDestinationRsCmp(); DavCmpFsImpl destDavCmp = PowerMockito.mock(DavCmpFsImpl.class); File destDir = mock(File.class); diff --git a/src/test/java/io/personium/core/model/jaxb/AclTest.java b/src/test/java/io/personium/core/model/jaxb/AclTest.java new file mode 100644 index 000000000..2da321cef --- /dev/null +++ b/src/test/java/io/personium/core/model/jaxb/AclTest.java @@ -0,0 +1,52 @@ +package io.personium.core.model.jaxb; + +import static org.junit.Assert.assertEquals; + +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.personium.common.auth.token.TransCellAccessToken; +import io.personium.core.PersoniumUnitConfig; +import io.personium.core.utils.UriUtils; + +public class AclTest { + private static Logger log = LoggerFactory.getLogger(AclTest.class); + + private static String unitUrl; + + + @BeforeClass + public static void beforeClass() throws Exception { + // Configure PersoniumUnitConfig's BaseUrl + TransCellAccessToken.configureX509(PersoniumUnitConfig.getX509PrivateKey(), + PersoniumUnitConfig.getX509Certificate(), PersoniumUnitConfig.getX509RootCertificate()); + unitUrl = PersoniumUnitConfig.getBaseUrl(); + } + + @Test + public void testGetSetBase_localUnitURL_shouldBeStoredUsing_localUnitScheme() throws Exception { + Acl acl = new Acl(); + String unitUrl = PersoniumUnitConfig.getBaseUrl(); + String mbUrl = unitUrl + "foo/__/"; + log.info("Configured Unit Url: " + unitUrl); + // --------------- + acl.setBase(mbUrl); + // --------------- + // URL Should be innternally + JSONObject j = (JSONObject) new JSONParser().parse(acl.toJSON()); + String baseVal = (String) j.get("@xml.base"); + log.info(j.toJSONString()); + log.info("base: " + baseVal); + // relativized using localunit scheme + assertEquals(UriUtils.convertSchemeFromHttpToLocalUnit(mbUrl), baseVal); + // --------------- + String retrievedUrl = acl.getBase(); + // --------------- + assertEquals(mbUrl, retrievedUrl); + } + +} diff --git a/src/test/java/io/personium/core/rs/box/BoxResourceTest.java b/src/test/java/io/personium/core/rs/box/BoxResourceTest.java index 146b5e089..43308ef0e 100644 --- a/src/test/java/io/personium/core/rs/box/BoxResourceTest.java +++ b/src/test/java/io/personium/core/rs/box/BoxResourceTest.java @@ -31,7 +31,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.model.Box; import io.personium.core.model.BoxCmp; @@ -93,7 +93,7 @@ public void recursiveDelete_Error_recursiveHeader_is_unexpected() throws Excepti } catch (PersoniumCoreException e) { // Confirm result PersoniumCoreException expected = PersoniumCoreException.Misc.PRECONDITION_FAILED.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); assertThat(e.getCode(), is(expected.getCode())); assertThat(e.getMessage(), is(expected.getMessage())); } @@ -123,7 +123,7 @@ public void recursiveDelete_Error_recursiveHeader_is_false() throws Exception { } catch (PersoniumCoreException e) { // Confirm result PersoniumCoreException expected = PersoniumCoreException.Misc.PRECONDITION_FAILED.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); assertThat(e.getCode(), is(expected.getCode())); assertThat(e.getMessage(), is(expected.getMessage())); } @@ -153,7 +153,7 @@ public void recursiveDelete_Error_recursiveHeader_is_null() throws Exception { } catch (PersoniumCoreException e) { // Confirm result PersoniumCoreException expected = PersoniumCoreException.Misc.PRECONDITION_FAILED.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); assertThat(e.getCode(), is(expected.getCode())); assertThat(e.getMessage(), is(expected.getMessage())); } diff --git a/src/test/java/io/personium/core/rs/box/DavCollectionResourceTest.java b/src/test/java/io/personium/core/rs/box/DavCollectionResourceTest.java index d3ba8ed13..6c26dae7c 100644 --- a/src/test/java/io/personium/core/rs/box/DavCollectionResourceTest.java +++ b/src/test/java/io/personium/core/rs/box/DavCollectionResourceTest.java @@ -32,7 +32,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.auth.AccessContext; import io.personium.core.model.DavCmp; @@ -73,7 +73,7 @@ public void delete_Error_recursiveHeader_is_unexpected() { } catch (PersoniumCoreException e) { // Confirm result PersoniumCoreException expected = PersoniumCoreException.Dav.INVALID_REQUEST_HEADER.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); assertThat(e.getCode(), is(expected.getCode())); assertThat(e.getMessage(), is(expected.getMessage())); } diff --git a/src/test/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResourceTest.java b/src/test/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResourceTest.java index dc58c3206..060791758 100644 --- a/src/test/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResourceTest.java +++ b/src/test/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResourceTest.java @@ -32,7 +32,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.auth.AccessContext; import io.personium.core.model.DavCmp; @@ -73,7 +73,7 @@ public void delete_Error_recursiveHeader_is_unexpected() { } catch (PersoniumCoreException e) { // Confirm result PersoniumCoreException expected = PersoniumCoreException.Dav.INVALID_REQUEST_HEADER.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); assertThat(e.getCode(), is(expected.getCode())); assertThat(e.getMessage(), is(expected.getMessage())); } diff --git a/src/test/java/io/personium/core/rs/cell/CellResourceTest.java b/src/test/java/io/personium/core/rs/cell/CellResourceTest.java index 5a96854f9..d323e0933 100644 --- a/src/test/java/io/personium/core/rs/cell/CellResourceTest.java +++ b/src/test/java/io/personium/core/rs/cell/CellResourceTest.java @@ -301,7 +301,7 @@ public void checkAccessContextForCellBulkDeletion_Error_type_local() throws Exce initCellResource(cell, cellCmp, cellRsCmp, accessContext); doNothing().when(accessContext).updateBasicAuthenticationStateForResource(null); - doReturn(AccessContext.TYPE_LOCAL).when(accessContext).getType(); + doReturn(AccessContext.TYPE_VISITOR).when(accessContext).getType(); // Expected result PersoniumCoreException expected = PersoniumCoreException.Auth.UNITUSER_ACCESS_REQUIRED; diff --git a/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java b/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java index bea2accbd..379d001b6 100644 --- a/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java +++ b/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java @@ -18,54 +18,185 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import static org.mockito.Matchers.anyList; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; +import java.io.ByteArrayInputStream; import java.lang.reflect.Method; +import java.net.URI; import java.util.ArrayList; import java.util.Date; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import javax.json.Json; +import javax.json.JsonObject; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import org.glassfish.grizzly.utils.Charsets; +import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.odata4j.core.OEntity; +import org.odata4j.core.OEntityKey; +import org.odata4j.core.OExtension; +import org.odata4j.core.OLink; +import org.odata4j.core.OProperties; +import org.odata4j.core.OProperty; +import org.odata4j.edm.EdmEntitySet; +import org.odata4j.edm.EdmEntityType; +import org.odata4j.edm.EdmType; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import io.personium.common.auth.token.AbstractOAuth2Token; -import io.personium.common.auth.token.CellLocalAccessToken; -import io.personium.common.auth.token.CellLocalRefreshToken; +import io.personium.common.auth.token.ResidentRefreshToken; import io.personium.common.auth.token.Role; -import io.personium.common.auth.token.TransCellRefreshToken; +import io.personium.common.auth.token.VisitorLocalAccessToken; +import io.personium.common.auth.token.VisitorRefreshToken; +import io.personium.core.PersoniumCoreAuthnException; +import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.Cell; +import io.personium.core.model.CellRsCmp; +import io.personium.core.model.ctl.Account; +import io.personium.core.odata.OEntityWrapper; +import io.personium.core.rs.PersoniumCoreApplication; import io.personium.test.categories.Unit; /** * TokenEndPointResource unit test classs. */ @RunWith(PowerMockRunner.class) -@PrepareForTest({ TokenEndPointResource.class, CellLocalRefreshToken.class, TransCellRefreshToken.class, +@PrepareForTest({ TokenEndPointResource.class, ResidentRefreshToken.class, VisitorRefreshToken.class, AbstractOAuth2Token.class }) @Category({ Unit.class }) +@PowerMockIgnore({"javax.crypto.*" }) public class TokenEndPointResourceTest { /** Target class of unit test. */ private TokenEndPointResource tokenEndPointResource; + private Cell mockCell; + private CellRsCmp mockCellRsCmp; + private UriInfo mockUriInfo; + + @BeforeClass + public static void beforeClass() { + PersoniumCoreApplication.loadConfig(); + PersoniumCoreApplication.loadPlugins(); + + } + @AfterClass + public static void afterClass() { + + } + /** * Before. + * @throws Exception */ @Before - public void befor() { - tokenEndPointResource = spy(new TokenEndPointResource(null, null)); + public void before() throws Exception { + String unitUrl = "https://personium/"; + String cellUrl = "https://personium/testcell/"; + + this.mockCellRsCmp = mock(CellRsCmp.class); + doReturn(null).when(this.mockCellRsCmp).getAccountsNotRecordingAuthHistory(); + doReturn(false).when(this.mockCellRsCmp).isRecordingAuthHistory(null, "username"); + + this.mockCell = Mockito.spy(Cell.class); + doReturn(unitUrl).when(this.mockCell).getUnitUrl(); + doReturn(cellUrl).when(this.mockCell).getUrl(); +// doReturn(null).when(this.mockCell). + Map o = new HashMap<>(); + o.put(Account.P_IP_ADDRESS_RANGE.getName(), null); + o.put(Account.P_TYPE.getName(), Account.P_TYPE.getDefaultValue()); + OEntity oe = new OEntity() { + EdmEntityType edmType = Account.EDM_TYPE_BUILDER.build(); + + @Override + public String getEntitySetName() { + return Account.EDM_TYPE_NAME; + } + + @Override + public OEntityKey getEntityKey() { + return OEntityKey.create(Account.P_NAME.getName(), "username"); + } + + @Override + public List> getProperties() { + Account.EDM_TYPE_BUILDER.build().getProperties(); + return null; + } + + @Override + public OProperty getProperty(String propName) { + String value = o.get(propName); + return OProperties.string(propName, value); + } + + @Override + public OProperty getProperty(String propName, Class propClass) { + return null; + } + + @Override + public EdmType getType() { + return this.edmType; + } + + @Override + public > TExtension findExtension(Class clazz) { + return null; + } + + @Override + public EdmEntitySet getEntitySet() { + return EdmEntitySet.newBuilder().setName("Account").build(); + } + + @Override + public EdmEntityType getEntityType() { + return Account.EDM_TYPE_BUILDER.build(); + } + + @Override + public List getLinks() { + // TODO 自動生成されたメソッド・スタブ + return null; + } + + @Override + public T getLink(String title, Class linkClass) { + return null; + } + + }; + OEntityWrapper oew = new OEntityWrapper(null, oe, "5678etag"); + doReturn(oew).when(this.mockCell).getAccount("username"); + doReturn(true).when(this.mockCell).authenticateAccount(oew, "password"); + + + this.tokenEndPointResource = PowerMockito.spy(new TokenEndPointResource(mockCell, this.mockCellRsCmp)); + this.mockUriInfo = mock(UriInfo.class); + doReturn(new URI(cellUrl)).when(this.mockUriInfo).getBaseUri(); + } /** @@ -76,9 +207,6 @@ public void befor() { @SuppressWarnings("unchecked") @Test public void receiveRefresh_Normal_cell_local_token() throws Exception { - Cell mockCell = mock(Cell.class); - tokenEndPointResource = PowerMockito.spy(new TokenEndPointResource(mockCell, null)); - // -------------------- // Test method args // -------------------- @@ -92,16 +220,15 @@ public void receiveRefresh_Normal_cell_local_token() throws Exception { // -------------------- // Mock settings // -------------------- - PowerMockito.doReturn(cellUrl).when(tokenEndPointResource, "getIssuerUrl"); - doReturn(host).when(mockCell).getUnitUrl(); - CellLocalRefreshToken mockOldRToken = PowerMockito.mock(CellLocalRefreshToken.class); + ResidentRefreshToken mockOldRToken = PowerMockito.mock(ResidentRefreshToken.class); PowerMockito.mockStatic(AbstractOAuth2Token.class); PowerMockito.when(AbstractOAuth2Token.class, "parse", refreshToken, cellUrl, host).thenReturn(mockOldRToken); PowerMockito.doReturn(false).when(mockOldRToken).isRefreshExpired(); + PowerMockito.doReturn(schema).when(mockOldRToken).getSchema(); - CellLocalRefreshToken mockNewRToken = PowerMockito.mock(CellLocalRefreshToken.class); + ResidentRefreshToken mockNewRToken = PowerMockito.mock(ResidentRefreshToken.class); doReturn(mockNewRToken).when(mockOldRToken).refreshRefreshToken(anyLong(), anyLong()); PowerMockito.doReturn("subject").when(mockNewRToken).getSubject(); @@ -109,9 +236,9 @@ public void receiveRefresh_Normal_cell_local_token() throws Exception { List roleList = new ArrayList(); doReturn(roleList).when(mockCell).getRoleListForAccount("subject"); - CellLocalAccessToken mockNewAToken = mock(CellLocalAccessToken.class); + VisitorLocalAccessToken mockNewAToken = mock(VisitorLocalAccessToken.class); PowerMockito.doReturn(mockNewAToken).when(mockNewRToken).refreshAccessToken( - anyLong(), anyLong(), anyString(), anyString(), anyList(), anyString()); + anyLong(), anyLong(), anyString(), anyString(), anyList()); Response response = Response.ok().build(); PowerMockito.doReturn(response).when(tokenEndPointResource, "responseAuthSuccess", @@ -148,9 +275,6 @@ public void receiveRefresh_Normal_cell_local_token() throws Exception { @SuppressWarnings("unchecked") @Test public void receiveRefresh_Normal_trans_cell_access_token() throws Exception { - Cell mockCell = mock(Cell.class); - tokenEndPointResource = PowerMockito.spy(new TokenEndPointResource(mockCell, null)); - // -------------------- // Test method args // -------------------- @@ -164,24 +288,23 @@ public void receiveRefresh_Normal_trans_cell_access_token() throws Exception { // -------------------- // Mock settings // -------------------- - PowerMockito.doReturn(cellUrl).when(tokenEndPointResource, "getIssuerUrl"); - doReturn(host).when(mockCell).getUnitUrl(); - TransCellRefreshToken mockOldRToken = PowerMockito.mock(TransCellRefreshToken.class); + VisitorRefreshToken mockOldRToken = PowerMockito.mock(VisitorRefreshToken.class); PowerMockito.mockStatic(AbstractOAuth2Token.class); PowerMockito.when(AbstractOAuth2Token.class, "parse", refreshToken, cellUrl, host).thenReturn(mockOldRToken); PowerMockito.doReturn(false).when(mockOldRToken).isRefreshExpired(); + PowerMockito.doReturn(schema).when(mockOldRToken).getSchema(); - TransCellRefreshToken mockNewRToken = PowerMockito.mock(TransCellRefreshToken.class); + VisitorRefreshToken mockNewRToken = PowerMockito.mock(VisitorRefreshToken.class); doReturn(mockNewRToken).when(mockOldRToken).refreshRefreshToken(anyLong(), anyLong()); List roleList = new ArrayList(); doReturn(roleList).when(mockCell).getRoleListHere(mockNewRToken); - CellLocalAccessToken mockNewAToken = mock(CellLocalAccessToken.class); + VisitorLocalAccessToken mockNewAToken = mock(VisitorLocalAccessToken.class); PowerMockito.doReturn(mockNewAToken).when(mockNewRToken).refreshAccessToken( - anyLong(), anyLong(), anyString(), anyString(), anyList(), anyString()); + anyLong(), anyLong(), anyString(), anyString(), anyList()); Response response = Response.ok().build(); PowerMockito.doReturn(response).when(tokenEndPointResource, "responseAuthSuccess", @@ -209,4 +332,100 @@ public void receiveRefresh_Normal_trans_cell_access_token() throws Exception { // -------------------- assertThat(actual.getStatus(), is(expected.getStatus())); } + + /** + * test for token() method with grant_type=password params setting. + * @throws Exception + */ + @Test + public void testToken_password() throws Exception { + String xForwadedFor = "1.2.3.4"; + + //PowerMockito.doReturn(cellUrl).when(tokenEndPointResource, "getIssuerUrl"); + MultivaluedMap formParams = new MultivaluedHashMap(); + formParams.add("grant_type", "password"); + formParams.add("username", "username"); + formParams.add("password", "password"); + formParams.add("scope", "root https://personium/appcell/"); + + + Response res = tokenEndPointResource.token(this.mockUriInfo, null, formParams, xForwadedFor); + JsonObject j = Json.createReader(new ByteArrayInputStream(res.getEntity().toString().getBytes(Charsets.UTF8_CHARSET))).readObject(); + assertEquals(200, res.getStatus()); + assertEquals("root", j.getString("scope")); + } + + /** + * test for token() method with invalid client_assertion_type. + * @throws Exception + */ + @Test + public void testToken_invalidClientAssertionType_shoudFail() throws Exception { + String xForwadedFor = "1.2.3.4"; + + //PowerMockito.doReturn(cellUrl).when(tokenEndPointResource, "getIssuerUrl"); + MultivaluedMap formParams = new MultivaluedHashMap(); + formParams.add("grant_type", "password"); + formParams.add("username", "username"); + formParams.add("password", "password"); + formParams.add("client_assertion_type", "invalid_client_assertion"); + formParams.add("scope", "root https://personium/appcell/"); + + try { + tokenEndPointResource.token(this.mockUriInfo, null, formParams, xForwadedFor); + } catch (PersoniumCoreAuthnException e) { + assertEquals(PersoniumCoreAuthnException.INVALID_CLIENT_ASSERTION_TYPE.getCode(), e.getCode()); + return; + } + fail("Should throw exception"); + } + + /** + * test for token() method with valid client_assertion_type and null client_assertion. + * @throws Exception + */ + @Test + public void testToken_nullClientAssertion_shouldFail() throws Exception { + String xForwadedFor = "1.2.3.4"; + + //PowerMockito.doReturn(cellUrl).when(tokenEndPointResource, "getIssuerUrl"); + MultivaluedMap formParams = new MultivaluedHashMap(); + formParams.add("grant_type", "password"); + formParams.add("username", "username"); + formParams.add("password", "password"); + formParams.add("client_assertion_type", OAuth2Helper.GrantType.SAML2_BEARER); + formParams.add("scope", "root https://personium/appcell/"); + + try { + tokenEndPointResource.token(this.mockUriInfo, null, formParams, xForwadedFor); + } catch (PersoniumCoreAuthnException e) { + assertEquals(PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getCode(), e.getCode()); + return; + } + fail("Should throw exception"); + } + /** + * test for token() method with null client_assertion_type and valid client_assertion. + * @throws Exception + */ + @Test + public void testToken_nullClientAssertionTypeAndValidClientAssertion_shouldFail() throws Exception { + String xForwadedFor = "1.2.3.4"; + + //PowerMockito.doReturn(cellUrl).when(tokenEndPointResource, "getIssuerUrl"); + MultivaluedMap formParams = new MultivaluedHashMap(); + formParams.add("grant_type", "password"); + formParams.add("username", "username"); + formParams.add("password", "password"); + formParams.add("client_assertion", "aa"); + formParams.add("scope", "root https://personium/appcell/"); + + try { + tokenEndPointResource.token(this.mockUriInfo, null, formParams, xForwadedFor); + } catch (PersoniumCoreAuthnException e) { + assertEquals(PersoniumCoreAuthnException.INVALID_CLIENT_ASSERTION_TYPE.getCode(), e.getCode()); + return; + } + fail("Should throw exception"); + } } diff --git a/src/test/java/io/personium/core/rs/unit/UnitCtlResourceTest.java b/src/test/java/io/personium/core/rs/unit/UnitCtlResourceTest.java index 02c3097dc..320dda11d 100644 --- a/src/test/java/io/personium/core/rs/unit/UnitCtlResourceTest.java +++ b/src/test/java/io/personium/core/rs/unit/UnitCtlResourceTest.java @@ -87,7 +87,7 @@ public void beforeCreate_Normal_type_unituser_subject_not_null() throws Exceptio doReturn("http://personiumunit/").when(accessContext).getBaseUri(); PowerMockito.mockStatic(UriUtils.class); PowerMockito.doReturn("personium-localunit:/admincell/#admin").when(UriUtils.class, - "convertSchemeFromHttpToLocalUnit", "http://personiumunit/", "http://personiumunit/admincell/#admin"); + "convertSchemeFromHttpToLocalUnit", "http://personiumunit/admincell/#admin"); doNothing().when(oEntityWrapper).put("Owner", "personium-localunit:/admincell/#admin"); @@ -189,7 +189,7 @@ public void checkAccessContext_Normal_type_unitmaster() throws Exception { // None. // Run method - unitCtlResource.checkAccessContext(ac, privilege); + unitCtlResource.checkAccessContext(privilege); } /** @@ -219,7 +219,7 @@ public void checkAccessContext_Error_type_invalid() throws Exception { try { // Run method - unitCtlResource.checkAccessContext(ac, privilege); + unitCtlResource.checkAccessContext(privilege); fail("Not throws exception."); } catch (PersoniumCoreAuthzException e) { // Confirm result @@ -255,7 +255,7 @@ public void checkAccessContext_Error_type_anonymous() throws Exception { try { // Run method - unitCtlResource.checkAccessContext(ac, privilege); + unitCtlResource.checkAccessContext(privilege); fail("Not throws exception."); } catch (PersoniumCoreAuthzException e) { // Confirm result @@ -282,14 +282,14 @@ public void checkAccessContext_Error_type_local() throws Exception { doReturn(uri).when(uriInfo).getBaseUri(); unitCtlResource = spy(new UnitCtlResource(ac)); - doReturn(AccessContext.TYPE_LOCAL).when(ac).getType(); + doReturn(AccessContext.TYPE_VISITOR).when(ac).getType(); // Expected result PersoniumCoreException expected = PersoniumCoreException.Auth.UNITUSER_ACCESS_REQUIRED; try { // Run method - unitCtlResource.checkAccessContext(ac, privilege); + unitCtlResource.checkAccessContext(privilege); fail("Not throws exception."); } catch (PersoniumCoreException e) { // Confirm result @@ -323,7 +323,7 @@ public void checkAccessContextPerEntity_Normal_type_unitmaster() throws Exceptio doReturn("http://personiumunit/").when(ac).getBaseUri(); PowerMockito.mockStatic(UriUtils.class); PowerMockito.doReturn("http://personiumunit/admincell/#admin").when(UriUtils.class, - "convertSchemeFromLocalUnitToHttp", "http://personiumunit/", "personium-localunit:/admincell/#admin"); + "convertSchemeFromLocalUnitToHttp", "personium-localunit:/admincell/#admin"); doReturn(AccessContext.TYPE_UNIT_MASTER).when(ac).getType(); @@ -362,7 +362,7 @@ public void checkAccessContextPerEntity_Normal_type_unituser_owner_equal_subject doReturn("http://personiumunit/").when(ac).getBaseUri(); PowerMockito.mockStatic(UriUtils.class); PowerMockito.doReturn("http://personiumunit/admincell/#admin").when(UriUtils.class, - "convertSchemeFromLocalUnitToHttp", "http://personiumunit/", "personium-localunit:/admincell/#admin"); + "convertSchemeFromLocalUnitToHttp", "personium-localunit:/admincell/#admin"); doReturn(AccessContext.TYPE_UNIT_USER).when(ac).getType(); @@ -403,7 +403,7 @@ public void checkAccessContextPerEntity_Error_type_unituser_owner_not_equal_subj doReturn("http://personiumunit/").when(ac).getBaseUri(); PowerMockito.mockStatic(UriUtils.class); PowerMockito.doReturn("http://personiumunit/admincell/#admin").when(UriUtils.class, - "convertSchemeFromLocalUnitToHttp", "http://personiumunit/", "personium-localunit:/admincell/#admin"); + "convertSchemeFromLocalUnitToHttp", "personium-localunit:/admincell/#admin"); doReturn(AccessContext.TYPE_UNIT_USER).when(ac).getType(); diff --git a/src/test/java/io/personium/core/rule/action/ActionFactoryTest.java b/src/test/java/io/personium/core/rule/action/ActionFactoryTest.java index d026a2272..f04d4a555 100644 --- a/src/test/java/io/personium/core/rule/action/ActionFactoryTest.java +++ b/src/test/java/io/personium/core/rule/action/ActionFactoryTest.java @@ -62,7 +62,7 @@ public void createActionl_Normal_action_is_log() throws Exception { // Mock settings // -------------------- Cell cell = mock(Cell.class); - doReturn(owner).when(cell).getOwner(); + doReturn(owner).when(cell).getOwnerNormalized(); doReturn(cellId).when(cell).getId(); PowerMockito.spy(LoggerFactory.class); PowerMockito.doReturn(null).when(LoggerFactory.class, "getLogger", "io.personium.core.rule.action"); @@ -97,7 +97,7 @@ public void createActionl_Normal_action_is_log_info() throws Exception { // Mock settings // -------------------- Cell cell = mock(Cell.class); - doReturn(owner).when(cell).getOwner(); + doReturn(owner).when(cell).getOwnerNormalized(); doReturn(cellId).when(cell).getId(); PowerMockito.spy(LoggerFactory.class); PowerMockito.doReturn(null).when(LoggerFactory.class, "getLogger", "io.personium.core.rule.action"); @@ -132,7 +132,7 @@ public void createActionl_Normal_action_is_log_warn() throws Exception { // Mock settings // -------------------- Cell cell = mock(Cell.class); - doReturn(owner).when(cell).getOwner(); + doReturn(owner).when(cell).getOwnerNormalized(); doReturn(cellId).when(cell).getId(); PowerMockito.spy(LoggerFactory.class); PowerMockito.doReturn(null).when(LoggerFactory.class, "getLogger", "io.personium.core.rule.action"); @@ -167,7 +167,7 @@ public void createActionl_Normal_action_is_log_error() throws Exception { // Mock settings // -------------------- Cell cell = mock(Cell.class); - doReturn(owner).when(cell).getOwner(); + doReturn(owner).when(cell).getOwnerNormalized(); doReturn(cellId).when(cell).getId(); PowerMockito.spy(LoggerFactory.class); PowerMockito.doReturn(null).when(LoggerFactory.class, "getLogger", "io.personium.core.rule.action"); @@ -202,7 +202,7 @@ public void createActionl_Normal_action_is_log_debug() throws Exception { // Mock settings // -------------------- Cell cell = mock(Cell.class); - doReturn(owner).when(cell).getOwner(); + doReturn(owner).when(cell).getOwnerNormalized(); doReturn(cellId).when(cell).getId(); PowerMockito.spy(LoggerFactory.class); PowerMockito.doReturn(null).when(LoggerFactory.class, "getLogger", "io.personium.core.rule.action"); diff --git a/src/test/java/io/personium/core/utils/UriUtilsTest.java b/src/test/java/io/personium/core/utils/UriUtilsTest.java index 4d81478e0..c5ce8e913 100644 --- a/src/test/java/io/personium/core/utils/UriUtilsTest.java +++ b/src/test/java/io/personium/core/utils/UriUtilsTest.java @@ -18,16 +18,16 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertNull; - -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.test.categories.Unit; @@ -50,25 +50,40 @@ public void convertSchemeFromLocalUnitToHttp_Normal_pathBase() throws Exception PowerMockito.spy(PersoniumUnitConfig.class); PowerMockito.doReturn(true) .when(PersoniumUnitConfig.class, "isPathBasedCellUrlEnabled"); - PowerMockito.spy(UriUtils.class); - PowerMockito.doReturn("http://cell.host.domain/") - .when(UriUtils.class, "convertPathBaseToFqdnBase", "http://host.domain/cell/"); + PowerMockito.doReturn("https://host.domain/") + .when(PersoniumUnitConfig.class, "getBaseUrl"); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("http://host.domain/", - "personium-localunit:/cell/"), - is("http://host.domain/cell/")); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", - "personium-localunit:/cell/"), - is("https://host.domain/cell/")); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", - "personium-localunit:/cell/#account"), - is("https://host.domain/cell/#account")); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", - "personium-localunit:/cell/box"), - is("https://host.domain/cell/box")); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", - "personium-localunit:/cell/box/col/ent?$inlinecount=allpages"), - is("https://host.domain/cell/box/col/ent?$inlinecount=allpages")); + + // Single Colon + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp( + "personium-localunit:/cell/"), + is("https://host.domain/cell/")); + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp( + "personium-localunit:/cell/"), + is("https://host.domain/cell/")); + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp( + "personium-localunit:/cell/#account"), + is("https://host.domain/cell/#account")); + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp( + "personium-localunit:/cell/box"), + is("https://host.domain/cell/box")); + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp( + "personium-localunit:/cell/box/col/ent?$inlinecount=allpages"), + is("https://host.domain/cell/box/col/ent?$inlinecount=allpages")); + + // Double Colons + assertThat( + UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:"), + is("https://host.domain/cell/")); + assertThat( + UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:"), + is("https://host.domain/cell/")); + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:#account"), + is("https://host.domain/cell/#account")); + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:/box"), + is("https://host.domain/cell/box")); + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:/box/col/ent?$inlinecount=allpages"), + is("https://host.domain/cell/box/col/ent?$inlinecount=allpages")); } /** @@ -81,28 +96,35 @@ public void convertSchemeFromLocalUnitToHttp_Normal_pathBase() throws Exception public void convertSchemeFromLocalUnitToHttp_Normal_fqdnBase() throws Exception { PowerMockito.spy(PersoniumUnitConfig.class); PowerMockito.doReturn(false) - .when(PersoniumUnitConfig.class, "isPathBasedCellUrlEnabled"); - PowerMockito.spy(UriUtils.class); - PowerMockito.doReturn("http://cell.host.domain/") - .when(UriUtils.class, "convertPathBaseToFqdnBase", "http://host.domain/cell/"); - PowerMockito.doReturn("https://cell.host.domain/") - .when(UriUtils.class, "convertPathBaseToFqdnBase", "https://host.domain/cell/"); + .when(PersoniumUnitConfig.class, "isPathBasedCellUrlEnabled"); + PowerMockito.doReturn("https://host.domain/") + .when(PersoniumUnitConfig.class, "getBaseUrl"); + + // Single Colon + assertThat( + UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:/cell/"), + is("https://cell.host.domain/")); + assertThat( + UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:/cell/"), + is("https://cell.host.domain/")); + assertThat( + UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:/cell/#account"), + is("https://cell.host.domain/#account")); + assertThat( + UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:/cell/box"), + is("https://cell.host.domain/box")); + assertThat( + UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:/cell/box/col/ent?$inlinecount=allpages"), + is("https://cell.host.domain/box/col/ent?$inlinecount=allpages")); + + // Double Colons + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:"), + is("https://cell.host.domain/")); + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:"), + is("https://cell.host.domain/")); + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:#account"), + is("https://cell.host.domain/#account")); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("http://host.domain/", - "personium-localunit:/cell/"), - is("http://cell.host.domain/")); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", - "personium-localunit:/cell/"), - is("https://cell.host.domain/")); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", - "personium-localunit:/cell/#account"), - is("https://cell.host.domain/#account")); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", - "personium-localunit:/cell/box"), - is("https://cell.host.domain/box")); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", - "personium-localunit:/cell/box/col/ent?$inlinecount=allpages"), - is("https://cell.host.domain/box/col/ent?$inlinecount=allpages")); } /** @@ -113,12 +135,14 @@ public void convertSchemeFromLocalUnitToHttp_Normal_fqdnBase() throws Exception */ @Test public void convertSchemeFromHttpToLocalUnit_Normal_url_starts_with_uniturl() throws Exception { - PowerMockito.spy(UriUtils.class); - PowerMockito.doReturn("http://host/host/cell/") - .when(UriUtils.class, "convertFqdnBaseToPathBase", "http://host/cell/"); - String actual = UriUtils.convertSchemeFromHttpToLocalUnit("http://host/", - "http://host/cell/"); - assertThat(actual, is("personium-localunit:/cell/")); + PowerMockito.spy(PersoniumUnitConfig.class); + PowerMockito.doReturn(false) + .when(PersoniumUnitConfig.class, "isPathBasedCellUrlEnabled"); + PowerMockito.doReturn("https://unit.example/") + .when(PersoniumUnitConfig.class, "getBaseUrl"); + assertThat( + UriUtils.convertSchemeFromHttpToLocalUnit("https://unit.example/cell/"), + is("personium-localunit:/cell/")); } /** @@ -129,12 +153,31 @@ public void convertSchemeFromHttpToLocalUnit_Normal_url_starts_with_uniturl() th */ @Test public void convertSchemeFromHttpToLocalUnit_Normal_url_is_fqdn_base() throws Exception { - PowerMockito.spy(UriUtils.class); - PowerMockito.doReturn("http://host.domain/cell/") - .when(UriUtils.class, "convertFqdnBaseToPathBase", "http://cell.host.domain/"); - String actual = UriUtils.convertSchemeFromHttpToLocalUnit("http://host.domain/", - "http://cell.host.domain/"); - assertThat(actual, is("personium-localunit:/cell/")); + PowerMockito.spy(PersoniumUnitConfig.class); + PowerMockito.doReturn(false) + .when(PersoniumUnitConfig.class, "isPathBasedCellUrlEnabled"); + PowerMockito.doReturn("http://unit.example/") + .when(PersoniumUnitConfig.class, "getBaseUrl"); + assertThat( + UriUtils.convertSchemeFromHttpToLocalUnit("http://cell.unit.example/"), + is("personium-localunit:cell:/")); + } + /** + * Test convertSchemeFromHttpToLocalUnit(). + * normal. + * url is path base. + * @throws Exception exception occurred in some errors + */ + @Test + public void convertSchemeFromHttpToLocalUnit_Normal_url_is_path_base() throws Exception { + PowerMockito.spy(PersoniumUnitConfig.class); + PowerMockito.doReturn(true) + .when(PersoniumUnitConfig.class, "isPathBasedCellUrlEnabled"); + PowerMockito.doReturn("http://unit.example/") + .when(PersoniumUnitConfig.class, "getBaseUrl"); + assertThat( + UriUtils.convertSchemeFromHttpToLocalUnit("http://unit.example/cell/"), + is("personium-localunit:cell:/")); } /** @@ -145,12 +188,13 @@ public void convertSchemeFromHttpToLocalUnit_Normal_url_is_fqdn_base() throws Ex */ @Test public void convertSchemeFromHttpToLocalUnit_Normal_url_not_starts_with_uniturl() throws Exception { - PowerMockito.spy(UriUtils.class); - PowerMockito.doReturn("http://otherdomain/otherhost/cell/") - .when(UriUtils.class, "convertFqdnBaseToPathBase", "http://otherhost.otherdomain/cell/"); - String actual = UriUtils.convertSchemeFromHttpToLocalUnit("http://host.domain/", - "http://otherhost.otherdomain/cell/"); - assertThat(actual, is("http://otherhost.otherdomain/cell/")); + PowerMockito.spy(PersoniumUnitConfig.class); + PowerMockito.doReturn("http://unit.example/") + .when(PersoniumUnitConfig.class, "getBaseUrl"); + + assertThat( + UriUtils.convertSchemeFromHttpToLocalUnit("http://otherhost.otherdomain/cell/"), + is("http://otherhost.otherdomain/cell/")); } /** @@ -161,8 +205,12 @@ public void convertSchemeFromHttpToLocalUnit_Normal_url_not_starts_with_uniturl( */ @Test public void convertSchemeFromHttpToLocalUnit_Normal_url_is_null() throws Exception { - String actual = UriUtils.convertSchemeFromHttpToLocalUnit("http://host.domain/", null); - assertNull(actual); + try { + UriUtils.convertSchemeFromHttpToLocalUnit(null); + } catch(PersoniumCoreException e) { + assertEquals(e.getCode(), "PR500-CM-0003"); + + } } /** @@ -173,8 +221,7 @@ public void convertSchemeFromHttpToLocalUnit_Normal_url_is_null() throws Excepti */ @Test public void convertSchemeFromHttpToLocalUnit_Normal_url_is_invalid() throws Exception { - String actual = UriUtils.convertSchemeFromHttpToLocalUnit("http://host.domain/", "hoge"); - assertThat(actual, is("hoge")); + assertThat(UriUtils.convertSchemeFromHttpToLocalUnit("hoge"), is("hoge")); } /** diff --git a/src/test/java/io/personium/test/jersey/CrossDomainTest.java b/src/test/java/io/personium/test/jersey/CrossDomainTest.java index ef16e0e31..8c0d13cc4 100644 --- a/src/test/java/io/personium/test/jersey/CrossDomainTest.java +++ b/src/test/java/io/personium/test/jersey/CrossDomainTest.java @@ -27,7 +27,7 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; -import io.personium.common.utils.PersoniumCoreUtils.HttpHeaders; +import io.personium.common.utils.CommonUtils.HttpHeaders; import io.personium.core.PersoniumUnitConfig; import io.personium.core.model.ctl.ReceivedMessage; import io.personium.core.model.ctl.SentMessage; diff --git a/src/test/java/io/personium/test/jersey/PersoniumRequest.java b/src/test/java/io/personium/test/jersey/PersoniumRequest.java index 1a5589044..b7ee9d14a 100644 --- a/src/test/java/io/personium/test/jersey/PersoniumRequest.java +++ b/src/test/java/io/personium/test/jersey/PersoniumRequest.java @@ -108,7 +108,7 @@ public static PersoniumRequest delete(String url) { */ public static PersoniumRequest move(String url) { PersoniumRequest req = new PersoniumRequest(url); - req.method = io.personium.common.utils.PersoniumCoreUtils.HttpMethod.MOVE; + req.method = io.personium.common.utils.CommonUtils.HttpMethod.MOVE; return req; } diff --git a/src/test/java/io/personium/test/jersey/bar/BarInstallTest.java b/src/test/java/io/personium/test/jersey/bar/BarInstallTest.java index 2b9a21629..c2e0e9f60 100644 --- a/src/test/java/io/personium/test/jersey/bar/BarInstallTest.java +++ b/src/test/java/io/personium/test/jersey/bar/BarInstallTest.java @@ -41,7 +41,7 @@ import org.slf4j.LoggerFactory; import org.w3c.dom.Element; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.Box; @@ -173,7 +173,7 @@ private static void cleanup() { String reqCell = Setup.TEST_CELL1; try { // Delete link. - String extRole = PersoniumCoreUtils.encodeUrlComp("https://fqdn/cellname/__role/__/role2"); + String extRole = CommonUtils.encodeUrlComp("https://fqdn/cellname/__role/__/role2"); String key = "Name='role1',_Box.Name='" + INSTALL_TARGET + "'"; String navKey = "ExtRole='" + extRole + "'" + ",_Relation.Name='relation1',_Relation._Box.Name='" + INSTALL_TARGET + "'"; @@ -195,7 +195,7 @@ private static void cleanup() { try { // Delete ExtRole. - String extRole = PersoniumCoreUtils.encodeUrlComp("https://fqdn/cellname/__role/__/role2"); + String extRole = CommonUtils.encodeUrlComp("https://fqdn/cellname/__role/__/role2"); Http.request("cell/extRole/extRole-delete.txt") .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL1) @@ -336,7 +336,7 @@ private static void cleanup() { @Test public final void メインボックスに対してbarインストールすると405エラーとなること() { String reqCell = Setup.TEST_CELL1; - String reqPath = Box.DEFAULT_BOX_NAME; + String reqPath = Box.MAIN_BOX_NAME; TResponse res = null; File barFile = new File(RESOURCE_PATH + BAR_FILE_MINIMUM); @@ -646,7 +646,7 @@ private void deleteAllData(final String reqCell, "Name='relation1',_Box.Name='" + INSTALL_TARGET + "'", Role.EDM_TYPE_NAME, role1, AbstractCase.MASTER_TOKEN_NAME, -1); // Role <--> ExtRole - String extRole = PersoniumCoreUtils.encodeUrlComp("https://fqdn/cellname/__role/__/role2"); + String extRole = CommonUtils.encodeUrlComp("https://fqdn/cellname/__role/__/role2"); LinksUtils.deleteLinks(Setup.TEST_CELL1, Role.EDM_TYPE_NAME, role1, ExtRole.EDM_TYPE_NAME, "ExtRole='" + extRole + "'" + ",_Relation.Name='relation1',_Relation._Box.Name='" + INSTALL_TARGET + "'", diff --git a/src/test/java/io/personium/test/jersey/box/CollectionTest.java b/src/test/java/io/personium/test/jersey/box/CollectionTest.java index d275d8144..28e2b7d95 100644 --- a/src/test/java/io/personium/test/jersey/box/CollectionTest.java +++ b/src/test/java/io/personium/test/jersey/box/CollectionTest.java @@ -42,7 +42,7 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.model.Box; import io.personium.core.model.ctl.Account; @@ -768,7 +768,7 @@ public void error_delete_OData_collection_recursive_header_error() { // Confirm results PersoniumCoreException expected = PersoniumCoreException.Dav.INVALID_REQUEST_HEADER.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, "dummy"); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, "dummy"); JSONObject bodyJson = response.bodyAsJson(); JSONObject messageJson = (JSONObject) bodyJson.get("message"); assertThat(bodyJson.get("code"), is(expected.getCode())); @@ -823,7 +823,7 @@ public void error_delete_WebDAV_collection_recursive_header_error() { // Confirm results PersoniumCoreException expected = PersoniumCoreException.Dav.INVALID_REQUEST_HEADER.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, "dummy"); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, "dummy"); JSONObject bodyJson = response.bodyAsJson(); JSONObject messageJson = (JSONObject) bodyJson.get("message"); assertThat(bodyJson.get("code"), is(expected.getCode())); @@ -878,7 +878,7 @@ public void error_delete_EngineService_collection_recursive_header_error() { // Confirm results PersoniumCoreException expected = PersoniumCoreException.Dav.INVALID_REQUEST_HEADER.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, "dummy"); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, "dummy"); JSONObject bodyJson = response.bodyAsJson(); JSONObject messageJson = (JSONObject) bodyJson.get("message"); assertThat(bodyJson.get("code"), is(expected.getCode())); @@ -1482,13 +1482,13 @@ public final void WebDAV_ACL_test() { Map> map = new HashMap>(); rolList.add("read"); rolList.add("write"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role1"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role1"), rolList); list.add(map); rolList = new ArrayList(); map = new HashMap>(); rolList.add("read"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role2"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role2"), rolList); list.add(map); list.addAll(createDefaultBoxAceMapList()); @@ -1582,7 +1582,7 @@ public final void WebDAV_ACL_parent_authority_test() { Map> map = new HashMap>(); List rolList = new ArrayList(); rolList.add("write"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role1"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role1"), rolList); list.add(map); // top collection ace. @@ -1590,13 +1590,13 @@ public final void WebDAV_ACL_parent_authority_test() { map = new HashMap>(); rolList.add("read"); rolList.add("write"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role1"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role1"), rolList); list.add(map); rolList = new ArrayList(); map = new HashMap>(); rolList.add("read"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role2"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role2"), rolList); list.add(map); // box ace. @@ -1636,14 +1636,14 @@ protected List>> createDefaultBoxAceMapList() { List rolList = new ArrayList(); Map> map = new HashMap>(); rolList.add("read"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role2"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role2"), rolList); list.add(map); // role3 rolList = new ArrayList(); map = new HashMap>(); rolList.add("write"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role3"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role3"), rolList); list.add(map); // role4 @@ -1651,42 +1651,42 @@ protected List>> createDefaultBoxAceMapList() { map = new HashMap>(); rolList.add("read"); rolList.add("write"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role4"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role4"), rolList); list.add(map); // role5 rolList = new ArrayList(); map = new HashMap>(); rolList.add("exec"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role5"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role5"), rolList); list.add(map); // role6 rolList = new ArrayList(); map = new HashMap>(); rolList.add("read-acl"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role6"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role6"), rolList); list.add(map); // role7 rolList = new ArrayList(); map = new HashMap>(); rolList.add("write-acl"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role7"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role7"), rolList); list.add(map); // role8 rolList = new ArrayList(); map = new HashMap>(); rolList.add("write-properties"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role8"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role8"), rolList); list.add(map); // role9 rolList = new ArrayList(); map = new HashMap>(); rolList.add("read-properties"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role9"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role9"), rolList); list.add(map); return list; @@ -1722,7 +1722,7 @@ protected List>> createDefaultBoxAceMapList() { Map> map = new HashMap>(); List rolList = new ArrayList(); rolList.add("read"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role1"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role1"), rolList); list.add(map); list.addAll(createDefaultBoxAceMapList()); @@ -1777,7 +1777,7 @@ protected List>> createDefaultBoxAceMapList() { Map> map = new HashMap>(); List rolList = new ArrayList(); rolList.add("exec"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role1"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role1"), rolList); list.add(map); list.addAll(createDefaultBoxAceMapList()); @@ -1835,13 +1835,13 @@ protected List>> createDefaultBoxAceMapList() { List rolList = new ArrayList(); rolList.add("read"); rolList.add("write"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role1"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role1"), rolList); list.add(map); List rolList2 = new ArrayList(); Map> map2 = new HashMap>(); rolList2.add("read"); - map2.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role2"), rolList2); + map2.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role2"), rolList2); list.add(map2); list.addAll(createDefaultBoxAceMapList()); @@ -1989,13 +1989,13 @@ protected List>> createDefaultBoxAceMapList() { List rolList = new ArrayList(); rolList.add("read"); rolList.add("write"); - map.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role1"), rolList); + map.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role1"), rolList); list.add(map); List rolList2 = new ArrayList(); Map> map2 = new HashMap>(); rolList2.add("read"); - map2.put(UrlUtils.aclRelativePath(Box.DEFAULT_BOX_NAME, "role2"), rolList2); + map2.put(UrlUtils.aclRelativePath(Box.MAIN_BOX_NAME, "role2"), rolList2); list.add(map2); TestMethodUtils.aclResponseTest(root2, resorce, list, 1, diff --git a/src/test/java/io/personium/test/jersey/box/Property.java b/src/test/java/io/personium/test/jersey/box/Property.java index 44b403c20..19af08c0f 100644 --- a/src/test/java/io/personium/test/jersey/box/Property.java +++ b/src/test/java/io/personium/test/jersey/box/Property.java @@ -21,7 +21,7 @@ import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; /** * Propertyを扱うオブジェクト. @@ -81,7 +81,7 @@ Property setUnique(String uniq) { @XmlAttribute(name = "Precision") String precision; - @XmlAttribute(namespace = PersoniumCoreUtils.XmlConst.NS_PERSONIUM, name = "Unique") + @XmlAttribute(namespace = CommonUtils.XmlConst.NS_PERSONIUM, name = "Unique") String unique; @Override diff --git a/src/test/java/io/personium/test/jersey/box/acl/AclAlterSchemaTest.java b/src/test/java/io/personium/test/jersey/box/acl/AclAlterSchemaTest.java index f0e27d36b..ac22ddc89 100644 --- a/src/test/java/io/personium/test/jersey/box/acl/AclAlterSchemaTest.java +++ b/src/test/java/io/personium/test/jersey/box/acl/AclAlterSchemaTest.java @@ -916,7 +916,7 @@ private void createODataCollection() throws JAXBException { privileges.add("write"); privileges.add("alter-schema"); acl.getAce().add(DavResourceUtils.createAce(false, roleCombPrivilege, privileges)); - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, COL_NAME, acl, HttpStatus.SC_OK); diff --git a/src/test/java/io/personium/test/jersey/box/dav/col/MoveCollectionAccessControlTest.java b/src/test/java/io/personium/test/jersey/box/dav/col/MoveCollectionAccessControlTest.java index e528c9248..4a0cd31fd 100644 --- a/src/test/java/io/personium/test/jersey/box/dav/col/MoveCollectionAccessControlTest.java +++ b/src/test/java/io/personium/test/jersey/box/dav/col/MoveCollectionAccessControlTest.java @@ -1081,7 +1081,7 @@ private void setDefaultAcl(String collection) throws JAXBException { privileges.add("bind"); privileges.add("unbind"); acl.getAce().add(DavResourceUtils.createAce(false, ROLE_BIND_AND_UNBIND_PREVILEGE, privileges)); - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, collection, acl, HttpStatus.SC_OK); } @@ -1096,7 +1096,7 @@ private void setDefaultAcl(String collection) throws JAXBException { private void setAcl(String collection, String role, String privilege) throws JAXBException { Acl acl = new Acl(); acl.getAce().add(DavResourceUtils.createAce(false, role, privilege)); - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, collection, acl, HttpStatus.SC_OK); } diff --git a/src/test/java/io/personium/test/jersey/box/dav/col/MoveODataCollectionAclTest.java b/src/test/java/io/personium/test/jersey/box/dav/col/MoveODataCollectionAclTest.java index 9af557cd7..a69d0d159 100644 --- a/src/test/java/io/personium/test/jersey/box/dav/col/MoveODataCollectionAclTest.java +++ b/src/test/java/io/personium/test/jersey/box/dav/col/MoveODataCollectionAclTest.java @@ -678,7 +678,7 @@ private void setDefaultAcl(String collection) throws JAXBException { privileges.add("read"); privileges.add("write"); acl.getAce().add(DavResourceUtils.createAce(false, ROLE_COMB_PRIVILEGE, privileges)); - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, collection, acl, HttpStatus.SC_OK); } @@ -693,7 +693,7 @@ private void setDefaultAcl(String collection) throws JAXBException { private void setAcl(String collection, String role, String privilege) throws JAXBException { Acl acl = new Acl(); acl.getAce().add(DavResourceUtils.createAce(false, role, privilege)); - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, collection, acl, HttpStatus.SC_OK); } diff --git a/src/test/java/io/personium/test/jersey/box/dav/col/MoveServiceCollectionAclTest.java b/src/test/java/io/personium/test/jersey/box/dav/col/MoveServiceCollectionAclTest.java index 37c93e14e..0985e658f 100644 --- a/src/test/java/io/personium/test/jersey/box/dav/col/MoveServiceCollectionAclTest.java +++ b/src/test/java/io/personium/test/jersey/box/dav/col/MoveServiceCollectionAclTest.java @@ -677,7 +677,7 @@ private void setDefaultAcl(String collection) throws JAXBException { privileges.add("read"); privileges.add("write"); acl.getAce().add(DavResourceUtils.createAce(false, ROLE_COMB_PRIVILEGE, privileges)); - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, collection, acl, HttpStatus.SC_OK); } @@ -692,7 +692,7 @@ private void setDefaultAcl(String collection) throws JAXBException { private void setAcl(String collection, String role, String privilege) throws JAXBException { Acl acl = new Acl(); acl.getAce().add(DavResourceUtils.createAce(false, role, privilege)); - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, collection, acl, HttpStatus.SC_OK); } diff --git a/src/test/java/io/personium/test/jersey/box/dav/col/ODataCollectionAccessControlTest.java b/src/test/java/io/personium/test/jersey/box/dav/col/ODataCollectionAccessControlTest.java index 86101ffa9..5d9366161 100644 --- a/src/test/java/io/personium/test/jersey/box/dav/col/ODataCollectionAccessControlTest.java +++ b/src/test/java/io/personium/test/jersey/box/dav/col/ODataCollectionAccessControlTest.java @@ -745,7 +745,7 @@ private TResponse setAcl(String token, int code, String collection, String role, for (String privilege : privileges) { acl.getAce().add(DavResourceUtils.createAce(false, role, privilege)); } - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); return DavResourceUtils.setAcl(token, CELL_NAME, BOX_NAME, collection, acl, code); } diff --git a/src/test/java/io/personium/test/jersey/box/dav/col/ServiceCollectionAccessControlTest.java b/src/test/java/io/personium/test/jersey/box/dav/col/ServiceCollectionAccessControlTest.java index 281a1da44..6f050698a 100644 --- a/src/test/java/io/personium/test/jersey/box/dav/col/ServiceCollectionAccessControlTest.java +++ b/src/test/java/io/personium/test/jersey/box/dav/col/ServiceCollectionAccessControlTest.java @@ -811,7 +811,7 @@ private TResponse setAcl(String token, int code, String collection, String role, for (String privilege : privileges) { acl.getAce().add(DavResourceUtils.createAce(false, role, privilege)); } - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); return DavResourceUtils.setAcl(token, CELL_NAME, BOX_NAME, collection, acl, code); } diff --git a/src/test/java/io/personium/test/jersey/box/dav/col/WebDAVCollectionAccessControlTest.java b/src/test/java/io/personium/test/jersey/box/dav/col/WebDAVCollectionAccessControlTest.java index 930e71d2b..ab0b1b9c7 100644 --- a/src/test/java/io/personium/test/jersey/box/dav/col/WebDAVCollectionAccessControlTest.java +++ b/src/test/java/io/personium/test/jersey/box/dav/col/WebDAVCollectionAccessControlTest.java @@ -759,7 +759,7 @@ private TResponse setAcl(String token, int code, String collection, String role, for (String privilege : privileges) { acl.getAce().add(DavResourceUtils.createAce(false, role, privilege)); } - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); return DavResourceUtils.setAcl(token, CELL_NAME, BOX_NAME, collection, acl, code); } diff --git a/src/test/java/io/personium/test/jersey/box/dav/file/DavFileTest.java b/src/test/java/io/personium/test/jersey/box/dav/file/DavFileTest.java index ef573ab63..7538e683b 100644 --- a/src/test/java/io/personium/test/jersey/box/dav/file/DavFileTest.java +++ b/src/test/java/io/personium/test/jersey/box/dav/file/DavFileTest.java @@ -30,7 +30,7 @@ import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.core.PersoniumUnitConfig.BinaryData; import io.personium.core.rs.PersoniumCoreApplication; @@ -456,7 +456,7 @@ public final void returns_200_on_GET_with_invalid_value_in_IfNoneMatch_header() getResp.statusCode(HttpStatus.SC_PARTIAL_CONTENT); assertEquals(String.format("bytes %s-%s/%s", first, last, body.length()), - getResp.getHeader(PersoniumCoreUtils.HttpHeaders.CONTENT_RANGE)); + getResp.getHeader(CommonUtils.HttpHeaders.CONTENT_RANGE)); assertEquals(body.substring(first, last + 1), getResp.getBody()); } finally { diff --git a/src/test/java/io/personium/test/jersey/box/dav/file/FileAccessControlTest.java b/src/test/java/io/personium/test/jersey/box/dav/file/FileAccessControlTest.java index 021f99ca6..015beaa0b 100644 --- a/src/test/java/io/personium/test/jersey/box/dav/file/FileAccessControlTest.java +++ b/src/test/java/io/personium/test/jersey/box/dav/file/FileAccessControlTest.java @@ -1368,7 +1368,7 @@ private TResponse setAcl(String token, int code, String collection, String role, for (String privilege : privileges) { acl.getAce().add(DavResourceUtils.createAce(false, role, privilege)); } - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); return DavResourceUtils.setAcl(token, CELL_NAME, BOX_NAME, collection, acl, code); } diff --git a/src/test/java/io/personium/test/jersey/box/dav/file/MoveFileAccessControlTest.java b/src/test/java/io/personium/test/jersey/box/dav/file/MoveFileAccessControlTest.java index daefabc10..8b86db525 100644 --- a/src/test/java/io/personium/test/jersey/box/dav/file/MoveFileAccessControlTest.java +++ b/src/test/java/io/personium/test/jersey/box/dav/file/MoveFileAccessControlTest.java @@ -927,7 +927,7 @@ private void setDefaultAcl(String collection) throws JAXBException { privileges.add("bind"); privileges.add("unbind"); acl.getAce().add(DavResourceUtils.createAce(false, ROLE_BIND_AND_UNBIND_PREVILEGE, privileges)); - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, collection, acl, HttpStatus.SC_OK); } diff --git a/src/test/java/io/personium/test/jersey/box/dav/file/MoveServiceSourceAccessControlTest.java b/src/test/java/io/personium/test/jersey/box/dav/file/MoveServiceSourceAccessControlTest.java index ece644765..f53f16ef2 100644 --- a/src/test/java/io/personium/test/jersey/box/dav/file/MoveServiceSourceAccessControlTest.java +++ b/src/test/java/io/personium/test/jersey/box/dav/file/MoveServiceSourceAccessControlTest.java @@ -777,7 +777,7 @@ private void setDefaultAcl(String collection) throws JAXBException { privileges.add("read"); privileges.add("write"); acl.getAce().add(DavResourceUtils.createAce(false, ROLE_COMB_PRIVILEGE, privileges)); - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, collection, acl, HttpStatus.SC_OK); } diff --git a/src/test/java/io/personium/test/jersey/box/dav/file/ServiceSourceAccessControlTest.java b/src/test/java/io/personium/test/jersey/box/dav/file/ServiceSourceAccessControlTest.java index 3990fafad..794b6d65a 100644 --- a/src/test/java/io/personium/test/jersey/box/dav/file/ServiceSourceAccessControlTest.java +++ b/src/test/java/io/personium/test/jersey/box/dav/file/ServiceSourceAccessControlTest.java @@ -779,7 +779,7 @@ private TResponse setAcl(String token, int code, String collection, String role, for (String privilege : privileges) { acl.getAce().add(DavResourceUtils.createAce(false, role, privilege)); } - acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); + acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.MAIN_BOX_NAME)); return DavResourceUtils.setAcl(token, CELL_NAME, BOX_NAME, collection, acl, code); } diff --git a/src/test/java/io/personium/test/jersey/box/odatacol/AbstractUserDataTest.java b/src/test/java/io/personium/test/jersey/box/odatacol/AbstractUserDataTest.java index 2cc5bad0f..1704f2501 100644 --- a/src/test/java/io/personium/test/jersey/box/odatacol/AbstractUserDataTest.java +++ b/src/test/java/io/personium/test/jersey/box/odatacol/AbstractUserDataTest.java @@ -33,7 +33,7 @@ import org.json.simple.JSONObject; import org.odata4j.edm.EdmSimpleType; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.test.jersey.AbstractCase; import io.personium.test.jersey.ODataCommon; @@ -468,7 +468,7 @@ protected void deleteUserData(String cell, String box, String col, String entity .with("box", box) .with("collection", col) .with("entityType", entityType) - .with("id", PersoniumCoreUtils.encodeUrlComp(userDataId)) + .with("id", CommonUtils.encodeUrlComp(userDataId)) .with("token", token) .with("ifMatch", ifMatch) .returns() diff --git a/src/test/java/io/personium/test/jersey/cell/AclTest.java b/src/test/java/io/personium/test/jersey/cell/AclTest.java index fa264b02c..dcc3bdc69 100644 --- a/src/test/java/io/personium/test/jersey/cell/AclTest.java +++ b/src/test/java/io/personium/test/jersey/cell/AclTest.java @@ -27,20 +27,29 @@ import org.apache.http.HttpStatus; import org.json.simple.JSONArray; import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.Box; +import io.personium.core.model.Cell; +import io.personium.core.model.CellCmp; +import io.personium.core.model.ModelFactory; import io.personium.core.model.ctl.Account; import io.personium.core.model.ctl.ExtCell; import io.personium.core.model.ctl.Relation; import io.personium.core.model.ctl.Role; +import io.personium.core.model.jaxb.Acl; import io.personium.core.rs.PersoniumCoreApplication; +import io.personium.core.utils.UriUtils; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; @@ -68,7 +77,7 @@ import io.personium.test.utils.TestMethodUtils; /** - * CellレベルACLのテスト. + * Cell level ACL testing. */ @Category({Unit.class, Integration.class, Regression.class }) public class AclTest extends AbstractCase { @@ -78,8 +87,11 @@ public class AclTest extends AbstractCase { static final String TEST_ROLE2 = "role5"; static final String TOKEN = AbstractCase.MASTER_TOKEN_NAME; + private static Logger log = LoggerFactory.getLogger(AclTest.class); + + /** - * コンストラクタ. + * Constructor. */ public AclTest() { super(new PersoniumCoreApplication()); @@ -128,7 +140,7 @@ public AclTest() { sb.deleteCharAt(resorce.length() - 1); TestMethodUtils.aclResponseTest(root, sb.toString(), list, 1, - UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, ""), null); + UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, ""), null); } finally { // ACLの設定を元に戻す @@ -138,6 +150,38 @@ public AclTest() { .statusCode(HttpStatus.SC_OK); } } + /** + * Base URL of ACL is stored using localunit scheme whenever possible. + * @throws ParseException + */ + @Test + public final void baseUrlStoredUsingLocalUnitSchemeWheneverPossible() throws ParseException { + + try { + // Configure acl includng role4, role5 onto testcell1 + Http.request("cell/acl-setting-request.txt").with("url", TEST_CELL1).with("token", TOKEN) + .with("role1", TEST_ROLE1).with("role2", TEST_ROLE2) + .with("roleBaseUrl", UrlUtils.roleResource(TEST_CELL1, null, "")).returns() + .statusCode(HttpStatus.SC_OK); + + Cell cell = ModelFactory.cellFromName(TEST_CELL1); + CellCmp cc = ModelFactory.cellCmp(cell); + Acl acl = cc.getAcl(); + log.info(acl.toJSON()); + JSONObject j = (JSONObject) new JSONParser().parse(acl.toJSON()); + String base = (String)j.get("@xml.base"); + assertTrue(base.startsWith(UriUtils.SCHEME_LOCALUNIT)); + + } finally { + // ACLの設定を元に戻す + Http.request("cell/acl-default.txt").with("url", TEST_CELL1).with("token", TOKEN).with("role1", TEST_ROLE1) + .with("role2", TEST_ROLE2).with("box", Setup.TEST_BOX1) + .with("roleBaseUrl", UrlUtils.roleResource(TEST_CELL1, null, "")).with("level", "").returns() + .statusCode(-1); + } + + + } /** * CellとBoxのACLを設定しBoxにアクセスできることを確認テスト. @@ -185,7 +229,7 @@ public AclTest() { StringBuffer sb = new StringBuffer(resorce); sb.deleteCharAt(resorce.length() - 1); TestMethodUtils.aclResponseTest(root, sb.toString(), list, 1, - UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, ""), null); + UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, ""), null); // Boxの作成 BoxUtils.create(TEST_CELL1, testBox1, TOKEN); @@ -227,7 +271,7 @@ public AclTest() { .with("token", TOKEN) .with("level", "none") .returns() - .statusCode(HttpStatus.SC_OK); + .statusCode(-1); // Cell ACLの設定を元に戻す Http.request("cell/acl-default.txt").with("url", TEST_CELL1) @@ -237,7 +281,7 @@ public AclTest() { .with("box", testBox1) .with("roleBaseUrl", UrlUtils.roleResource(TEST_CELL1, null, "")) .returns() - .statusCode(HttpStatus.SC_OK); + .statusCode(-1); } } @@ -282,7 +326,7 @@ public AclTest() { StringBuffer sb = new StringBuffer(resorce); sb.deleteCharAt(resorce.length() - 1); TestMethodUtils.aclResponseTest(root, sb.toString(), list, 1, - UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, ""), null); + UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, ""), null); // Boxの作成 BoxUtils.create(TEST_CELL1, testBox1, TOKEN); @@ -359,7 +403,7 @@ public AclTest() { StringBuffer sb = new StringBuffer(resorce); sb.deleteCharAt(resorce.length() - 1); TestMethodUtils.aclResponseTest(root, sb.toString(), list, 1, - UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, ""), null); + UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, ""), null); // Boxの作成 BoxUtils.create(TEST_CELL1, testBox1, TOKEN); @@ -436,7 +480,7 @@ public AclTest() { StringBuffer sb = new StringBuffer(resorce); sb.deleteCharAt(resorce.length() - 1); TestMethodUtils.aclResponseTest(root, sb.toString(), list, 1, - UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, ""), null); + UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, ""), null); // Boxの作成 BoxUtils.create(TEST_CELL1, testBox1, TOKEN); @@ -557,7 +601,7 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S sb.deleteCharAt(resorce.length() - 1); TestMethodUtils.aclResponseTest(root, sb.toString(), list, 1, - UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, ""), null); + UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, ""), null); } finally { // ACLの設定を元に戻す @@ -630,7 +674,7 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S sb.deleteCharAt(resorce.length() - 1); TestMethodUtils.aclResponseTest(root, sb.toString(), list, 1, - UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, ""), null); + UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, ""), null); // PROPPATCH設定実行 DavResourceUtils.setProppatch(TEST_CELL1, TOKEN, HttpStatus.SC_MULTI_STATUS, "author1", "hoge1"); @@ -667,7 +711,7 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S sb.deleteCharAt(resorce.length() - 1); TestMethodUtils.aclResponseTest(root, sb.toString(), list, 1, - UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, ""), null); + UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, ""), null); } finally { // ACLの設定を元に戻す Http.request("cell/acl-default.txt") @@ -731,7 +775,7 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S sb.deleteCharAt(resorce.length() - 1); TestMethodUtils.aclResponseTest(root, sb.toString(), list, 1, - UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, ""), null); + UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, ""), null); } finally { // ACLの設定を元に戻す @@ -797,7 +841,7 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S sb.deleteCharAt(resorce.length() - 1); TestMethodUtils.aclResponseTest(root, sb.toString(), list, 1, - UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, ""), null); + UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, ""), null); } finally { // ロールの削除 @@ -956,7 +1000,7 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S @SuppressWarnings("unchecked") @Test public final void CellレベルACL設定アクセス制御$link確認() { - String extCellUrl = PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot(Setup.TEST_CELL2)); + String extCellUrl = CommonUtils.encodeUrlComp(UrlUtils.cellRoot(Setup.TEST_CELL2)); String relationName = "testRelation"; try { List account = new ArrayList(); @@ -1007,7 +1051,7 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S account.get(4), HttpStatus.SC_NO_CONTENT); // 削除 LinksUtils.deleteLinksExtCell(TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot(Setup.TEST_CELL2)), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot(Setup.TEST_CELL2)), Relation.EDM_TYPE_NAME, relationName, null, account.get(10), HttpStatus.SC_NO_CONTENT); // $link extCellとrole→SOCIALとAUTHの権限が必要 @@ -1022,7 +1066,7 @@ private static TResponse setAclAllandRole(String cell, String token, int code, S // 削除 LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot(Setup.TEST_CELL2)), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot(Setup.TEST_CELL2)), Role.EDM_TYPE_NAME, "role1", null, account.get(10), HttpStatus.SC_NO_CONTENT); } finally { // Relationの削除 @@ -1643,7 +1687,7 @@ private void approvedMessageTest(List account) { // OK: ROOT apvRes4 = ReceivedMessageUtils.approve(account.get(10), TEST_CELL1, uuid, HttpStatus.SC_NO_CONTENT); // Relation-ExtCell $links削除 - LinksUtils.deleteLinksExtCell(TEST_CELL1, PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetcell")), + LinksUtils.deleteLinksExtCell(TEST_CELL1, CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetcell")), Relation.EDM_TYPE_NAME, "user", null, AbstractCase.MASTER_TOKEN_NAME, -1); // ExtCell削除 ExtCellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, TEST_CELL1, UrlUtils.cellRoot("targetcell")); @@ -1657,7 +1701,7 @@ private void approvedMessageTest(List account) { // OK: message+social apvRes5 = ReceivedMessageUtils.approve(account.get(18), TEST_CELL1, uuid, HttpStatus.SC_NO_CONTENT); // Relation-ExtCell $links削除 - LinksUtils.deleteLinksExtCell(TEST_CELL1, PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetcell")), + LinksUtils.deleteLinksExtCell(TEST_CELL1, CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetcell")), Relation.EDM_TYPE_NAME, "user", null, AbstractCase.MASTER_TOKEN_NAME, -1); // Relation削除 RelationUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, "user", null, -1); @@ -1726,7 +1770,7 @@ private void approvedMessageTest(List account) { ODataCommon.deleteOdataResource(apvRes7.getLocationHeader()); } // Relation-ExtCell $links削除 - LinksUtils.deleteLinksExtCell(TEST_CELL1, PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetcell")), + LinksUtils.deleteLinksExtCell(TEST_CELL1, CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetcell")), Relation.EDM_TYPE_NAME, "user", null, AbstractCase.MASTER_TOKEN_NAME, -1); // Relation削除 RelationUtils.delete(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, "user", null, -1); @@ -2061,7 +2105,7 @@ private void logListAclTest(List account) { "_" + ExtCell.EDM_TYPE_NAME, extCellBody, account.get(4), HttpStatus.SC_CREATED); // 作成した$linkの削除 - LinksUtils.deleteLinksExtCell(TEST_CELL1, PersoniumCoreUtils.encodeUrlComp(extCellUrl), + LinksUtils.deleteLinksExtCell(TEST_CELL1, CommonUtils.encodeUrlComp(extCellUrl), Relation.EDM_TYPE_NAME, relationName, null, account.get(10), HttpStatus.SC_NO_CONTENT); // 作成したExtCell削除 ExtCellUtils.delete(TOKEN, TEST_CELL1, extCellUrl, @@ -2072,28 +2116,28 @@ private void logListAclTest(List account) { // extCellとrole→SOCIALとAUTHの権限が必要 CellUtils.createNp(post, TEST_CELL1, ExtCell.EDM_TYPE_NAME, - PersoniumCoreUtils.encodeUrlComp(extCellUrl), + CommonUtils.encodeUrlComp(extCellUrl), "_" + Role.EDM_TYPE_NAME, roleBody, account.get(0), HttpStatus.SC_FORBIDDEN); CellUtils.createNp(post, TEST_CELL1, ExtCell.EDM_TYPE_NAME, - PersoniumCoreUtils.encodeUrlComp(extCellUrl), + CommonUtils.encodeUrlComp(extCellUrl), "_" + Role.EDM_TYPE_NAME, roleBody, account.get(1), HttpStatus.SC_FORBIDDEN); CellUtils.createNp(post, TEST_CELL1, ExtCell.EDM_TYPE_NAME, - PersoniumCoreUtils.encodeUrlComp(extCellUrl), + CommonUtils.encodeUrlComp(extCellUrl), "_" + Role.EDM_TYPE_NAME, roleBody, account.get(4), HttpStatus.SC_FORBIDDEN); CellUtils.createNp(post, TEST_CELL1, ExtCell.EDM_TYPE_NAME, - PersoniumCoreUtils.encodeUrlComp(extCellUrl), + CommonUtils.encodeUrlComp(extCellUrl), "_" + Role.EDM_TYPE_NAME, roleBody, account.get(9), HttpStatus.SC_CREATED); // 作成した$linkの削除 - LinksUtils.deleteLinksExtCell(TEST_CELL1, PersoniumCoreUtils.encodeUrlComp(extCellUrl), + LinksUtils.deleteLinksExtCell(TEST_CELL1, CommonUtils.encodeUrlComp(extCellUrl), Role.EDM_TYPE_NAME, roleName, null, TOKEN, HttpStatus.SC_NO_CONTENT); // Role削除 RoleUtils.delete(TEST_CELL1, TOKEN, roleName, null); CellUtils.createNp(post, TEST_CELL1, ExtCell.EDM_TYPE_NAME, - PersoniumCoreUtils.encodeUrlComp(extCellUrl), + CommonUtils.encodeUrlComp(extCellUrl), "_" + Role.EDM_TYPE_NAME, roleBody, account.get(10), HttpStatus.SC_CREATED); // Role削除 @@ -2101,7 +2145,7 @@ private void logListAclTest(List account) { } finally { // 作成した$linkの削除 - LinksUtils.deleteLinksExtCell(TEST_CELL1, PersoniumCoreUtils.encodeUrlComp(extCellUrl), + LinksUtils.deleteLinksExtCell(TEST_CELL1, CommonUtils.encodeUrlComp(extCellUrl), Relation.EDM_TYPE_NAME, relationName, null, TOKEN, -1); // ExtCell 削除 ExtCellUtils.delete(TOKEN, TEST_CELL1, extCellUrl, @@ -2111,6 +2155,9 @@ private void logListAclTest(List account) { } } + + + private void deleteBox(String boxName, String location) { if (location == null) { diff --git a/src/test/java/io/personium/test/jersey/cell/BoxUrlTest.java b/src/test/java/io/personium/test/jersey/cell/BoxUrlTest.java index 2b8ebc7a5..a745b8fff 100644 --- a/src/test/java/io/personium/test/jersey/cell/BoxUrlTest.java +++ b/src/test/java/io/personium/test/jersey/cell/BoxUrlTest.java @@ -88,19 +88,19 @@ public BoxUrlTest() { } /** - * 指定したローカルユニットschemaのBoxURLがLocalUnitで取得できること. + * URL of a box whose Schema URL is personium-localunit scheme should be obtained by querying with Http URL. */ @Test - public final void schemaパラメタとしてhttpURLの指定でlocalunitURLをschemaとするBoxが取得できること() { + public final void URLofBox_withLocalUnitURLSchema_shouldBeObtainedBy_QueryingWith_HttpURL() { try { - // テスト準備 - // スキーマ設定(Box更新) + // preparing test + // (Update Box and change Schema) // Setupでセル1にBoxのSchemaとして登録されている urlをhttpからpersonium-localunitに一時的に更新。 BoxUtils.update(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, Setup.TEST_BOX1, "*", Setup.TEST_BOX1, - UriUtils.SCHEME_UNIT_URI + Setup.TEST_CELL_SCHEMA1 + "/", HttpStatus.SC_NO_CONTENT); + UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL_SCHEMA1 + ":/", HttpStatus.SC_NO_CONTENT); - // テスト実施 + // Run Test PersoniumRestAdapter rest = new PersoniumRestAdapter(); PersoniumResponse res = null; @@ -117,7 +117,7 @@ public BoxUrlTest() { } catch (PersoniumException e) { fail(e.getMessage()); } finally { - // Box Schema更新(元に戻す) + // Update Box Schema (restore) BoxUtils.update(Setup.TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, Setup.TEST_BOX1, "*", Setup.TEST_BOX1, UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1), HttpStatus.SC_NO_CONTENT); @@ -125,10 +125,10 @@ public BoxUrlTest() { } /** - * schemaパラメタとしてhttpURLの指定でlocalunitURLをschemaとするBoxが取得できること. + * URL of a box whose Schema URL is Http scheme should be obtained by querying with personium-localunit URL. */ @Test - public final void schemaパラメタとしてlocalunitURLの指定でhttpURLをschemaとするBoxが取得できること() { + public final void URLofBox_withHttpURLSchema_shouldBeObtainedBy_QueryingWith_LocalUnitURL() { try { // Setupを流用 PersoniumRestAdapter rest = new PersoniumRestAdapter(); @@ -137,9 +137,9 @@ public BoxUrlTest() { HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); - String localunitUrl = UriUtils.SCHEME_UNIT_URI + Setup.TEST_CELL_SCHEMA1 + "/"; - res = rest.getAcceptEncodingGzip( - UrlUtils.boxUrl(Setup.TEST_CELL1, localunitUrl), requestheaders); + String localunitUrl = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL_SCHEMA1 + ":/"; + String boxUrlApiUrl = UrlUtils.boxUrl(Setup.TEST_CELL1, localunitUrl); + res = rest.getAcceptEncodingGzip(boxUrlApiUrl , requestheaders); assertEquals(HttpStatus.SC_OK, res.getStatusCode()); assertEquals(UrlUtils.boxRoot(Setup.TEST_CELL1, Setup.TEST_BOX1 + "/"), res.getFirstHeader(HttpHeaders.LOCATION)); diff --git a/src/test/java/io/personium/test/jersey/cell/CellBulkDeletionTest.java b/src/test/java/io/personium/test/jersey/cell/CellBulkDeletionTest.java index ba33950e8..29bfebde4 100644 --- a/src/test/java/io/personium/test/jersey/cell/CellBulkDeletionTest.java +++ b/src/test/java/io/personium/test/jersey/cell/CellBulkDeletionTest.java @@ -30,7 +30,7 @@ import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; import io.personium.common.auth.token.UnitLocalUnitUserToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.Cell; @@ -144,7 +144,7 @@ public void Before() { assertEquals(HttpStatus.SC_PRECONDITION_FAILED, response.getStatusCode()); ODataCommon.checkErrorResponseBody(response, PersoniumCoreException.Misc.PRECONDITION_FAILED.getCode(), PersoniumCoreException.Misc.PRECONDITION_FAILED - .params(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) + .params(CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) .getMessage()); } finally { // セルを削除する @@ -173,7 +173,7 @@ public void Before() { assertEquals(HttpStatus.SC_PRECONDITION_FAILED, response.getStatusCode()); ODataCommon.checkErrorResponseBody(response, PersoniumCoreException.Misc.PRECONDITION_FAILED.getCode(), PersoniumCoreException.Misc.PRECONDITION_FAILED - .params(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) + .params(CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) .getMessage()); } finally { // セルを削除する diff --git a/src/test/java/io/personium/test/jersey/cell/DefaultBoxTest.java b/src/test/java/io/personium/test/jersey/cell/DefaultBoxTest.java index a35ceecc5..0b2ac8d07 100644 --- a/src/test/java/io/personium/test/jersey/cell/DefaultBoxTest.java +++ b/src/test/java/io/personium/test/jersey/cell/DefaultBoxTest.java @@ -36,7 +36,7 @@ import io.personium.test.utils.DavResourceUtils; /** - * UnitUserでCellをCRUDするテスト. + * MainBoxに関するテスト. */ @RunWith(PersoniumIntegTestRunner.class) @Category({Unit.class, Integration.class, Regression.class }) @@ -77,21 +77,21 @@ public void after() { } /** - * セル作成時にデフォルトボックスが生成されることの確認. + * セル作成時にMain Boxが生成されることの確認. */ @Test - public final void セル作成時にデフォルトボックスが生成されることの確認() { + public final void セル作成時にMainBoxが生成されることの確認() { try { // セル作成 CellUtils.create(CELL_NAME, TOKEN, HttpStatus.SC_CREATED); // デフォルトボックスに対してMKCOLを実行して、ボックスの存在及び子要素が作成できることを確認 - DavResourceUtils.createWebDavCollection("box/mkcol.txt", CELL_NAME, Box.DEFAULT_BOX_NAME + "/" + COL_NAME, + DavResourceUtils.createWebDavCollection("box/mkcol.txt", CELL_NAME, Box.MAIN_BOX_NAME + "/" + COL_NAME, TOKEN, HttpStatus.SC_CREATED); } finally { // コレクションの削除 - DavResourceUtils.deleteCollection(CELL_NAME, Box.DEFAULT_BOX_NAME, COL_NAME, TOKEN, -1); + DavResourceUtils.deleteCollection(CELL_NAME, Box.MAIN_BOX_NAME, COL_NAME, TOKEN, -1); // セル削除 CellUtils.delete(TOKEN, CELL_NAME, -1); @@ -99,24 +99,24 @@ public void after() { } /** - * デフォルトボックス配下にデータが存在するとセルが削除できないことの確認. + * Main Box配下にデータが存在するとセルが削除できないことの確認. */ @Test - public final void デフォルトボックス配下にデータが存在するとセルが削除できないことの確認() { + public final void MainBox配下にデータが存在するとセルが削除できないことの確認() { try { // セル作成 CellUtils.create(CELL_NAME, TOKEN, HttpStatus.SC_CREATED); - // デフォルトボックスにコレクションを作成 - DavResourceUtils.createWebDavCollection("box/mkcol.txt", CELL_NAME, Box.DEFAULT_BOX_NAME + "/" + COL_NAME, + // Main Boxにコレクションを作成 + DavResourceUtils.createWebDavCollection("box/mkcol.txt", CELL_NAME, Box.MAIN_BOX_NAME + "/" + COL_NAME, TOKEN, HttpStatus.SC_CREATED); - // デフォルトボックスにコレクションがあるためセル削除が失敗すること + // Main Boxにコレクションがあるためセル削除が失敗すること CellUtils.delete(TOKEN, CELL_NAME, HttpStatus.SC_CONFLICT); } finally { // コレクションの削除 - DavResourceUtils.deleteCollection(CELL_NAME, Box.DEFAULT_BOX_NAME, COL_NAME, TOKEN, -1); + DavResourceUtils.deleteCollection(CELL_NAME, Box.MAIN_BOX_NAME, COL_NAME, TOKEN, -1); // セル削除 CellUtils.delete(TOKEN, CELL_NAME, -1); diff --git a/src/test/java/io/personium/test/jersey/cell/EventTest.java b/src/test/java/io/personium/test/jersey/cell/EventTest.java index eadf0559e..603bb14f3 100644 --- a/src/test/java/io/personium/test/jersey/cell/EventTest.java +++ b/src/test/java/io/personium/test/jersey/cell/EventTest.java @@ -117,7 +117,7 @@ public EventTest() { public final void イベント受付に対するPROPFINDで501が返却されること() { Http.request("cell/cell-event.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL1) .with("requestKey", "testRequestKey") @@ -133,7 +133,7 @@ public EventTest() { public final void イベント受付に対するPROPPATCHで501が返却されること() { Http.request("cell/cell-event.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPPATCH) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPPATCH) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL1) .with("requestKey", "testRequestKey") diff --git a/src/test/java/io/personium/test/jersey/cell/LogListTest.java b/src/test/java/io/personium/test/jersey/cell/LogListTest.java index 0d5dd7721..c7d3205ca 100644 --- a/src/test/java/io/personium/test/jersey/cell/LogListTest.java +++ b/src/test/java/io/personium/test/jersey/cell/LogListTest.java @@ -74,7 +74,7 @@ public LogListTest() { public final void ログファイル一覧取得に対するPROPFINDで501が返却されること() { Http.request("cell/log-propfind-with-nobody.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", CURRENT_COLLECTION) @@ -126,7 +126,7 @@ public LogListTest() { .statusCode(HttpStatus.SC_METHOD_NOT_ALLOWED); Http.request("cell/log-propfind-with-nobody.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPPATCH) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPPATCH) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", CURRENT_COLLECTION) @@ -142,7 +142,7 @@ public LogListTest() { public final void ログファイル一覧取得で存在しないコレクションに対するPROPFINDで404が返却されること() { Http.request("cell/log-propfind-with-nobody.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", "dummy") @@ -195,7 +195,7 @@ public LogListTest() { public final void アーカイブログファイル一覧取得_ボディなしかつContentLengthありのPROPFINDで207が返却されること() { Http.request("cell/log-propfind-with-nobody.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", ARCHIVE_COLLECTION) @@ -211,7 +211,7 @@ public LogListTest() { public final void アーカイブログファイル一覧取得_ボディなしかつContentLengthなしのPROPFINDで207が返却されること() { Http.request("cell/log-propfind-with-nobody-non-content-length.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", ARCHIVE_COLLECTION) @@ -230,7 +230,7 @@ public LogListTest() { + ""; TResponse tresponse = Http.request("cell/log-propfind-with-body.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", ARCHIVE_COLLECTION) @@ -254,7 +254,7 @@ public LogListTest() { + ""; TResponse tresponse = Http.request("cell/log-propfind-with-body.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", ARCHIVE_COLLECTION) @@ -278,7 +278,7 @@ public LogListTest() { + ""; Http.request("cell/log-propfind-with-body.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", ARCHIVE_COLLECTION) @@ -299,7 +299,7 @@ public LogListTest() { + ""; Http.request("cell/log-propfind-with-body.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", ARCHIVE_COLLECTION) @@ -320,7 +320,7 @@ public LogListTest() { + ""; Http.request("cell/log-propfind-with-body.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", ARCHIVE_COLLECTION) @@ -340,7 +340,7 @@ public LogListTest() { + ""; Http.request("cell/log-propfind-with-body.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", "Invalid-Token") .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", ARCHIVE_COLLECTION) @@ -360,7 +360,7 @@ public LogListTest() { + ""; Http.request("cell/log-propfind-with-body-no-depth.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", ARCHIVE_COLLECTION) @@ -379,7 +379,7 @@ public LogListTest() { + ""; Http.request("cell/log-propfind-with-body.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", ARCHIVE_COLLECTION) @@ -400,7 +400,7 @@ public LogListTest() { + ""; Http.request("cell/log-propfind-with-body.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL_EVENTLOG) .with("collection", ARCHIVE_COLLECTION) diff --git a/src/test/java/io/personium/test/jersey/cell/LogTest.java b/src/test/java/io/personium/test/jersey/cell/LogTest.java index 388327b2e..9000d88fb 100644 --- a/src/test/java/io/personium/test/jersey/cell/LogTest.java +++ b/src/test/java/io/personium/test/jersey/cell/LogTest.java @@ -252,7 +252,7 @@ public LogTest() { .statusCode(HttpStatus.SC_METHOD_NOT_ALLOWED); Http.request("cell/log-get.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL1) .with("collection", CURRENT_COLLECTION) @@ -262,7 +262,7 @@ public LogTest() { .statusCode(HttpStatus.SC_METHOD_NOT_ALLOWED); Http.request("cell/log-get.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPPATCH) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPPATCH) .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", Setup.TEST_CELL1) .with("collection", CURRENT_COLLECTION) diff --git a/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java b/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java index 12076dfcf..287c4a08e 100644 --- a/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java +++ b/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java @@ -42,7 +42,7 @@ import org.junit.runner.RunWith; import io.personium.common.auth.token.TransCellAccessToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.model.ctl.Common; import io.personium.core.model.ctl.ExtCell; @@ -69,14 +69,14 @@ import io.personium.test.utils.TResponse; /** - * メッセージ承認APIのテスト. + * Message Approval API test. */ @RunWith(PersoniumIntegTestRunner.class) @Category({Unit.class, Integration.class, Regression.class }) public class MessageApproveTest extends ODataCommon { /** - * コンストラクタ. + * Constructor. */ public MessageApproveTest() { super(new PersoniumCoreApplication()); @@ -372,7 +372,7 @@ public MessageApproveTest() { } finally { // Relation-ExtCell $links削除 LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, null, MASTER_TOKEN_NAME, -1); // Relation削除 RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, null, -1); @@ -451,7 +451,7 @@ public void normal_approve_build_message_for_not_exist_relation() { } finally { // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, null, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, null, -1); @@ -547,7 +547,7 @@ public void normal_approve_build_message_with_relationClassURL_for_allready_exis } // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, boxName, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, -1); @@ -626,7 +626,7 @@ public void normal_approve_build_message_with_relationClassURL_for_not_exist_rel } // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, boxName, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, -1); @@ -731,7 +731,7 @@ public void normal_approve_break_message_with_relationClassURL() { } // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, boxName, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, -1); @@ -894,7 +894,7 @@ public void normal_approve_build_message_with_unit_local_relationClassURL() { } // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, boxName, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, -1); @@ -987,7 +987,7 @@ public void normal_approve_boxbound_build_message_for_allready_exist_relation() } // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, boxName, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, -1); @@ -1067,7 +1067,7 @@ public void normal_approve_boxbound_build_message_for_not_exist_relation() { } // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, boxName, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, -1); @@ -1174,7 +1174,7 @@ public void normal_approve_boxbound_break_message() { } // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, boxName, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, -1); @@ -1344,7 +1344,7 @@ public void normal_approve_boxbound_build_message_with_relationClassURL() { BoxUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, "testBox002", -1); // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, boxName, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, -1); @@ -1457,7 +1457,7 @@ public void normal_approve_boxbound_break_message_with_relationClassURL() { BoxUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, "testBox002", -1); // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, boxName, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, -1); @@ -1549,7 +1549,7 @@ public void normal_approve_grant_message_with_roleClassURL_for_allready_exist_ro } // Delete Role-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Role.EDM_TYPE_NAME, roleName, boxName, MASTER_TOKEN_NAME, -1); // Delete Role RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); @@ -1628,7 +1628,7 @@ public void normal_approve_grant_message_with_roleClassURL_for_not_exist_role() } // Delete Role-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Role.EDM_TYPE_NAME, roleName, boxName, MASTER_TOKEN_NAME, -1); // Delete Role RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); @@ -1734,7 +1734,7 @@ public void normal_approve_revoke_message_with_roleClassURL() { } // Delete Role-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Role.EDM_TYPE_NAME, roleName, boxName, MASTER_TOKEN_NAME, -1); // Delete Role RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); @@ -1897,7 +1897,7 @@ public void normal_approve_grant_message_with_unit_local_roleClassURL() { } // Delete Role-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Role.EDM_TYPE_NAME, roleName, boxName, MASTER_TOKEN_NAME, -1); // Delete Role RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); @@ -2004,11 +2004,11 @@ public void normal_approve_multiple_request_object_message() { } // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, boxName, MASTER_TOKEN_NAME, -1); // Delete Role-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Role.EDM_TYPE_NAME, roleName, boxName, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, -1); @@ -2103,7 +2103,7 @@ public void normal_approve_boxbound_grant_message_for_allready_exist_role() { } // Delete Role-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Role.EDM_TYPE_NAME, roleName, boxName, MASTER_TOKEN_NAME, -1); // Delete Role RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); @@ -2183,7 +2183,7 @@ public void normal_approve_boxbound_grant_message_for_not_exist_role() { } // Delete Role-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Role.EDM_TYPE_NAME, roleName, boxName, MASTER_TOKEN_NAME, -1); // Delete Role RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); @@ -2290,7 +2290,7 @@ public void normal_approve_boxbound_revoke_message() { } // Delete Role-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Role.EDM_TYPE_NAME, roleName, boxName, MASTER_TOKEN_NAME, -1); // Delete Role RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); @@ -2460,7 +2460,7 @@ public void normal_approve_boxbound_grant_message_with_roleClassURL() { BoxUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, "testBox002", -1); // Delete Role-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Role.EDM_TYPE_NAME, roleName, boxName, MASTER_TOKEN_NAME, -1); // Delete Role RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); @@ -2573,7 +2573,7 @@ public void normal_approve_boxbound_revoke_message_with_roleClassURL() { BoxUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, "testBox002", -1); // Delete Role-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Role.EDM_TYPE_NAME, roleName, boxName, MASTER_TOKEN_NAME, -1); // Delete Role RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); @@ -2656,7 +2656,7 @@ public void error_approve_build_message_not_found_box_corresponding_to_RelationC } // Delete Relation-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, boxName, MASTER_TOKEN_NAME, -1); // Delete Relation RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, boxName, -1); @@ -2739,7 +2739,7 @@ public void error_approve_grant_message_not_found_box_corresponding_to_RoleClass } // Delete Role-ExtCell $links LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Role.EDM_TYPE_NAME, roleName, boxName, MASTER_TOKEN_NAME, -1); // Delete Role RoleUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, roleName, boxName, -1); @@ -2789,7 +2789,7 @@ public void error_approve_grant_message_not_found_box_corresponding_to_RoleClass HttpStatus.SC_CREATED); // Relation-ExtCell $links LinksUtils.createLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, null, MASTER_TOKEN_NAME, HttpStatus.SC_NO_CONTENT); // メッセージ受信を登録 @@ -2817,7 +2817,7 @@ public void error_approve_grant_message_not_found_box_corresponding_to_RoleClass } finally { // Relation-ExtCell $links削除 LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, null, MASTER_TOKEN_NAME, -1); // Relation削除 RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, null, -1); @@ -3105,7 +3105,7 @@ public void error_approve_grant_message_not_found_box_corresponding_to_RoleClass } finally { // Relation-ExtCell $links削除 LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, null, MASTER_TOKEN_NAME, -1); // Relation削除 RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, null, -1); @@ -3313,7 +3313,7 @@ public void error_approve_grant_message_not_found_box_corresponding_to_RoleClass } finally { // Relation-ExtCell $links削除 LinksUtils.deleteLinksExtCell(Setup.TEST_CELL1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot("targetCell")), Relation.EDM_TYPE_NAME, relationName, null, MASTER_TOKEN_NAME, -1); // Relation削除 RelationUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN_NAME, relationName, null, -1); @@ -3468,7 +3468,7 @@ private PersoniumResponse createReceivedMessage(String requestUrl, JSONObject bo private String getCellIssueToken(String targetCellUrl) { String cellUrl = UrlUtils.cellRoot(Setup.TEST_CELL2); TransCellAccessToken token = new TransCellAccessToken(cellUrl, cellUrl, - targetCellUrl, new ArrayList(), ""); + targetCellUrl, new ArrayList(), "", null); return token.toTokenString(); } diff --git a/src/test/java/io/personium/test/jersey/cell/MessageReceivedTest.java b/src/test/java/io/personium/test/jersey/cell/MessageReceivedTest.java index 5421254bc..ca08ccee8 100644 --- a/src/test/java/io/personium/test/jersey/cell/MessageReceivedTest.java +++ b/src/test/java/io/personium/test/jersey/cell/MessageReceivedTest.java @@ -312,7 +312,7 @@ public MessageReceivedTest() { String cellUrl = UrlUtils.cellRoot(Setup.TEST_CELL2); String targetCellUrl = UrlUtils.cellRoot(Setup.TEST_CELL1); TransCellAccessToken token = new TransCellAccessToken(cellUrl, cellUrl + "#account", - targetCellUrl, new ArrayList(), ""); + targetCellUrl, new ArrayList(), "", null); requestheaders.put(HttpHeaders.AUTHORIZATION, "Bearer " + token.toTokenString()); @@ -1813,7 +1813,7 @@ private PersoniumResponse createReceivedMessage() { private String getCellIssueToken(String targetCellUrl) { String cellUrl = UrlUtils.cellRoot(Setup.TEST_CELL2); TransCellAccessToken token = new TransCellAccessToken(cellUrl, cellUrl, - targetCellUrl, new ArrayList(), ""); + targetCellUrl, new ArrayList(), "", null); return token.toTokenString(); } } diff --git a/src/test/java/io/personium/test/jersey/cell/UnitUserCellTest.java b/src/test/java/io/personium/test/jersey/cell/UnitUserCellTest.java index c10526559..415dca118 100644 --- a/src/test/java/io/personium/test/jersey/cell/UnitUserCellTest.java +++ b/src/test/java/io/personium/test/jersey/cell/UnitUserCellTest.java @@ -31,14 +31,20 @@ import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import io.personium.common.auth.token.AbstractOAuth2Token.TokenDsigException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; +import io.personium.common.auth.token.AbstractOAuth2Token.TokenRootCrtException; import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; import io.personium.common.auth.token.UnitLocalUnitUserToken; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; import io.personium.core.auth.OAuth2Helper; +import io.personium.core.model.Cell; +import io.personium.core.model.ModelFactory; import io.personium.core.model.ctl.Account; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.core.utils.UriUtils; @@ -67,6 +73,8 @@ @Category({Unit.class, Integration.class, Regression.class }) public class UnitUserCellTest extends PersoniumTest { + private static Logger log = LoggerFactory.getLogger(UnitUserCellTest.class); + private static final String UNIT_USER_CELL = "unitusercell"; private static final String UNIT_USER_ACCOUNT = "UnitUserName"; private static final String UNIT_USER_ACCOUNT_PASS = "password"; @@ -80,7 +88,7 @@ public class UnitUserCellTest extends PersoniumTest { private static String issuersBackup = ""; /** - * コンストラクタ. テスト対象のパッケージをsuperに渡す必要がある + * Constructor. テスト対象のパッケージをsuperに渡す必要がある */ public UnitUserCellTest() { super(new PersoniumCoreApplication()); @@ -95,7 +103,7 @@ public static void beforeClass() throws Exception { // Override issuers in unitconfig. issuersBackup = PersoniumUnitConfig.get("io.personium.core.unitUser.issuers"); PersoniumUnitConfig.set("io.personium.core.unitUser.issuers", - UriUtils.SCHEME_UNIT_URI + UNIT_USER_CELL + "/"); + UriUtils.SCHEME_LOCALUNIT + ":/" + UNIT_USER_CELL + "/"); // Read role name from AccessContext Field admin = AccessContext.class.getDeclaredField("ROLE_UNIT_ADMIN"); @@ -140,11 +148,72 @@ public static void afterClass() { /** * ユニットユーザートークンでセル作成を行いオーナーが設定されることを確認. + * @throws TokenRootCrtException + * @throws TokenDsigException + * @throws TokenParseException */ @Test - public void ユニットユーザートークンでセル作成を行いオーナーが設定されることを確認() { + public void ユニットユーザートークンでセル作成を行いオーナーが設定されることを確認() throws TokenParseException, TokenDsigException, TokenRootCrtException { try { - // 本テスト用セルの作成 + // 本テスト用 Unit User Cell の作成 + CellUtils.create(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, -1); + + // アカウント追加 + AccountUtils.create(AbstractCase.MASTER_TOKEN_NAME, UNIT_USER_CELL, + UNIT_USER_ACCOUNT, UNIT_USER_ACCOUNT_PASS, -1); + + // 認証(ユニットユーザートークン取得) + TResponse res = Http.request("authn/password-tc-c0.txt") + .with("remoteCell", UNIT_USER_CELL) + .with("username", UNIT_USER_ACCOUNT) + .with("password", UNIT_USER_ACCOUNT_PASS) + .with("p_target", UrlUtils.unitRoot()) + .returns() + .statusCode(HttpStatus.SC_OK); + + JSONObject json = res.bodyAsJson(); + String unitUserToken = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN); + + // + TransCellAccessToken tcToken = TransCellAccessToken.parse(unitUserToken); + String subject = tcToken.getSubject(); + log.info("##TOKEN##"); + log.info("Subject: "+ subject); + log.info("Issuer : "+ tcToken.getSubject()); + log.info("Target : "+ tcToken.getTarget()); + String localunitSubject = UriUtils.convertSchemeFromHttpToLocalUnit(subject); + log.info("Owner Should be : "+ localunitSubject); + + // ユニットユーザートークンを使ってセル作成をする. + // オーナーがユニットユーザー(ここだとuserNameアカウントのURL)になるはず。 + CellUtils.create(CREATE_CELL, unitUserToken, HttpStatus.SC_CREATED); + + Cell cell = ModelFactory.cellFromName(CREATE_CELL); + String owner = cell.getOwnerRaw(); + log.info(" OWNER = " + owner); + assertEquals(localunitSubject, owner); + + + } finally { + // アカウント削除 + AccountUtils.delete(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, + UNIT_USER_ACCOUNT, -1); + // 本テスト用セルの削除 + CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, CREATE_CELL, -1); + CellUtils.delete(AbstractCase.MASTER_TOKEN_NAME, UNIT_USER_CELL, -1); + } + } + + /** + * ユニットユーザートークンでセル作成を行いオーナーとして各種処理が可能なことを確認. + * @throws TokenRootCrtException + * @throws TokenDsigException + * @throws TokenParseException + */ + @Test + public void ユニットユーザートークンでセル作成を行いオーナーとして各種処理が可能なことを確認() throws TokenParseException, TokenDsigException, TokenRootCrtException { + try { + // 本テスト用 Unit User Cell の作成 CellUtils.create(UNIT_USER_CELL, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_CREATED); // アカウント追加 @@ -163,7 +232,8 @@ public static void afterClass() { JSONObject json = res.bodyAsJson(); String unitUserToken = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN); - // ユニットユーザートークンを使ってセル作成をするとオーナーがユニットユーザー(ここだとuserNameアカウントのURL)になるはず。 + // ユニットユーザートークンを使ってセル作成をする. + // オーナーがユニットユーザー(ここだとuserNameアカウントのURL)になるはず。 CellUtils.create(CREATE_CELL, unitUserToken, HttpStatus.SC_CREATED); // ユニットユーザートークンを使ってセル更新ができることを確認 @@ -202,6 +272,7 @@ public static void afterClass() { } } + /** * ユニットアドミンロールをもつユニットユーザートークンでセル作成を行いオーナーが設定されないことを確認. */ @@ -242,7 +313,7 @@ public static void afterClass() { // UnitUserTokenを自作 TransCellAccessToken tcat = new TransCellAccessToken(UrlUtils.cellRoot(UNIT_USER_CELL), UrlUtils.subjectUrl(UNIT_USER_CELL, UNIT_USER_ACCOUNT), - UrlUtils.getBaseUrl() + "/", new ArrayList(), null); + UrlUtils.getBaseUrl() + "/", new ArrayList(), null, null); // ユニットユーザトークンでは取得できないことを確認 CellUtils.get(CREATE_CELL, tcat.toTokenString(), HttpStatus.SC_FORBIDDEN); @@ -522,7 +593,7 @@ public static void afterClass() { public void セルレベルPROPPATCHをユニットユーザトークンで実行可能なことを確認() throws TokenParseException { // UnitUserTokenを自作 TransCellAccessToken tcat = new TransCellAccessToken(UrlUtils.cellRoot(UNIT_USER_CELL), - Setup.OWNER_VET, UrlUtils.getBaseUrl() + "/", new ArrayList(), null); + Setup.OWNER_VET, UrlUtils.getBaseUrl() + "/", new ArrayList(), null, null); String unitUserToken = tcat.toTokenString(); @@ -540,7 +611,7 @@ public static void afterClass() { public void セルレベルPROPPATCHをオーナーの違うユニットユーザトークンでは実行不可なことを確認() throws TokenParseException { // UnitUserTokenを自作 TransCellAccessToken tcat = new TransCellAccessToken(UrlUtils.cellRoot(UNIT_USER_CELL), - Setup.OWNER_HMC, UrlUtils.getBaseUrl() + "/", new ArrayList(), null); + Setup.OWNER_HMC, UrlUtils.getBaseUrl() + "/", new ArrayList(), null, null); String unitUserToken = tcat.toTokenString(); @@ -721,7 +792,7 @@ public static void afterClass() { public void セルの検索でオーナーが一致するものだけ検索できることの確認() throws TokenParseException { // VETをオーナーにもつUnitUserTokenを自作 TransCellAccessToken tcatvet = new TransCellAccessToken(UrlUtils.cellRoot(UNIT_USER_CELL), - Setup.OWNER_VET, UrlUtils.getBaseUrl() + "/", new ArrayList(), null); + Setup.OWNER_VET, UrlUtils.getBaseUrl() + "/", new ArrayList(), null, null); // ユニットユーザトークンではオーナーが一致するセルのみ検索できることの確認(vetをオーナーに持つのはsetupで作っているtestcell1,schema1のみの想定) TResponse tcatget = CellUtils.list(tcatvet.toTokenString(), HttpStatus.SC_OK); diff --git a/src/test/java/io/personium/test/jersey/cell/auth/AuthCheckTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthCheckTest.java index a6f53a6e7..c046ab637 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/AuthCheckTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/AuthCheckTest.java @@ -36,10 +36,10 @@ import io.personium.common.auth.token.AbstractOAuth2Token.TokenDsigException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenRootCrtException; -import io.personium.common.auth.token.CellLocalAccessToken; +import io.personium.common.auth.token.VisitorLocalAccessToken; import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.Box; import io.personium.core.model.ctl.Account; @@ -101,9 +101,9 @@ public class AuthCheckTest extends PersoniumTest { static final String EXTCELL_URL = UrlUtils.extCellResource(CELL_NAME1, UrlUtils.cellRoot(CELL_NAME2)); static final String ROLE_URI = UrlUtils.roleUrl(CELL_NAME1, null, ROLE_NAME); static final String RELATION_BOX_NAME = null; - static final String EXTROLE_NAME1 = UrlUtils.roleResource(APP_CELL_NAME, Box.DEFAULT_BOX_NAME, ROLE_NAME1); - static final String EXTROLE_NAME2 = UrlUtils.roleResource(CELL_NAME2, Box.DEFAULT_BOX_NAME, ROLE_NAME2); - static final String EXTROLE_NAME4 = UrlUtils.roleResource(APP_CELL_NAME, Box.DEFAULT_BOX_NAME, ROLE_NAME4); + static final String EXTROLE_NAME1 = UrlUtils.roleResource(APP_CELL_NAME, Box.MAIN_BOX_NAME, ROLE_NAME1); + static final String EXTROLE_NAME2 = UrlUtils.roleResource(CELL_NAME2, Box.MAIN_BOX_NAME, ROLE_NAME2); + static final String EXTROLE_NAME4 = UrlUtils.roleResource(APP_CELL_NAME, Box.MAIN_BOX_NAME, ROLE_NAME4); /** * コンストラクタ. @@ -158,7 +158,7 @@ public AuthCheckTest() { TransCellAccessToken aToken = TransCellAccessToken.parse(transCellAccessToken); // 取得トークン内のロール確認 - assertEquals(UrlUtils.roleResource(testCellName, Box.DEFAULT_BOX_NAME, roleNameNoneBox), + assertEquals(UrlUtils.roleResource(testCellName, Box.MAIN_BOX_NAME, roleNameNoneBox), aToken.getRoles().get(0).createUrl()); } finally { @@ -366,7 +366,7 @@ public AuthCheckTest() { RelationUtils.create(testCellName1, AbstractCase.MASTER_TOKEN_NAME, body, HttpStatus.SC_CREATED); // Cell1のExtCellとRelationを結びつけ LinksUtils.createLinksExtCell(testCellName1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot(testCellName2)), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot(testCellName2)), Relation.EDM_TYPE_NAME, relationName, null, masterToken, HttpStatus.SC_NO_CONTENT); // Cell1のRelationとRoleを結びつけ @@ -381,7 +381,7 @@ public AuthCheckTest() { String token1RoleUrl = tokenRoles1.get(0).createUrl(); // 取得トークン内のロール確認 - assertEquals(UrlUtils.roleResource(testCellName1, Box.DEFAULT_BOX_NAME, roleName), token1RoleUrl); + assertEquals(UrlUtils.roleResource(testCellName1, Box.MAIN_BOX_NAME, roleName), token1RoleUrl); // テスト2(user3でのアクセス時にTCAT内にrole2が入っていないこと) List tokenRoles2 = this.checkTransCellAccessToken(testCellName1, @@ -395,7 +395,7 @@ public AuthCheckTest() { // Cell1のExtCellとRelationの削除 LinksUtils.deleteLinksExtCell(testCellName1, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot(testCellName2)), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot(testCellName2)), Relation.EDM_TYPE_NAME, relationName, null, masterToken, -1); // Cell1のRelationを削除 RelationUtils.delete(testCellName1, masterToken, relationName, null, HttpStatus.SC_NO_CONTENT); @@ -485,16 +485,16 @@ public AuthCheckTest() { extRoleBody4.put("_Relation._Box.Name", null); ExtRoleUtils.create(masterToken, CELL_NAME1, extRoleBody4, HttpStatus.SC_CREATED); // Cell1のExtCellとRelationを結びつけ - LinksUtils.createLinksExtCell(CELL_NAME1, PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot(CELL_NAME2)), + LinksUtils.createLinksExtCell(CELL_NAME1, CommonUtils.encodeUrlComp(UrlUtils.cellRoot(CELL_NAME2)), Relation.EDM_TYPE_NAME, RELATION_NAME, null, masterToken, HttpStatus.SC_NO_CONTENT); // Cell1のExtRoleとRoleを結びつけ - LinksUtils.createLinksExtRole(CELL_NAME1, PersoniumCoreUtils.encodeUrlComp(EXTROLE_NAME1), + LinksUtils.createLinksExtRole(CELL_NAME1, CommonUtils.encodeUrlComp(EXTROLE_NAME1), RELATION_NAME, null, Role.EDM_TYPE_NAME, ROLE_NAME, null, masterToken, HttpStatus.SC_NO_CONTENT); - LinksUtils.createLinksExtRole(CELL_NAME1, PersoniumCoreUtils.encodeUrlComp(EXTROLE_NAME2), + LinksUtils.createLinksExtRole(CELL_NAME1, CommonUtils.encodeUrlComp(EXTROLE_NAME2), RELATION_NAME, null, Role.EDM_TYPE_NAME, ROLE_NAME, null, masterToken, HttpStatus.SC_NO_CONTENT); - LinksUtils.createLinksExtRole(CELL_NAME1, PersoniumCoreUtils.encodeUrlComp(EXTROLE_NAME4), + LinksUtils.createLinksExtRole(CELL_NAME1, CommonUtils.encodeUrlComp(EXTROLE_NAME4), RELATION_NAME, null, Role.EDM_TYPE_NAME, ROLE_NAME, null, masterToken, HttpStatus.SC_NO_CONTENT); @@ -505,7 +505,7 @@ public AuthCheckTest() { // テスト環境がロール1つのため、1以外はテスト失敗 assertEquals(1, tokenRoles1.size()); // 取得トークン内のロール確認 - assertEquals(UrlUtils.roleResource(CELL_NAME1, Box.DEFAULT_BOX_NAME, ROLE_NAME), + assertEquals(UrlUtils.roleResource(CELL_NAME1, Box.MAIN_BOX_NAME, ROLE_NAME), tokenRoles1.get(0).createUrl()); // テスト2(user2でのアクセス時にTCAT内にdoctorが入っていること) @@ -514,7 +514,7 @@ public AuthCheckTest() { // テスト環境がロール1つのため、1以外はテスト失敗 assertEquals(1, tokenRoles2.size()); // 取得トークン内のロール確認 - assertEquals(UrlUtils.roleResource(CELL_NAME1, Box.DEFAULT_BOX_NAME, ROLE_NAME), + assertEquals(UrlUtils.roleResource(CELL_NAME1, Box.MAIN_BOX_NAME, ROLE_NAME), tokenRoles2.get(0).createUrl()); // テスト3(user3でのアクセス時にTCAT内にdoctorが入っていないこと) @@ -530,14 +530,14 @@ public AuthCheckTest() { assertEquals(0, tokenRoles4.size()); } finally { // Cell1のExtRoleとRoleを結びつけを削除 - LinksUtils.deleteLinksExtRole(CELL_NAME1, PersoniumCoreUtils.encodeUrlComp(EXTROLE_NAME1), + LinksUtils.deleteLinksExtRole(CELL_NAME1, CommonUtils.encodeUrlComp(EXTROLE_NAME1), RELATION_NAME, null, Role.EDM_TYPE_NAME, ROLE_NAME, null, masterToken, -1); - LinksUtils.deleteLinksExtRole(CELL_NAME1, PersoniumCoreUtils.encodeUrlComp(EXTROLE_NAME2), + LinksUtils.deleteLinksExtRole(CELL_NAME1, CommonUtils.encodeUrlComp(EXTROLE_NAME2), RELATION_NAME, null, Role.EDM_TYPE_NAME, ROLE_NAME, null, masterToken, -1); - LinksUtils.deleteLinksExtRole(CELL_NAME1, PersoniumCoreUtils.encodeUrlComp(EXTROLE_NAME4), + LinksUtils.deleteLinksExtRole(CELL_NAME1, CommonUtils.encodeUrlComp(EXTROLE_NAME4), RELATION_NAME, null, Role.EDM_TYPE_NAME, ROLE_NAME, null, masterToken, -1); // Cell1のExtCellとRelationの削除 - LinksUtils.deleteLinksExtCell(CELL_NAME1, PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot(CELL_NAME2)), + LinksUtils.deleteLinksExtCell(CELL_NAME1, CommonUtils.encodeUrlComp(UrlUtils.cellRoot(CELL_NAME2)), Relation.EDM_TYPE_NAME, RELATION_NAME, null, masterToken, -1); // Cell1のExtRoleを削除する ExtRoleUtils.delete(CELL_NAME1, EXTROLE_NAME1, @@ -754,7 +754,7 @@ public AuthCheckTest() { // extCellとロールの結びつけ LinksUtils.createLinksExtCell(testCellName2, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot(testCellName)), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot(testCellName)), Role.EDM_TYPE_NAME, roleNameWithBox1, boxNameNoneScheme, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_NO_CONTENT); @@ -791,7 +791,7 @@ public AuthCheckTest() { // ロールとextCellの結びつけ削除 LinksUtils.deleteLinksExtCell(testCellName2, - PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot(testCellName)), + CommonUtils.encodeUrlComp(UrlUtils.cellRoot(testCellName)), Role.EDM_TYPE_NAME, roleNameWithBox1, boxNameNoneScheme, AbstractCase.MASTER_TOKEN_NAME, -1); // ExtCell削除 @@ -1071,9 +1071,9 @@ private List checkTransCellAccessToken(final String tokenAuthCellName, fin JSONObject json2 = res2.bodyAsJson(); String localToken2 = (String) json2.get(OAuth2Helper.Key.ACCESS_TOKEN); - CellLocalAccessToken aToken = null; + VisitorLocalAccessToken aToken = null; try { - aToken = CellLocalAccessToken.parse(localToken2, UrlUtils.cellRoot(tokenAuthCellName)); + aToken = VisitorLocalAccessToken.parse(localToken2, UrlUtils.cellRoot(tokenAuthCellName)); } catch (TokenParseException e) { fail(); } diff --git a/src/test/java/io/personium/test/jersey/cell/auth/AuthCookieTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthCookieTest.java index 087f1e1bf..2575e3995 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/AuthCookieTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/AuthCookieTest.java @@ -328,7 +328,7 @@ public AuthCookieTest() { // 期限切れでないトークンを生成 TransCellAccessToken validToken = new TransCellAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR + MILLISECS_IN_AN_MINITE, - issuer, subject, target, roleList, schema); + issuer, subject, target, roleList, schema, new String[] {"scope"}); // セルに対してトークン認証 TResponse passRes = Http.request("authn/issue-cookie-with-saml.txt") .with("remoteCell", LOCAL_CELL) @@ -377,7 +377,7 @@ public AuthCookieTest() { // 期限切れでないトークンを生成 TransCellAccessToken validToken = new TransCellAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR + MILLISECS_IN_AN_MINITE, - issuer, subject, target, roleList, schema); + issuer, subject, target, roleList, schema, new String[] {"scope"}); // セルに対してトークン認証 TResponse passRes = Http.request("authn/issue-cookie-with-saml.txt") .with("remoteCell", LOCAL_CELL) @@ -568,7 +568,7 @@ public AuthCookieTest() { // ACL作成 DavResourceUtils.setACLwithRoleBaseUrl(AbstractCase.MASTER_TOKEN_NAME, TEST_CELL1, boxName, colName, - "none", UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, "role2"), "", + "none", UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, "role2"), "", HttpStatus.SC_OK); // パスワード認証要求、クッキーを取得 @@ -607,7 +607,7 @@ public AuthCookieTest() { // ACL作成 DavResourceUtils.setACLwithRoleBaseUrl(AbstractCase.MASTER_TOKEN_NAME, TEST_CELL1, boxName, colName, - "none", UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, "role2"), "", + "none", UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, "role2"), "", HttpStatus.SC_OK); // パスワード認証要求、クッキーを取得 @@ -660,7 +660,7 @@ public AuthCookieTest() { // ACL作成 DavResourceUtils.setACLwithRoleBaseUrl(AbstractCase.MASTER_TOKEN_NAME, TEST_CELL1, boxName, colName, - "none", UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, "role1"), "", + "none", UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, "role1"), "", HttpStatus.SC_OK); // パスワード認証要求、クッキーを取得 @@ -701,7 +701,7 @@ public AuthCookieTest() { // ACL作成 DavResourceUtils.setACLwithRoleBaseUrl(AbstractCase.MASTER_TOKEN_NAME, TEST_CELL1, boxName, colName, - "none", UrlUtils.roleResource(TEST_CELL1, Box.DEFAULT_BOX_NAME, "role1"), "", + "none", UrlUtils.roleResource(TEST_CELL1, Box.MAIN_BOX_NAME, "role1"), "", HttpStatus.SC_OK); // パスワード認証要求、クッキーを取得 @@ -901,7 +901,7 @@ private void createTestResource() throws UnsupportedEncodingException { DavResourceUtils.createODataCollection(AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_CREATED, LOCAL_CELL, "box1", "setodata"); DavResourceUtils.setACLwithRoleBaseUrl(AbstractCase.MASTER_TOKEN_NAME, LOCAL_CELL, "box1", "setodata", - "none", UrlUtils.roleResource(LOCAL_CELL, Box.DEFAULT_BOX_NAME, "appadmin"), "", + "none", UrlUtils.roleResource(LOCAL_CELL, Box.MAIN_BOX_NAME, "appadmin"), "", HttpStatus.SC_OK); } diff --git a/src/test/java/io/personium/test/jersey/cell/auth/AuthErrorTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthErrorTest.java index 1e01a9161..6bc35a7e0 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/AuthErrorTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/AuthErrorTest.java @@ -24,7 +24,7 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreAuthnException; import io.personium.core.auth.OAuth2Helper; import io.personium.core.auth.OAuth2Helper.Error; @@ -268,7 +268,7 @@ public AuthErrorTest() { // リフレッシュトークン認証 TResponse tokenRes = Http.request("authn/refresh-cl-with-bearerheader.txt") .with("remoteCell", TEST_CELL1) - .with("Authorization_token", "bearerHeader") + .with("Authorization_token", "invalidBearerHeader") .with("refresh_token", refreshToken) .returns() .statusCode(HttpStatus.SC_BAD_REQUEST) @@ -297,8 +297,8 @@ public AuthErrorTest() { .statusCode(HttpStatus.SC_BAD_REQUEST); AuthTestCommon.checkAuthenticateHeaderNotExists(passRes); - String code = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getCode(); - String message = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getMessage(); + String code = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getCode(); + String message = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getMessage(); String errDesc = String.format("[%s] - %s", code, message); checkErrorResponseBody(passRes, Error.INVALID_CLIENT, errDesc); @@ -310,7 +310,7 @@ public AuthErrorTest() { @Test public final void パスワード認証APIのヘッダにclient_secretの指定がない場合_400が返却されること() { String schemaTransCellAccessTokenHeader = - PersoniumCoreUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), ""); + CommonUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), ""); // セルに対してパスワード認証 TResponse passRes = Http.request("authn/auth-with-header.txt") @@ -321,8 +321,8 @@ public AuthErrorTest() { .statusCode(HttpStatus.SC_BAD_REQUEST); AuthTestCommon.checkAuthenticateHeaderNotExists(passRes); - String code = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getCode(); - String message = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getMessage(); + String code = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getCode(); + String message = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getMessage(); String errDesc = String.format("[%s] - %s", code, message); checkErrorResponseBody(passRes, Error.INVALID_CLIENT, errDesc); @@ -358,8 +358,8 @@ public AuthErrorTest() { .statusCode(HttpStatus.SC_BAD_REQUEST); AuthTestCommon.checkAuthenticateHeaderNotExists(tokenRes); - String code = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getCode(); - String message = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getMessage(); + String code = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getCode(); + String message = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getMessage(); String errDesc = String.format("[%s] - %s", code, message); checkErrorResponseBody(tokenRes, Error.INVALID_CLIENT, errDesc); @@ -384,7 +384,7 @@ public AuthErrorTest() { String transCellAccessToken = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN); String schemaTransCellAccessTokenHeader = - PersoniumCoreUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), ""); + CommonUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), ""); // セルに対してトークン認証 TResponse tokenRes = @@ -397,8 +397,8 @@ public AuthErrorTest() { .statusCode(HttpStatus.SC_BAD_REQUEST); AuthTestCommon.checkAuthenticateHeaderNotExists(tokenRes); - String code = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getCode(); - String message = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getMessage(); + String code = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getCode(); + String message = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getMessage(); String errDesc = String.format("[%s] - %s", code, message); checkErrorResponseBody(tokenRes, Error.INVALID_CLIENT, errDesc); @@ -431,8 +431,8 @@ public AuthErrorTest() { .debug(); AuthTestCommon.checkAuthenticateHeaderNotExists(tokenRes); - String code = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getCode(); - String message = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getMessage(); + String code = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getCode(); + String message = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getMessage(); String errDesc = String.format("[%s] - %s", code, message); checkErrorResponseBody(tokenRes, Error.INVALID_CLIENT, errDesc); @@ -456,7 +456,7 @@ public AuthErrorTest() { String refreshToken = (String) json.get(OAuth2Helper.Key.REFRESH_TOKEN); String schemaTransCellAccessTokenHeader = - PersoniumCoreUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), ""); + CommonUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), ""); // リフレッシュトークン認証 TResponse tokenRes = Http.request("authn/auth-with-header.txt") .with("remoteCell", TEST_CELL1) @@ -467,8 +467,8 @@ public AuthErrorTest() { .debug(); AuthTestCommon.checkAuthenticateHeaderNotExists(tokenRes); - String code = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getCode(); - String message = PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.getMessage(); + String code = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getCode(); + String message = PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.getMessage(); String errDesc = String.format("[%s] - %s", code, message); checkErrorResponseBody(tokenRes, Error.INVALID_CLIENT, errDesc); diff --git a/src/test/java/io/personium/test/jersey/cell/auth/AuthExpiresInTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthExpiresInTest.java index e88612139..3f15314ed 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/AuthExpiresInTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/AuthExpiresInTest.java @@ -261,11 +261,11 @@ public final void receiveRefresh() throws Exception { } /** - * Test if receiveCord. + * Test if receiveCode. * @throws Exception Unexpected exception */ @Test - public final void receiveCord() throws Exception { + public final void receiveCode() throws Exception { // authz endpoint. String clientId = UrlUtils.cellRoot(Setup.TEST_CELL_SCHEMA1); String redirectUri = clientId + "__/redirect.html"; diff --git a/src/test/java/io/personium/test/jersey/cell/auth/AuthTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthTest.java index 0b47d5e80..65036bcaf 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/AuthTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/AuthTest.java @@ -37,13 +37,12 @@ import io.personium.common.auth.token.AbstractOAuth2Token.TokenDsigException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenRootCrtException; -import io.personium.common.auth.token.AccountAccessToken; -import io.personium.common.auth.token.CellLocalAccessToken; -import io.personium.common.auth.token.CellLocalRefreshToken; +import io.personium.common.auth.token.VisitorLocalAccessToken; +import io.personium.common.auth.token.ResidentRefreshToken; import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; -import io.personium.common.auth.token.TransCellRefreshToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.auth.token.VisitorRefreshToken; +import io.personium.common.utils.CommonUtils; import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.ctl.Relation; import io.personium.core.rs.PersoniumCoreApplication; @@ -125,7 +124,7 @@ public class AuthTest extends PersoniumTest { static final int READ_PROP = 7; /** - * コンストラクタ. + * Constructor. */ public AuthTest() { super(new PersoniumCoreApplication()); @@ -135,7 +134,7 @@ public AuthTest() { * 4.パスワード認証ー自分セルトークン取得. */ @Test - public final void パスワード認証ー自分セルトークン取得Box() { + public final void C04_パスワード認証ー自分セルトークン取得Box() { // このテストの流れ // testcell1 => testcell1 // パスワード認証 セルローカルでデータアクセス @@ -151,7 +150,7 @@ public AuthTest() { * 4.パスワード認証ー自分セルトークン取得davcol. */ @Test - public final void パスワード認証ー自分セルトークン取得davcol() { + public final void C04_パスワード認証ー自分セルトークン取得davcol() { HashMap token = new HashMap(); HashMap refreshToken = new HashMap(); AuthTestCommon.accountAuth(TEST_CELL1, token, refreshToken); @@ -162,7 +161,7 @@ public AuthTest() { * 4.パスワード認証ー自分セルトークン取得ーユーザーOData. */ @Test - public final void パスワード認証ー自分セルトークン取得ーユーザーOData() { + public final void C04_パスワード認証ー自分セルトークン取得ーユーザーOData() { HashMap token = new HashMap(); HashMap refreshToken = new HashMap(); AuthTestCommon.accountAuth(TEST_CELL1, token, refreshToken); @@ -174,7 +173,7 @@ public AuthTest() { * 4.パスワード認証ー自分セルトークン取得ーユーザーDavFileResource. */ @Test - public final void パスワード認証ー自分セルトークン取得ーユーザーDavFileResource() { + public final void C04_パスワード認証ー自分セルトークン取得ーユーザーDavFileResource() { HashMap token = new HashMap(); HashMap refreshToken = new HashMap(); AuthTestCommon.accountAuth(TEST_CELL1, token, refreshToken); @@ -185,7 +184,7 @@ public AuthTest() { * 4.パスワード認証ー自分セルトークン取得ーサービスリソース. */ @Test - public final void パスワード認証ー自分セルトークン取得ーサービスリソース() { + public final void C04_パスワード認証ー自分セルトークン取得ーサービスリソース() { HashMap token = new HashMap(); HashMap refreshToken = new HashMap(); AuthTestCommon.accountAuth(TEST_CELL1, token, refreshToken); @@ -196,7 +195,7 @@ public AuthTest() { * 4.パスワード認証ー自分セルトークン取得ーNullResource. */ @Test - public final void パスワード認証ー自分セルトークン取得ーNullResource() { + public final void C04_パスワード認証ー自分セルトークン取得ーNullResource() { HashMap token = new HashMap(); HashMap refreshToken = new HashMap(); AuthTestCommon.accountAuth(TEST_CELL1, token, refreshToken); @@ -207,7 +206,7 @@ public AuthTest() { * 2.パスワード認証ートランセルトークン取得. */ @Test - public final void パスワード認証ートランセルトークン取得() { + public final void C02_パスワード認証ートランセルトークン取得() { // このテストの流れ // testcell2 => testcell1 // パスワード認証 TCトークンでデータアクセス @@ -224,7 +223,7 @@ public AuthTest() { * @throws UnsupportedEncodingException UnsupportedEncodingException */ @Test - public final void スキーマ付きーパスワード認証ー自分セルトークン取得() throws UnsupportedEncodingException { + public final void C03_スキーマ付きーパスワード認証ー自分セルトークン取得() throws UnsupportedEncodingException { // アプリセルに対して認証 TResponse res = Http.request("authn/password-tc-c0.txt") @@ -249,7 +248,7 @@ public AuthTest() { .statusCode(HttpStatus.SC_OK); String schemaTransCellAccessTokenHeader = - PersoniumCoreUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), + CommonUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), transCellAccessToken); // Authorizationヘッダでスキーマ認証 Http.request("authn/password-cl-ch.txt") @@ -265,7 +264,7 @@ public AuthTest() { * 1.スキーマ付きーパスワード認証ートランセルトークン取得. */ @Test - public final void スキーマ付きーパスワード認証ートランセルトークン取得() { + public final void C01_スキーマ付きーパスワード認証ートランセルトークン取得() { // アプリセルに対して認証 TResponse res = Http.request("authn/password-tc-c0.txt") @@ -290,7 +289,7 @@ public AuthTest() { .statusCode(HttpStatus.SC_OK); String schemaTransCellAccessTokenHeader = - PersoniumCoreUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), + CommonUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); // Authorizationヘッダでスキーマ認証 Http.request("authn/password-cl-ch.txt") @@ -306,7 +305,7 @@ public AuthTest() { * 6.トークン認証ートランセルトークン取得_アクセス制御. */ @Test - public final void トークン認証ートランセルトークン取得_アクセス制御() { + public final void C06_トークン認証ートランセルトークン取得_アクセス制御() { // このテストの流れ // testcell2 => testcell1 => testcell2 => testcell1 => testcell1 // パスワード認証 TCトークン1 TCトークン2 TCトークン3 セルローカルでデータアクセス @@ -335,8 +334,8 @@ public AuthTest() { * 6.トークン認証ートランセルトークン取得_トークン発行のテスト. */ @Test - public final void トークン認証ートランセルトークン取得_トークン発行のテスト() { - // セルに対してパスワード認証 + public final void C06_トークン認証ートランセルトークン取得_トークン発行のテスト() { + // ROPC at "testcell1" targeting "testcell2" TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_CELL1) @@ -364,7 +363,7 @@ public AuthTest() { */ @Test public final void トークン認証ートランセルトークン取得_localunitスキーム宛のトークン発行できること() { - // TEST_CELL1のパスワード認証にてTEST_CELL2宛トークンを発行 + // ROPC at "testcell1" targeting "testcell2" TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_CELL1) @@ -394,29 +393,30 @@ public AuthTest() { public final void ターゲットhttp外部セルのurlがlocalunitの場合でもトークン発行できること_外部セルにロールが直接わりあてられている場合() { String httpCell1Url = UrlUtils.cellRoot(TEST_CELL1); String httpCell2Url = UrlUtils.cellRoot(TEST_CELL2); - String localunitCell1Url = "personium-localunit:/" + TEST_CELL1 + "/"; + String localunitCell1Url = "personium-localunit:" + TEST_CELL1 + ":/"; String transCellAccessToken = null; String testfile = "testfile.txt"; String testrole = "transCellTestRole"; String roleUrl = UrlUtils.roleUrl(TEST_CELL2, null, testrole); - // main box を使用(box1にはACL設定がありテストには不適切であるため) + // use main box (box1 has ACL settings and not suitable for testing) String testBox = "__"; - // dcTargetの値がhttpの場合 + // When p_target is http URL try { - // テスト準備 (MASTER_TOKENで実施) - // 1.ExtCell更新 - // Setupでセル2に外部セルとして登録されているセル1のhttpのURLをpersonium-localunitに一時的に更新。 + // Preparing Test (with MASTER_TOKEN) + // 1. Update ExtCell + // temporarily update the preregistered (by Setup) ExtCell entry on cell 2 that points to cell 1 + // using http URL, so that it will point to the same cell but using personium-localunit scheme. ExtCellUtils.update(MASTER_TOKEN, TEST_CELL2, httpCell1Url, localunitCell1Url, HttpStatus.SC_NO_CONTENT); - // Role作成 + // Create Role RoleUtils.create(TEST_CELL2, MASTER_TOKEN, testrole, HttpStatus.SC_CREATED); // 2.セル2の設定として、この外部セルにロール1を割当。 // Setupで作成されたrole1を紐づけ。 Http.request("cell/link-extCell-role.txt") .with("cellPath", TEST_CELL2) - .with("cellName", PersoniumCoreUtils.encodeUrlComp(localunitCell1Url)) + .with("cellName", CommonUtils.encodeUrlComp(localunitCell1Url)) .with("token", MASTER_TOKEN) .with("roleUrl", roleUrl) .returns().statusCode(HttpStatus.SC_NO_CONTENT); @@ -497,7 +497,7 @@ public AuthTest() { .with("sourceEntity", "Role") .with("sourceKey", "'" + testrole + "'") .with("navPropName", "_ExtCell") - .with("navPropKey", "'" + PersoniumCoreUtils.encodeUrlComp(localunitCell1Url) + "'") + .with("navPropKey", "'" + CommonUtils.encodeUrlComp(localunitCell1Url) + "'") .with("token", "Bearer " + MASTER_TOKEN) .with("ifMatch", "*") .returns(); @@ -518,7 +518,7 @@ public AuthTest() { public final void 外部セルのurlがlocalunitの場合でもトークン発行できること_外部セルにリレーションが割り当てられさらにリレーションにロールが割り当てられている場合() { String httpCell1Url = UrlUtils.cellRoot(TEST_CELL1); String httpCell2Url = UrlUtils.cellRoot(TEST_CELL2); - String localunitCell1Url = "personium-localunit:/" + TEST_CELL1 + "/"; + String localunitCell1Url = "personium-localunit:" + TEST_CELL1 + ":/"; String transCellAccessToken = null; String testfile = "testfile.txt"; String testrole = "transCellTestRole"; @@ -526,7 +526,7 @@ public AuthTest() { // main box を使用(box1にはACL設定がありテストには不適切であるため) String testBox = "__"; - // dcTargetの値がhttpの場合 + // When p_target URL is http try { // テスト準備 (MASTER_TOKENで実施) // 1.ExtCell更新 @@ -544,7 +544,7 @@ public AuthTest() { RelationUtils.create(TEST_CELL2, MASTER_TOKEN, body, HttpStatus.SC_CREATED); // Cell1のExtCellとRelationを結びつけ - LinksUtils.createLinksExtCell(TEST_CELL2, PersoniumCoreUtils.encodeUrlComp(localunitCell1Url), + LinksUtils.createLinksExtCell(TEST_CELL2, CommonUtils.encodeUrlComp(localunitCell1Url), Relation.EDM_TYPE_NAME, testrelation, null, MASTER_TOKEN, HttpStatus.SC_NO_CONTENT); // Cell1のRelationとRoleを結びつけ LinksUtils.createLinks(TEST_CELL2, Relation.EDM_TYPE_NAME, testrelation, null, @@ -625,7 +625,7 @@ public AuthTest() { Role.EDM_TYPE_NAME, testrole, null, MASTER_TOKEN, -1); // Cell1のExtCellとRelationの削除 - LinksUtils.deleteLinksExtCell(TEST_CELL2, PersoniumCoreUtils.encodeUrlComp(localunitCell1Url), + LinksUtils.deleteLinksExtCell(TEST_CELL2, CommonUtils.encodeUrlComp(localunitCell1Url), Relation.EDM_TYPE_NAME, testrelation, null, MASTER_TOKEN, -1); // Cell1のRelationを削除 @@ -664,7 +664,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 8.トークン認証ー他人セルトークン取得_アクセス制御. */ @Test - public final void トークン認証ー他人セルトークン取得_アクセス制御() { + public final void C08_トークン認証ー他人セルトークン取得_アクセス制御() { // このテストの流れ // testcell2 => testcell1 => testcell1 // パスワード認証 TCトークン セルローカルでアクセス @@ -684,8 +684,8 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 8.トークン認証ー他人セルトークン取得_トークン発行のテスト. */ @Test - public final void トークン認証ー他人セルトークン取得_トークン発行のテスト() { - // セルに対してパスワード認証 + public final void C08_トークン認証ー他人セルトークン取得_トークン発行のテスト() { + // ROPC at "testcell1" targeting "testcell2" TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_CELL1) @@ -711,8 +711,8 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 5.スキーマ付きートークン認証ートランセルトークン取得. */ @Test - public final void スキーマ付きートークン認証ートランセルトークン取得() { - // セルに対してパスワード認証 + public final void C05_スキーマ付きートークン認証ートランセルトークン取得() { + // ROPC at "testcell1" targeting "testcell2" TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_CELL1) @@ -748,7 +748,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .statusCode(HttpStatus.SC_OK); String schemaTransCellAccessTokenHeader = - PersoniumCoreUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), + CommonUtils.createBasicAuthzHeader(UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); // Authorizationヘッダでスキーマ認証 Http.request("authn/saml-cl-ch.txt") @@ -763,8 +763,8 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 7.スキーマ認証ートークン取得ー他人セルトークン. */ @Test - public final void スキーマ認証ートークン取得ー他人セルトークン() { - // セルに対してパスワード認証 + public final void C07_スキーマ認証ートークン取得ー他人セルトークン() { + // ROPC at "testcell1" targeting "testcell2" TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_CELL1) @@ -800,7 +800,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .returns() .statusCode(HttpStatus.SC_OK); - String schemaTransCellAccessTokenHeader = PersoniumCoreUtils.createBasicAuthzHeader( + String schemaTransCellAccessTokenHeader = CommonUtils.createBasicAuthzHeader( UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); @@ -818,7 +818,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 10.パスワード認証リフレッシュトークンートランセル_アクセス制御. */ @Test - public final void パスワード認証リフレッシュトークンートランセル_アクセス制御() { + public final void C10_パスワード認証リフレッシュトークンートランセル_アクセス制御() { // このテストの流れ // testcell2 => testcell2 => testcell1 // パスワード認証 リフレッシュ TCトークンでデータアクセス @@ -837,12 +837,12 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 10.パスワード認証リフレッシュトークンートランセル_トークン発行のテスト. */ @Test - public final void パスワード認証リフレッシュトークンートランセル_トークン発行のテスト() { + public final void C10_パスワード認証リフレッシュトークンートランセル_トークン発行のテスト() { try { // セルに対してパスワード認証 JSONObject json = ResourceUtils.getLocalTokenByPassAuth(TEST_CELL1, "account1", "password1", -1); String refreshToken = (String) json.get(OAuth2Helper.Key.REFRESH_TOKEN); - CellLocalRefreshToken rCellLocalToken = CellLocalRefreshToken.parse(refreshToken, + ResidentRefreshToken rCellLocalToken = ResidentRefreshToken.parse(refreshToken, UrlUtils.cellRoot(TEST_CELL1)); // リフレッシュトークンの作成時にミリ秒を秒に丸めてトークン文字列化しているため1秒停止 @@ -860,7 +860,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .returns() .statusCode(HttpStatus.SC_OK); String refreshToken2 = (String) res.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); - CellLocalRefreshToken rCellLocalToken2 = CellLocalRefreshToken.parse(refreshToken2, + ResidentRefreshToken rCellLocalToken2 = ResidentRefreshToken.parse(refreshToken2, UrlUtils.cellRoot(TEST_CELL1)); // リフレッシュトークンが更新されている事をチェック @@ -880,7 +880,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 12.パスワード認証リフレッシュトークンー自セルトークン_アクセス制御. */ @Test - public final void パスワード認証リフレッシュトークンー自セルトークン_アクセス制御() { + public final void C12_パスワード認証リフレッシュトークンー自セルトークン_アクセス制御() { // このテストの流れ // testcell1 => testcell1 => testcell1 // パスワード認証 リフレッシュ セルローカルでデータアクセス @@ -900,12 +900,12 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 12.パスワード認証リフレッシュトークンー自セルトークン_トークン発行のテスト. */ @Test - public final void パスワード認証リフレッシュトークンー自セルトークン_トークン発行のテスト() { + public final void C12_パスワード認証リフレッシュトークンー自セルトークン_トークン発行のテスト() { try { // セルに対してパスワード認証 JSONObject json = ResourceUtils.getLocalTokenByPassAuth(TEST_CELL1, "account1", "password1", -1); String refreshToken = (String) json.get(OAuth2Helper.Key.REFRESH_TOKEN); - CellLocalRefreshToken rCellLocalToken = CellLocalRefreshToken.parse(refreshToken, + ResidentRefreshToken rCellLocalToken = ResidentRefreshToken.parse(refreshToken, UrlUtils.cellRoot(TEST_CELL1)); // リフレッシュトークンの作成時にミリ秒を秒に丸めてトークン文字列化しているため1秒停止 @@ -922,7 +922,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .returns() .statusCode(HttpStatus.SC_OK); String refreshToken2 = (String) res.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); - CellLocalRefreshToken rCellLocalToken2 = CellLocalRefreshToken.parse(refreshToken2, + ResidentRefreshToken rCellLocalToken2 = ResidentRefreshToken.parse(refreshToken2, UrlUtils.cellRoot(TEST_CELL1)); // リフレッシュトークンが更新されている事をチェック @@ -943,9 +943,9 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 9.スキーマ付きパスワード認証リフレッシュトークンートランセル. */ @Test - public final void スキーマ付きパスワード認証リフレッシュトークンートランセル() { + public final void C09_スキーマ付きパスワード認証リフレッシュトークンートランセル() { try { - // アプリセルに対して認証 + // App Auth at "schema1" TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_APP_CELL1) @@ -957,7 +957,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String JSONObject json = res.bodyAsJson(); String transCellAccessToken = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN); - // Queryでスキーマ認証 + // ROPC at "testcell1" with app auth (body) TResponse res2 = Http.request("authn/password-cl-cp.txt") .with("remoteCell", TEST_CELL1) .with("username", "account1") @@ -968,7 +968,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .statusCode(HttpStatus.SC_OK); String refreshToken = (String) res2.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); - CellLocalRefreshToken rCellLocalToken = CellLocalRefreshToken.parse(refreshToken, + ResidentRefreshToken rCellLocalToken = ResidentRefreshToken.parse(refreshToken, UrlUtils.cellRoot(TEST_CELL1)); // リフレッシュトークンの作成時にミリ秒を秒に丸めてトークン文字列化しているため1秒停止 @@ -978,16 +978,18 @@ private TResponse resetAcl(String cellName, String boxName, String token, String fail(); } - // アプリセルに対して認証 + // refresh without app auth should fail TResponse res3 = - Http.request("authn/refresh-tc.txt") + Http.request("authn/refresh-tc-cp.txt") .with("remoteCell", TEST_CELL1) .with("refresh_token", refreshToken) + .with("client_id", UrlUtils.cellRoot(TEST_APP_CELL1)) + .with("client_secret", transCellAccessToken) .with("p_target", UrlUtils.cellRoot(TEST_CELL2)) .returns() .statusCode(HttpStatus.SC_OK); String refreshToken2 = (String) res3.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); - CellLocalRefreshToken rCellLocalToken2 = CellLocalRefreshToken.parse(refreshToken2, + ResidentRefreshToken rCellLocalToken2 = ResidentRefreshToken.parse(refreshToken2, UrlUtils.cellRoot(TEST_CELL1)); // リフレッシュトークンが更新されている事をチェック @@ -1007,7 +1009,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 11.スキーマ付きパスワード認証リフレッシュトークンー自セルトークン. */ @Test - public final void スキーマ付きパスワード認証リフレッシュトークンー自セルトークン() { + public final void C11_スキーマ付きパスワード認証リフレッシュトークンー自セルトークン() { try { // アプリセルに対して認証 TResponse res = @@ -1033,7 +1035,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .statusCode(HttpStatus.SC_OK); String refreshToken = (String) res2.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); - CellLocalRefreshToken rCellLocalToken = CellLocalRefreshToken.parse(refreshToken, + ResidentRefreshToken rCellLocalToken = ResidentRefreshToken.parse(refreshToken, UrlUtils.cellRoot(TEST_CELL1)); // リフレッシュトークンの作成時にミリ秒を秒に丸めてトークン文字列化しているため1秒停止 @@ -1045,13 +1047,15 @@ private TResponse resetAcl(String cellName, String boxName, String token, String // アプリセルに対して認証 TResponse res3 = - Http.request("authn/refresh-cl.txt") + Http.request("authn/refresh-cl-cp.txt") .with("remoteCell", TEST_CELL1) .with("refresh_token", refreshToken) + .with("client_id", UrlUtils.cellRoot(TEST_APP_CELL1)) + .with("client_secret", transCellAccessToken) .returns() .statusCode(HttpStatus.SC_OK); String refreshToken2 = (String) res3.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); - CellLocalRefreshToken rCellLocalToken2 = CellLocalRefreshToken.parse(refreshToken2, + ResidentRefreshToken rCellLocalToken2 = ResidentRefreshToken.parse(refreshToken2, UrlUtils.cellRoot(TEST_CELL1)); // リフレッシュトークンが更新されている事をチェック @@ -1071,7 +1075,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 14.トークン認証リフレッシュトークンートランセル_アクセス制御. */ @Test - public final void トークン認証リフレッシュトークンートランセル_アクセス制御() { + public final void C14_トークン認証リフレッシュトークンートランセル_アクセス制御() { // このテストの流れ // testcell2 => testcell1 => testcell2 => testcell1 => testcell1 => testcell1 // パスワード認証 TCトークン1 TCトークン2 TCトークン3 リフレッシュ セルローカルでデータアクセス @@ -1104,9 +1108,9 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 14.トークン認証リフレッシュトークンートランセル_トークン発行のテスト. */ @Test - public final void トークン認証リフレッシュトークンートランセル_トークン発行のテスト() { + public final void C14_トークン認証リフレッシュトークンートランセル_トークン発行のテスト() { try { - // セルに対してパスワード認証 + // ROPC at "testcell1" targeting "testcell2" TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_CELL1) @@ -1130,7 +1134,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String JSONObject json2 = res2.bodyAsJson(); String refreshToken = (String) json2.get(OAuth2Helper.Key.REFRESH_TOKEN); - TransCellRefreshToken rToken = TransCellRefreshToken.parse(refreshToken, + VisitorRefreshToken rToken = VisitorRefreshToken.parse(refreshToken, UrlUtils.cellRoot(TEST_CELL2)); // リフレッシュトークンの作成時にミリ秒を秒に丸めてトークン文字列化しているため1秒停止 @@ -1150,7 +1154,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .statusCode(HttpStatus.SC_OK); JSONObject json3 = res3.bodyAsJson(); String refreshToken2 = (String) json3.get(OAuth2Helper.Key.REFRESH_TOKEN); - TransCellRefreshToken rToken2 = TransCellRefreshToken.parse(refreshToken2, + VisitorRefreshToken rToken2 = VisitorRefreshToken.parse(refreshToken2, UrlUtils.cellRoot(TEST_CELL2)); // リフレッシュトークンが更新されている事をチェック @@ -1171,7 +1175,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 16.トークン認証リフレッシュトークンー他人セルトークン_アクセス制御. */ @Test - public final void トークン認証リフレッシュトークンー他人セルトークン_アクセス制御() { + public final void C16_トークン認証リフレッシュトークンー他人セルトークン_アクセス制御() { // このテストの流れ // testcell2 => testcell1 => testcell1 => testcell1 // パスワード認証 TCトークン リフレッシュ セルローカルでデータアクセス @@ -1195,9 +1199,9 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 16.トークン認証リフレッシュトークンー他人セルトークン_トークン発行のテスト. */ @Test - public final void トークン認証リフレッシュトークンー他人セルトークン_トークン発行のテスト() { + public final void C16_トークン認証リフレッシュトークンー他人セルトークン_トークン発行のテスト() { try { - // セルに対してパスワード認証 + // ROPC at "testcell1" targeting "testcell2" TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_CELL1) @@ -1221,7 +1225,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String JSONObject json2 = res2.bodyAsJson(); String refreshToken = (String) json2.get(OAuth2Helper.Key.REFRESH_TOKEN); - TransCellRefreshToken rToken = TransCellRefreshToken.parse(refreshToken, + VisitorRefreshToken rToken = VisitorRefreshToken.parse(refreshToken, UrlUtils.cellRoot(TEST_CELL2)); // Refresh @@ -1233,7 +1237,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .statusCode(HttpStatus.SC_OK); JSONObject json3 = res3.bodyAsJson(); String refreshToken2 = (String) json3.get(OAuth2Helper.Key.REFRESH_TOKEN); - TransCellRefreshToken rToken2 = TransCellRefreshToken.parse(refreshToken2, + VisitorRefreshToken rToken2 = VisitorRefreshToken.parse(refreshToken2, UrlUtils.cellRoot(TEST_CELL2)); // リフレッシュトークンが更新されている事をチェック @@ -1254,9 +1258,9 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 13.スキーマ付きトークン認証リフレッシュトークンートランセル. */ @Test - public final void スキーマ付きトークン認証リフレッシュトークンートランセル() { + public final void C13_スキーマ付きトークン認証リフレッシュトークンートランセル() { try { - // セルに対してパスワード認証 + // ROPC at "testcell1" targeting "testcell2" TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_CELL1) @@ -1269,7 +1273,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String JSONObject json = res.bodyAsJson(); String transCellAccessToken = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN); - // アプリセルに対して認証 + // App Auth at "schema1" TResponse res2 = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_APP_CELL1) @@ -1282,7 +1286,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String JSONObject json2 = res2.bodyAsJson(); String schemaTransCellAccessToken = (String) json2.get(OAuth2Helper.Key.ACCESS_TOKEN); - // Queryでスキーマ認証 + // receive assertion at "testcell2" with app auth TResponse res3 = Http.request("authn/saml-cl-cp.txt") .with("remoteCell", TEST_CELL2) .with("assertion", transCellAccessToken) @@ -1292,7 +1296,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .statusCode(HttpStatus.SC_OK); String refreshToken = (String) res3.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); - TransCellRefreshToken rToken1 = TransCellRefreshToken.parse(refreshToken, + VisitorRefreshToken rToken1 = VisitorRefreshToken.parse(refreshToken, UrlUtils.cellRoot(TEST_CELL2)); // リフレッシュトークンの作成時にミリ秒を秒に丸めてトークン文字列化しているため1秒停止 @@ -1304,14 +1308,16 @@ private TResponse resetAcl(String cellName, String boxName, String token, String // アプリセルに対して認証 TResponse res4 = - Http.request("authn/refresh-tc.txt") + Http.request("authn/refresh-tc-cp.txt") .with("remoteCell", TEST_CELL2) .with("refresh_token", refreshToken) .with("p_target", UrlUtils.cellRoot(TEST_APP_CELL1)) + .with("client_id", UrlUtils.cellRoot(TEST_APP_CELL1)) + .with("client_secret", schemaTransCellAccessToken) .returns() .statusCode(HttpStatus.SC_OK); String refreshToken2 = (String) res4.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); - TransCellRefreshToken rToken2 = TransCellRefreshToken.parse(refreshToken2, + VisitorRefreshToken rToken2 = VisitorRefreshToken.parse(refreshToken2, UrlUtils.cellRoot(TEST_CELL2)); // リフレッシュトークンが更新されている事をチェック @@ -1333,9 +1339,9 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 15.スキーマ付きトークン認証リフレッシュトークンー他人セルトークン. */ @Test - public final void スキーマ付きトークン認証リフレッシュトークンー他人セルトークン() { + public final void C15_スキーマ付きトークン認証リフレッシュトークンー他人セルトークン() { try { - // セルに対してパスワード認証 + // ROPC at "testcell1" targeting at "testcell2" TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_CELL1) @@ -1348,7 +1354,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String JSONObject json = res.bodyAsJson(); String transCellAccessToken = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN); - // アプリセルに対して認証 + // App Auth at "schema1" TResponse res2 = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_APP_CELL1) @@ -1361,7 +1367,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String JSONObject json2 = res2.bodyAsJson(); String schemaTransCellAccessToken = (String) json2.get(OAuth2Helper.Key.ACCESS_TOKEN); - // Queryでスキーマ認証 + // receive assertion at "testcell2" TResponse res3 = Http.request("authn/saml-cl-cp.txt") .with("remoteCell", TEST_CELL2) .with("assertion", transCellAccessToken) @@ -1371,7 +1377,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .statusCode(HttpStatus.SC_OK); String refreshToken = (String) res3.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); - TransCellRefreshToken rToken1 = TransCellRefreshToken.parse(refreshToken, + VisitorRefreshToken rToken1 = VisitorRefreshToken.parse(refreshToken, UrlUtils.cellRoot(TEST_CELL2)); // リフレッシュトークンの作成時にミリ秒を秒に丸めてトークン文字列化しているため1秒停止 @@ -1383,13 +1389,15 @@ private TResponse resetAcl(String cellName, String boxName, String token, String // Refresh TResponse res4 = - Http.request("authn/refresh-cl.txt") + Http.request("authn/refresh-cl-cp.txt") .with("remoteCell", TEST_CELL2) .with("refresh_token", refreshToken) + .with("client_id", UrlUtils.cellRoot(TEST_APP_CELL1)) + .with("client_secret", schemaTransCellAccessToken) .returns() .statusCode(HttpStatus.SC_OK); String refreshToken2 = (String) res4.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); - TransCellRefreshToken rToken2 = TransCellRefreshToken.parse(refreshToken2, + VisitorRefreshToken rToken2 = VisitorRefreshToken.parse(refreshToken2, UrlUtils.cellRoot(TEST_CELL2)); // リフレッシュトークンが更新されている事をチェック @@ -1409,17 +1417,30 @@ private TResponse resetAcl(String cellName, String boxName, String token, String } /** - * 17.スキーマ付き自セルリフレッシュートランスセルトークン. */ @Test - public void スキーマ付き自セルリフレッシュートランスセルトークン() { + public void C17_スキーマ付き自セルリフレッシュートランスセルトークン() { try { - // Authenticate to user cell + // App Auth Token for TEST_CELL1 + TResponse res2 = + Http.request("authn/password-tc-c0.txt") + .with("remoteCell", TEST_APP_CELL1) + .with("username", "account1") + .with("password", "password1") + .with("p_target", UrlUtils.cellRoot(TEST_CELL1)) + .returns() + .statusCode(HttpStatus.SC_OK); + + String schemaTransCellAccessToken = (String) res2.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + + // ROPC at TEST_CELL1 without app auth TResponse res = - Http.request("authn/password-cl-c0.txt") + Http.request("authn/password-cl-cp.txt") .with("remoteCell", TEST_CELL1) .with("username", "account1") .with("password", "password1") + .with("client_id", UrlUtils.cellRoot(TEST_APP_CELL1)) + .with("client_secret", schemaTransCellAccessToken) .returns() .statusCode(HttpStatus.SC_OK); @@ -1433,20 +1454,9 @@ private TResponse resetAcl(String cellName, String boxName, String token, String fail(); } - // Authenticate to app cell - TResponse res2 = - Http.request("authn/password-tc-c0.txt") - .with("remoteCell", TEST_APP_CELL1) - .with("username", "account1") - .with("password", "password1") - .with("p_target", UrlUtils.cellRoot(TEST_CELL1)) - .returns() - .statusCode(HttpStatus.SC_OK); - - String schemaTransCellAccessToken = (String) res2.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); // ------------------------------ - // Schema authentication (body) + // refresh at TEST_CELL1 adding app auth (body) // ------------------------------ TResponse res3 = Http.request("authn/refresh-tc-cp.txt") .with("remoteCell", TEST_CELL1) @@ -1469,9 +1479,9 @@ private TResponse resetAcl(String cellName, String boxName, String token, String assertThat(aToken.getSubject(), is(UrlUtils.cellRoot(TEST_CELL1) + "#account1")); // ------------------------------ - // Schema authentication (header) + // refresh at TEST_CELL1 adding app auth (header) // ------------------------------ - String schemaTransCellAccessTokenHeader = PersoniumCoreUtils.createBasicAuthzHeader( + String schemaTransCellAccessTokenHeader = CommonUtils.createBasicAuthzHeader( UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); res3 = Http.request("authn/refresh-tc-ch.txt") @@ -1502,97 +1512,97 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 18.スキーマ付き自セルリフレッシュー自セルトークン. */ @Test - public void スキーマ付き自セルリフレッシュー自セルトークン() { - try { - // Authenticate to user cell - TResponse res = - Http.request("authn/password-cl-c0.txt") - .with("remoteCell", TEST_CELL1) - .with("username", "account1") - .with("password", "password1") - .returns() - .statusCode(HttpStatus.SC_OK); + public void C18_スキーマ付き自セルリフレッシュー自セルトークン() { + // ROPC "testcell1" without app auth + TResponse res = + Http.request("authn/password-cl-c0.txt") + .with("remoteCell", TEST_CELL1) + .with("username", "account1") + .with("password", "password1") + .returns() + .statusCode(HttpStatus.SC_OK); - String cellAccessToken = (String) res.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); - String refreshToken = (String) res.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); + String cellAccessToken = (String) res.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + String refreshToken = (String) res.bodyAsJson().get(OAuth2Helper.Key.REFRESH_TOKEN); - // One second stop to use the refresh token - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - fail(); - } + // pause to use the refresh token + try { + Thread.sleep(100); + } catch (InterruptedException e) { + fail(); + } - // Authenticate to app cell - TResponse res2 = - Http.request("authn/password-tc-c0.txt") - .with("remoteCell", TEST_APP_CELL1) - .with("username", "account1") - .with("password", "password1") - .with("p_target", UrlUtils.cellRoot(TEST_CELL1)) - .returns() - .statusCode(HttpStatus.SC_OK); + // App Auth at "schema1" cell + TResponse res2 = + Http.request("authn/password-tc-c0.txt") + .with("remoteCell", TEST_APP_CELL1) + .with("username", "account1") + .with("password", "password1") + .with("p_target", UrlUtils.cellRoot(TEST_CELL1)) + .returns() + .statusCode(HttpStatus.SC_OK); - String schemaTransCellAccessToken = (String) res2.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + String schemaTransCellAccessToken = (String) res2.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); - // ------------------------------ - // Schema authentication (body) - // ------------------------------ - TResponse res3 = Http.request("authn/refresh-cl-cp.txt") - .with("remoteCell", TEST_CELL1) - .with("refresh_token", refreshToken) - .with("client_id", UrlUtils.cellRoot(TEST_APP_CELL1)) - .with("client_secret", schemaTransCellAccessToken) - .returns() - .statusCode(HttpStatus.SC_OK); + // ------------------------------ + // Refresh Should fail when added app (body) auth at refresh time + // ------------------------------ + TResponse res3 = Http.request("authn/refresh-cl-cp.txt") + .with("remoteCell", TEST_CELL1) + .with("refresh_token", refreshToken) + .with("client_id", UrlUtils.cellRoot(TEST_APP_CELL1)) + .with("client_secret", schemaTransCellAccessToken) + .returns() + .statusCode(HttpStatus.SC_UNAUTHORIZED); - String cellAccessToken2 = (String) res3.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); +/* String cellAccessToken2 = (String) res3.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); AccountAccessToken aToken = (AccountAccessToken) AccountAccessToken.parse( cellAccessToken2, UrlUtils.cellRoot(TEST_CELL1)); // Token check - assertTrue(!cellAccessToken.equals(cellAccessToken2)); - assertThat(aToken.getIssuer(), is(UrlUtils.cellRoot(TEST_CELL1))); - assertThat(aToken.getSchema(), is(UrlUtils.cellRoot(TEST_APP_CELL1) + "#c")); - assertNull(aToken.getTarget()); - assertThat(aToken.getSubject(), is("account1")); +// assertTrue(!cellAccessToken.equals(cellAccessToken2)); +// assertThat(aToken.getIssuer(), is(UrlUtils.cellRoot(TEST_CELL1))); +// assertThat(aToken.getSchema(), is(UrlUtils.cellRoot(TEST_APP_CELL1) + "#c")); +// assertNull(aToken.getTarget()); +// assertThat(aToken.getSubject(), is("account1")); + * + */ - // ------------------------------ - // Schema authentication (header) - // ------------------------------ - String schemaTransCellAccessTokenHeader = PersoniumCoreUtils.createBasicAuthzHeader( - UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); + // ------------------------------ + // Refresh should fail when added app auth (header) at refresh time. + // ------------------------------ + String schemaTransCellAccessTokenHeader = CommonUtils.createBasicAuthzHeader( + UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); - res3 = Http.request("authn/refresh-cl-ch.txt") - .with("remoteCell", TEST_CELL1) - .with("refresh_token", refreshToken) - .with("base64idpw", schemaTransCellAccessTokenHeader) - .returns() - .statusCode(HttpStatus.SC_OK); + res3 = Http.request("authn/refresh-cl-ch.txt") + .with("remoteCell", TEST_CELL1) + .with("refresh_token", refreshToken) + .with("base64idpw", schemaTransCellAccessTokenHeader) + .returns() + .statusCode(HttpStatus.SC_UNAUTHORIZED); - cellAccessToken2 = (String) res3.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); - aToken = (AccountAccessToken) AccountAccessToken.parse( - cellAccessToken2, UrlUtils.cellRoot(TEST_CELL1)); + /* + cellAccessToken2 = (String) res3.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + aToken = (AccountAccessToken) AccountAccessToken.parse( + cellAccessToken2, UrlUtils.cellRoot(TEST_CELL1)); - // Token check - assertTrue(!cellAccessToken.equals(cellAccessToken2)); - assertThat(aToken.getIssuer(), is(UrlUtils.cellRoot(TEST_CELL1))); - assertThat(aToken.getSchema(), is(UrlUtils.cellRoot(TEST_APP_CELL1) + "#c")); - assertNull(aToken.getTarget()); - assertThat(aToken.getSubject(), is("account1")); + // Token check + assertTrue(!cellAccessToken.equals(cellAccessToken2)); + assertThat(aToken.getIssuer(), is(UrlUtils.cellRoot(TEST_CELL1))); + assertThat(aToken.getSchema(), is(UrlUtils.cellRoot(TEST_APP_CELL1) + "#c")); + assertNull(aToken.getTarget()); + assertThat(aToken.getSubject(), is("account1")); + */ - } catch (TokenParseException e) { - fail(); - } } /** * 19.スキーマ付きトランスセルリフレッシュートランスセルトークン. */ @Test - public void スキーマ付きトランスセルリフレッシュートランスセルトークン() { + public void C19_スキーマ付きトランスセルリフレッシュートランスセルトークン() { try { - // Authenticate to user cell (get TransCellAccessToken) + // ROPC at "testcell1" targeting at "testcell2" without app auth TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_CELL1) @@ -1604,11 +1614,24 @@ private TResponse resetAcl(String cellName, String boxName, String token, String String transCellAccessToken = (String) res.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + // App Auth at "schema1" for "testcell2" + TResponse res3 = + Http.request("authn/password-tc-c0.txt") + .with("remoteCell", TEST_APP_CELL1) + .with("username", "account1") + .with("password", "password1") + .with("p_target", UrlUtils.cellRoot(TEST_CELL2)) + .returns() + .statusCode(HttpStatus.SC_OK); + String schemaTransCellAccessToken = (String) res3.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + // Authenticate to user cell (get TransCellRefreshToken) TResponse res2 = - Http.request("authn/saml-cl-c0.txt") + Http.request("authn/saml-cl-cp.txt") .with("remoteCell", TEST_CELL2) .with("assertion", transCellAccessToken) + .with("client_id", UrlUtils.cellRoot(TEST_APP_CELL1)) + .with("client_secret", schemaTransCellAccessToken) .returns() .statusCode(HttpStatus.SC_OK); String cellAccessToken = (String) res2.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); @@ -1621,20 +1644,9 @@ private TResponse resetAcl(String cellName, String boxName, String token, String fail(); } - // Authenticate to app cell - TResponse res3 = - Http.request("authn/password-tc-c0.txt") - .with("remoteCell", TEST_APP_CELL1) - .with("username", "account1") - .with("password", "password1") - .with("p_target", UrlUtils.cellRoot(TEST_CELL2)) - .returns() - .statusCode(HttpStatus.SC_OK); - - String schemaTransCellAccessToken = (String) res3.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); // ------------------------------ - // Schema authentication (body) + // Refresh at "testcell2" adding app auth (body) // ------------------------------ TResponse res4 = Http.request("authn/refresh-tc-cp.txt") .with("remoteCell", TEST_CELL2) @@ -1657,9 +1669,9 @@ private TResponse resetAcl(String cellName, String boxName, String token, String assertThat(aToken.getSubject(), is(UrlUtils.cellRoot(TEST_CELL1) + "#account1")); // ------------------------------ - // Schema authentication (header) + // Refresh at "testcell2" adding app auth (header) // ------------------------------ - String schemaTransCellAccessTokenHeader = PersoniumCoreUtils.createBasicAuthzHeader( + String schemaTransCellAccessTokenHeader = CommonUtils.createBasicAuthzHeader( UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); res4 = Http.request("authn/refresh-tc-ch.txt") @@ -1690,9 +1702,10 @@ private TResponse resetAcl(String cellName, String boxName, String token, String * 20.スキーマ付きトランスセルリフレッシュー自セルトークン. */ @Test - public void スキーマ付きトランスセルリフレッシュー自セルトークン() { + public void C20_スキーマ付きトランスセルリフレッシュー自セルトークン() { try { - // Authenticate to user cell (get TransCellAccessToken) + + // ROPC at "testcell1" targeting at "testcell2" without app auth TResponse res = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_CELL1) @@ -1704,11 +1717,27 @@ private TResponse resetAcl(String cellName, String boxName, String token, String String transCellAccessToken = (String) res.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); - // Authenticate to user cell (get TransCellRefreshToken) + + // App Auth at "schema1" for "testcell2" + TResponse res3 = + Http.request("authn/password-tc-c0.txt") + .with("remoteCell", TEST_APP_CELL1) + .with("username", "account1") + .with("password", "password1") + .with("p_target", UrlUtils.cellRoot(TEST_CELL2)) + .returns() + .statusCode(HttpStatus.SC_OK); + + String schemaTransCellAccessToken = (String) res3.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); + + + // receive TCAT at "testcell2" TResponse res2 = - Http.request("authn/saml-cl-c0.txt") + Http.request("authn/saml-cl-cp.txt") .with("remoteCell", TEST_CELL2) .with("assertion", transCellAccessToken) + .with("client_id", UrlUtils.cellRoot(TEST_APP_CELL1)) + .with("client_secret", schemaTransCellAccessToken) .returns() .statusCode(HttpStatus.SC_OK); String cellAccessToken = (String) res2.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); @@ -1721,20 +1750,9 @@ private TResponse resetAcl(String cellName, String boxName, String token, String fail(); } - // Authenticate to app cell - TResponse res3 = - Http.request("authn/password-tc-c0.txt") - .with("remoteCell", TEST_APP_CELL1) - .with("username", "account1") - .with("password", "password1") - .with("p_target", UrlUtils.cellRoot(TEST_CELL2)) - .returns() - .statusCode(HttpStatus.SC_OK); - - String schemaTransCellAccessToken = (String) res3.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); // ------------------------------ - // Schema authentication (body) + // Refresh at "testcell2" adding app auth (body) // ------------------------------ TResponse res4 = Http.request("authn/refresh-cl-cp.txt") .with("remoteCell", TEST_CELL2) @@ -1745,7 +1763,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .statusCode(HttpStatus.SC_OK); String cellAccessToken2 = (String) res4.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); - CellLocalAccessToken aToken = (CellLocalAccessToken) CellLocalAccessToken.parse( + VisitorLocalAccessToken aToken = (VisitorLocalAccessToken) VisitorLocalAccessToken.parse( cellAccessToken2, UrlUtils.cellRoot(TEST_CELL2)); // Token check @@ -1756,9 +1774,9 @@ private TResponse resetAcl(String cellName, String boxName, String token, String assertThat(aToken.getSubject(), is(UrlUtils.cellRoot(TEST_CELL1) + "#account1")); // ------------------------------ - // Schema authentication (header) + // Refresh at "testcell2" adding app auth (header) // ------------------------------ - String schemaTransCellAccessTokenHeader = PersoniumCoreUtils.createBasicAuthzHeader( + String schemaTransCellAccessTokenHeader = CommonUtils.createBasicAuthzHeader( UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); res4 = Http.request("authn/refresh-cl-ch.txt") @@ -1769,7 +1787,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .statusCode(HttpStatus.SC_OK); cellAccessToken2 = (String) res4.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); - aToken = (CellLocalAccessToken) CellLocalAccessToken.parse( + aToken = (VisitorLocalAccessToken) VisitorLocalAccessToken.parse( cellAccessToken2, UrlUtils.cellRoot(TEST_CELL2)); // Token check diff --git a/src/test/java/io/personium/test/jersey/cell/auth/AuthzValidIntervalTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthzValidIntervalTest.java index fd3e5f6b2..e38981df3 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/AuthzValidIntervalTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/AuthzValidIntervalTest.java @@ -41,7 +41,7 @@ import org.junit.runner.RunWith; import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; -import io.personium.common.auth.token.AccountAccessToken; +import io.personium.common.auth.token.ResidentLocalAccessToken; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.lock.LockManager; @@ -180,7 +180,7 @@ public final void test_interval_normal() { Map response = UrlUtils.parseFragment(res.getFirstHeader(HttpHeaders.LOCATION)); try { - AccountAccessToken aToken = AccountAccessToken.parse(response.get(OAuth2Helper.Key.ACCESS_TOKEN), + ResidentLocalAccessToken aToken = ResidentLocalAccessToken.parse(response.get(OAuth2Helper.Key.ACCESS_TOKEN), UrlUtils.cellRoot(Setup.TEST_CELL1)); assertNotNull("access token parse error.", aToken); assertEquals(OAuth2Helper.Scheme.BEARER, response.get(OAuth2Helper.Key.TOKEN_TYPE)); diff --git a/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthCellLevelTest.java b/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthCellLevelTest.java index b0c34c8af..730c345cb 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthCellLevelTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthCellLevelTest.java @@ -67,7 +67,7 @@ public class BasicAuthCellLevelTest extends PersoniumTest { + Base64.encodeBase64String(String.format(("%s:%s"), userName, password).getBytes()); /** - * コンストラクタ. + * Constructor. */ public BasicAuthCellLevelTest() { super(new PersoniumCoreApplication()); diff --git a/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthDavCollectionLevelTest.java b/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthDavCollectionLevelTest.java index 4858713b9..2e1efc5d9 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthDavCollectionLevelTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthDavCollectionLevelTest.java @@ -22,7 +22,7 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; -import io.personium.common.auth.token.Role; +import io.personium.core.model.Box; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; @@ -159,12 +159,12 @@ private void fileInShemalessBox() { // スキーマなしのBox直下のファイルにACL設定(Basic認証-成功) DavResourceUtils.setACLwithBox(cellName, tokenForACLWrite, HttpStatus.SC_OK, - boxName, fileName, "box/acl-2role-setting.txt", "role4", "role4", Role.DEFAULT_BOX_NAME, + boxName, fileName, "box/acl-2role-setting.txt", "role4", "role4", Box.MAIN_BOX_NAME, "", "", ""); // スキーマなしのBox直下のファイルにACL設定(Basic認証-失敗) res = DavResourceUtils.setACLwithBox(cellName, invalidToken, HttpStatus.SC_UNAUTHORIZED, - boxName, fileName, "box/acl-2role-setting.txt", "role4", "role4", Role.DEFAULT_BOX_NAME, + boxName, fileName, "box/acl-2role-setting.txt", "role4", "role4", Box.MAIN_BOX_NAME, "", "", ""); AuthTestCommon.checkAuthenticateHeader(res, cellName); @@ -210,16 +210,16 @@ private void fileInMainBox() { try { // メインボックスにACL(read + write)を設定 DavResourceUtils.setACLwithBox(cellName, AbstractCase.BEARER_MASTER_TOKEN, HttpStatus.SC_OK, - Role.DEFAULT_BOX_NAME, "", - "box/acl-2role-setting.txt", "role4", "role4", Role.DEFAULT_BOX_NAME, "", + Box.MAIN_BOX_NAME, "", + "box/acl-2role-setting.txt", "role4", "role4", Box.MAIN_BOX_NAME, "", "", ""); // メインボックス直下にファイル作成(Basic認証-成功) DavResourceUtils.createWebDavFile(cellName, token, "box/dav-put-anyAuthSchema.txt", "hoge", - Role.DEFAULT_BOX_NAME, fileName, HttpStatus.SC_CREATED); + Box.MAIN_BOX_NAME, fileName, HttpStatus.SC_CREATED); // メインボックス直下にファイル作成(Basic認証-失敗) TResponse res = DavResourceUtils.createWebDavFile(cellName, invalidToken, - "box/dav-put-anyAuthSchema.txt", "hoge", Role.DEFAULT_BOX_NAME, fileName, + "box/dav-put-anyAuthSchema.txt", "hoge", Box.MAIN_BOX_NAME, fileName, HttpStatus.SC_UNAUTHORIZED); AuthTestCommon.checkAuthenticateHeader(res, cellName); // 認証失敗のアカウントロックが解除されるのを待ち合わせる @@ -227,57 +227,57 @@ private void fileInMainBox() { // メインボックスにACL(read-acl + write-acl)を設定 DavResourceUtils.setACLwithBox(cellName, AbstractCase.BEARER_MASTER_TOKEN, HttpStatus.SC_OK, - Role.DEFAULT_BOX_NAME, "", - "box/acl-2role-setting.txt", "role7", "role7", Role.DEFAULT_BOX_NAME, "", + Box.MAIN_BOX_NAME, "", + "box/acl-2role-setting.txt", "role7", "role7", Box.MAIN_BOX_NAME, "", "", ""); // メインボックス直下のファイルにACL設定(Basic認証-成功) DavResourceUtils.setACLwithBox(cellName, tokenForACLWrite, HttpStatus.SC_OK, - Role.DEFAULT_BOX_NAME, fileName, "box/acl-2role-setting.txt", "role4", "role4", - Role.DEFAULT_BOX_NAME, "", "", ""); + Box.MAIN_BOX_NAME, fileName, "box/acl-2role-setting.txt", "role4", "role4", + Box.MAIN_BOX_NAME, "", "", ""); // メインボックス直下のファイルにACL設定(Basic認証-失敗) res = DavResourceUtils.setACLwithBox(cellName, invalidToken, HttpStatus.SC_UNAUTHORIZED, - Role.DEFAULT_BOX_NAME, fileName, "box/acl-2role-setting.txt", "role4", "role4", - Role.DEFAULT_BOX_NAME, "", "", ""); + Box.MAIN_BOX_NAME, fileName, "box/acl-2role-setting.txt", "role4", "role4", + Box.MAIN_BOX_NAME, "", "", ""); AuthTestCommon.checkAuthenticateHeader(res, cellName); // 認証失敗のアカウントロックが解除されるのを待ち合わせる AuthTestCommon.waitForIntervalLock(); // メインボックスにACL(read + write)を設定 DavResourceUtils.setACLwithBox(cellName, AbstractCase.BEARER_MASTER_TOKEN, HttpStatus.SC_OK, - Role.DEFAULT_BOX_NAME, "", - "box/acl-2role-setting.txt", "role4", "role4", Role.DEFAULT_BOX_NAME, "", + Box.MAIN_BOX_NAME, "", + "box/acl-2role-setting.txt", "role4", "role4", Box.MAIN_BOX_NAME, "", "", ""); // メインボックス直下のファイルを取得(Basic認証-成功) - DavResourceUtils.getWebDavFile(cellName, token, "box/dav-get-anyAuthSchema.txt", Role.DEFAULT_BOX_NAME, + DavResourceUtils.getWebDavFile(cellName, token, "box/dav-get-anyAuthSchema.txt", Box.MAIN_BOX_NAME, fileName, HttpStatus.SC_OK); // メインボックス直下のファイルを取得(Basic認証-失敗) res = DavResourceUtils.getWebDavFile(cellName, invalidToken, "box/dav-get-anyAuthSchema.txt", - Role.DEFAULT_BOX_NAME, fileName, HttpStatus.SC_UNAUTHORIZED); + Box.MAIN_BOX_NAME, fileName, HttpStatus.SC_UNAUTHORIZED); AuthTestCommon.checkAuthenticateHeader(res, cellName); // 認証失敗のアカウントロックが解除されるのを待ち合わせる AuthTestCommon.waitForIntervalLock(); // メインボックス直下のファイルをPROPFIND(Basic認証-成功) DavResourceUtils.propfind("box/propfind-box-allprop-anyAuthSchema.txt", token, cellName, - Role.DEFAULT_BOX_NAME + "/" + fileName, 1, HttpStatus.SC_MULTI_STATUS); + Box.MAIN_BOX_NAME + "/" + fileName, 1, HttpStatus.SC_MULTI_STATUS); // メインボックス直下のファイルをPROPFIND(Basic認証-失敗) res = DavResourceUtils.propfind("box/propfind-box-allprop-anyAuthSchema.txt", invalidToken, cellName, - Role.DEFAULT_BOX_NAME + "/" + fileName, 1, HttpStatus.SC_UNAUTHORIZED); + Box.MAIN_BOX_NAME + "/" + fileName, 1, HttpStatus.SC_UNAUTHORIZED); AuthTestCommon.checkAuthenticateHeader(res, cellName); // 認証失敗のアカウントロックが解除されるのを待ち合わせる AuthTestCommon.waitForIntervalLock(); // メインボックス直下のファイルをPROPPATCH(Basic認証-成功) - Http.request("box/proppatch.txt").with("cell", cellName).with("box", Role.DEFAULT_BOX_NAME) + Http.request("box/proppatch.txt").with("cell", cellName).with("box", Box.MAIN_BOX_NAME) .with("path", fileName) .with("token", token) .with("author1", "Author1 update") .with("hoge", "fuga") .returns().statusCode(HttpStatus.SC_MULTI_STATUS); // メインボックス直下のファイルをPROPPATCH(Basic認証-失敗) - res = Http.request("box/proppatch.txt").with("cell", cellName).with("box", Role.DEFAULT_BOX_NAME) + res = Http.request("box/proppatch.txt").with("cell", cellName).with("box", Box.MAIN_BOX_NAME) .with("path", fileName) .with("token", invalidToken) .with("author1", "Author1 update") @@ -289,30 +289,30 @@ private void fileInMainBox() { // メインボックス直下のファイルを変名(Basic認証-成功) String dstFileName = "dstFileName"; - String destinationPath = UrlUtils.box(cellName, Role.DEFAULT_BOX_NAME, dstFileName); - DavResourceUtils.moveWebDavWithAnyAuthSchema(token, cellName, Role.DEFAULT_BOX_NAME + "/" + fileName, + String destinationPath = UrlUtils.box(cellName, Box.MAIN_BOX_NAME, dstFileName); + DavResourceUtils.moveWebDavWithAnyAuthSchema(token, cellName, Box.MAIN_BOX_NAME + "/" + fileName, destinationPath, HttpStatus.SC_CREATED); - String originalPath = UrlUtils.box(cellName, Role.DEFAULT_BOX_NAME, fileName); - DavResourceUtils.moveWebDav(AbstractCase.MASTER_TOKEN_NAME, cellName, Role.DEFAULT_BOX_NAME + "/" + String originalPath = UrlUtils.box(cellName, Box.MAIN_BOX_NAME, fileName); + DavResourceUtils.moveWebDav(AbstractCase.MASTER_TOKEN_NAME, cellName, Box.MAIN_BOX_NAME + "/" + dstFileName, originalPath, -1); // メインボックス直下のファイルをMOVE(Basic認証-失敗) - DavResourceUtils.moveWebDavWithAnyAuthSchema(invalidToken, cellName, Role.DEFAULT_BOX_NAME + "/" + DavResourceUtils.moveWebDavWithAnyAuthSchema(invalidToken, cellName, Box.MAIN_BOX_NAME + "/" + fileName, destinationPath, HttpStatus.SC_UNAUTHORIZED); // 認証失敗のアカウントロックが解除されるのを待ち合わせる AuthTestCommon.waitForIntervalLock(); // メインボックス直下のファイルを削除(Basic認証-成功) DavResourceUtils.deleteWebDavFile("box/dav-delete-anyAuthSchema.txt", cellName, token, - fileName, HttpStatus.SC_NO_CONTENT, Role.DEFAULT_BOX_NAME); + fileName, HttpStatus.SC_NO_CONTENT, Box.MAIN_BOX_NAME); // メインボックス直下のファイルを削除(Basic認証-失敗) res = DavResourceUtils.deleteWebDavFile("box/dav-delete-anyAuthSchema.txt", cellName, invalidToken, - fileName, HttpStatus.SC_UNAUTHORIZED, Role.DEFAULT_BOX_NAME); + fileName, HttpStatus.SC_UNAUTHORIZED, Box.MAIN_BOX_NAME); AuthTestCommon.checkAuthenticateHeader(res, cellName); // 認証失敗のアカウントロックが解除されるのを待ち合わせる AuthTestCommon.waitForIntervalLock(); } finally { DavResourceUtils.deleteWebDavFile("box/dav-delete.txt", cellName, AbstractCase.MASTER_TOKEN_NAME, fileName, - -1, Role.DEFAULT_BOX_NAME); + -1, Box.MAIN_BOX_NAME); } } @@ -364,11 +364,11 @@ private void davCollectionInSchemalessBox() { // コレクションACL設定(Basic認証-成功) DavResourceUtils.setACLwithBox(cellName, tokenForACLWrite, HttpStatus.SC_OK, - boxName, thisMethodColName, "box/acl-2role-setting.txt", "role4", "role4", Role.DEFAULT_BOX_NAME, + boxName, thisMethodColName, "box/acl-2role-setting.txt", "role4", "role4", Box.MAIN_BOX_NAME, "", "", ""); // コレクションACL設定(Basic認証-失敗) res = DavResourceUtils.setACLwithBox(cellName, invalidToken, HttpStatus.SC_UNAUTHORIZED, - boxName, thisMethodColName, "box/acl-2role-setting.txt", "role4", "role4", Role.DEFAULT_BOX_NAME, + boxName, thisMethodColName, "box/acl-2role-setting.txt", "role4", "role4", Box.MAIN_BOX_NAME, "", "", ""); AuthTestCommon.checkAuthenticateHeader(res, cellName); // 認証失敗のアカウントロックが解除されるのを待ち合わせる @@ -455,13 +455,13 @@ private void fileInSchemalessBoxCollection() { // ファイルにACL設定(Basic認証-成功) DavResourceUtils.setACLwithBox(cellName, tokenForACLWrite, HttpStatus.SC_OK, boxName, colName + "/" + fileName, "box/acl-2role-setting.txt", "role4", "role4", - Role.DEFAULT_BOX_NAME, + Box.MAIN_BOX_NAME, "", "", ""); // ファイルにACL設定(Basic認証-失敗) res = DavResourceUtils.setACLwithBox(cellName, invalidToken, HttpStatus.SC_UNAUTHORIZED, boxName, colName + "/" + fileName, "box/acl-2role-setting.txt", "role4", "role4", - Role.DEFAULT_BOX_NAME, + Box.MAIN_BOX_NAME, "", "", ""); AuthTestCommon.checkAuthenticateHeader(res, cellName); diff --git a/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthSvcCollectionLevelTest.java b/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthSvcCollectionLevelTest.java index 208559ea8..96ded8242 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthSvcCollectionLevelTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/BasicAuthSvcCollectionLevelTest.java @@ -29,7 +29,7 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; -import io.personium.common.auth.token.Role; +import io.personium.core.model.Box; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; @@ -132,11 +132,11 @@ private void svcCollectionValidate() { // コレクションACL設定(Basic認証-成功) DavResourceUtils.setACLwithBox(cellName, tokenForACLWrite, HttpStatus.SC_OK, - boxName, colName, "box/acl-2role-setting.txt", "role4", "role4", Role.DEFAULT_BOX_NAME, + boxName, colName, "box/acl-2role-setting.txt", "role4", "role4", Box.MAIN_BOX_NAME, "", "", ""); // コレクションACL設定(Basic認証-失敗) res = DavResourceUtils.setACLwithBox(cellName, invalidToken, HttpStatus.SC_UNAUTHORIZED, - boxName, colName, "box/acl-2role-setting.txt", "role4", "role4", Role.DEFAULT_BOX_NAME, + boxName, colName, "box/acl-2role-setting.txt", "role4", "role4", Box.MAIN_BOX_NAME, "", "", ""); checkAuthenticateHeaderForSchemalessBoxLevel(res, cellName); // 認証失敗のアカウントロックが解除されるのを待ち合わせる @@ -264,13 +264,13 @@ private void svcSourceValidate() { // ファイルにACL設定(Basic認証-成功) DavResourceUtils.setACLwithBox(cellName, tokenForACLWrite, HttpStatus.SC_METHOD_NOT_ALLOWED, boxName, srcFile, "box/acl-2role-setting.txt", "role4", "role4", - Role.DEFAULT_BOX_NAME, + Box.MAIN_BOX_NAME, "", "", ""); // ファイルにACL設定(Basic認証-失敗) res = DavResourceUtils.setACLwithBox(cellName, invalidToken, HttpStatus.SC_UNAUTHORIZED, boxName, srcFile, "box/acl-2role-setting.txt", "role4", "role4", - Role.DEFAULT_BOX_NAME, + Box.MAIN_BOX_NAME, "", "", ""); checkAuthenticateHeaderForSchemalessBoxLevel(res, cellName); diff --git a/src/test/java/io/personium/test/jersey/cell/auth/ImplicitFlowTest.java b/src/test/java/io/personium/test/jersey/cell/auth/ImplicitFlowTest.java index aa88e962f..87634d079 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/ImplicitFlowTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/ImplicitFlowTest.java @@ -50,7 +50,7 @@ import com.sun.org.apache.xerces.internal.parsers.DOMParser; import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; -import io.personium.common.auth.token.AccountAccessToken; +import io.personium.common.auth.token.ResidentLocalAccessToken; import io.personium.core.PersoniumCoreMessageUtils; import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.lock.LockManager; @@ -136,7 +136,7 @@ public final void normal() { // {redirect_uri}#access_token={access_token}&token_type=Bearer&expires_in={expires_in}&state={state} Map response = UrlUtils.parseFragment(res.getFirstHeader(HttpHeaders.LOCATION)); try { - AccountAccessToken aToken = AccountAccessToken.parse(response.get(OAuth2Helper.Key.ACCESS_TOKEN), + ResidentLocalAccessToken aToken = ResidentLocalAccessToken.parse(response.get(OAuth2Helper.Key.ACCESS_TOKEN), UrlUtils.cellRoot(Setup.TEST_CELL1)); assertNotNull("access token parse error.", aToken); assertEquals(OAuth2Helper.Scheme.BEARER, response.get(OAuth2Helper.Key.TOKEN_TYPE)); @@ -413,7 +413,7 @@ public final void cancel() { // {redirect_uri}#access_token={access_token}&token_type=Bearer&expires_in={expires_in}&state={state} Map response = UrlUtils.parseFragment(res.getFirstHeader(HttpHeaders.LOCATION)); try { - AccountAccessToken aToken = AccountAccessToken.parse(response.get(OAuth2Helper.Key.ACCESS_TOKEN), + ResidentLocalAccessToken aToken = ResidentLocalAccessToken.parse(response.get(OAuth2Helper.Key.ACCESS_TOKEN), UrlUtils.cellRoot(Setup.TEST_CELL1)); assertNotNull("access token parse error.", aToken); assertEquals(OAuth2Helper.Scheme.BEARER, response.get(OAuth2Helper.Key.TOKEN_TYPE)); diff --git a/src/test/java/io/personium/test/jersey/cell/auth/MyPasswordTest.java b/src/test/java/io/personium/test/jersey/cell/auth/MyPasswordTest.java index 1f24ed3d9..73ca9e1c4 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/MyPasswordTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/MyPasswordTest.java @@ -1,6 +1,6 @@ /** - * personium.io - * Copyright 2014 FUJITSU LIMITED + * Personium + * Copyright 2014-2019 FUJITSU LIMITED * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,25 +19,39 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import java.io.IOException; +import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import javax.ws.rs.core.HttpHeaders; +import org.apache.commons.io.Charsets; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; -import io.personium.common.auth.token.AccountAccessToken; import io.personium.common.auth.token.PasswordChangeAccessToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.auth.token.ResidentLocalAccessToken; +import io.personium.common.utils.CommonUtils; import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.ctl.Account; import io.personium.core.rs.PersoniumCoreApplication; +import io.personium.core.utils.HttpClientFactory; +import io.personium.core.utils.UriUtils; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; import io.personium.test.categories.Unit; @@ -57,7 +71,7 @@ import io.personium.test.utils.TResponse; /** - * パスワード変更APIのテスト. + * Test for Password change API. */ @RunWith(PersoniumIntegTestRunner.class) @Category({ Unit.class, Integration.class, Regression.class }) @@ -66,25 +80,37 @@ public class MyPasswordTest extends PersoniumTest { private static final String MASTER_TOKEN = AbstractCase.MASTER_TOKEN_NAME; private static final String UNIT_USER_CELL = "unitusercell"; + private String cellUrl; + + /** - * コンストラクタ. + * Constructor. */ public MyPasswordTest() { super(new PersoniumCoreApplication()); } + @Before + public void before() { + String usrCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL1 + ":/"; + this.cellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); + } /** - * 自分セルローカルトークン認証でパスワード変更を実行し204が返ること. - * @throws TokenParseException 認証用トークンのパースエラー + * When accessed with residential Access Token with sufficient scope, then return 204. + * @throws TokenParseException */ @Test - public final void 自分セルローカルトークン認証でパスワード変更を実行し204が返ること() throws TokenParseException { + public final void When_ResidentialAccessTokenWithSufficientScope_Then_Return_204() throws TokenParseException { + String accountName = "PasswordTest"; + String accountPw = "password"; + try { // Account作成 - AccountUtils.create(MASTER_TOKEN, Setup.TEST_CELL1, "PasswordTest", "password", 201); + AccountUtils.create(MASTER_TOKEN, Setup.TEST_CELL1, accountName, accountPw, 201); // 認証 - JSONObject resBody = ResourceUtils.getLocalTokenByPassAuth(Setup.TEST_CELL1, - "PasswordTest", "password", -1); + HttpResponse httpRes = this.httpReqROPC(this.cellUrl, accountName, accountPw, null, null, null, null); + JSONObject resBody = (JSONObject) (new JSONParser()).parse(new InputStreamReader(httpRes.getEntity().getContent(), Charsets.UTF_8)); + // セルローカルトークンを取得する String tokenStr = (String) resBody.get(OAuth2Helper.Key.ACCESS_TOKEN); @@ -100,16 +126,48 @@ public MyPasswordTest() { // 2.変更後のパスワードのセルローカルトークンでアカウントの取得を実行して200となること // 認証 resBody = ResourceUtils.getLocalTokenByPassAuth(Setup.TEST_CELL1, - "PasswordTest", "newPassword", -1); + accountName, "newPassword", -1); // セルローカルトークンを取得する tokenStr = (String) resBody.get(OAuth2Helper.Key.ACCESS_TOKEN); res = requesttoMypassword(tokenStr, "newPassword1", Setup.TEST_CELL1); assertEquals(204, res.getStatusCode()); + } catch (Exception e) { + e.printStackTrace(); } finally { - AccountUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN, "PasswordTest", 204); + AccountUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN, accountName, 204); } } + /** + * When Access Token_Has Insufficient Scope Then Return_403. + * @throws TokenParseException + */ + @Test + public final void When_ResidentialAccessToken_HasInsufficientScope_Then_Return_403() throws TokenParseException { + String accountName = "PasswordTest"; + String accountPw = "password"; + + try { + // Account作成 + AccountUtils.create(MASTER_TOKEN, Setup.TEST_CELL1, accountName, accountPw, 201); + + // 認証 + HttpResponse httpRes = this.httpReqROPC(this.cellUrl, accountName, accountPw, null, "messsage", null, null); + JSONObject resBody = (JSONObject) (new JSONParser()).parse(new InputStreamReader(httpRes.getEntity().getContent(), Charsets.UTF_8)); + // セルローカルトークンを取得する + String tokenStr = (String) resBody.get(OAuth2Helper.Key.ACCESS_TOKEN); + // 確認 + + PersoniumResponse res = requesttoMypassword(tokenStr, "newPassword", Setup.TEST_CELL1); + assertEquals(403, res.getStatusCode()); + } catch (Exception e) { + e.printStackTrace(); + } finally { + AccountUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN, accountName, 204); + } + } + + /** * Test that my password change token authentication can be change the password. * @throws TokenParseException token parse exception. @@ -122,9 +180,15 @@ public final void test_my_password_change_token() throws TokenParseException { AccountUtils.createWithStatus(Setup.MASTER_TOKEN_NAME, Setup.TEST_CELL1, account, account, Account.STATUS_PASSWORD_CHANGE_REQUIRED, HttpStatus.SC_CREATED); // Authenticate - JSONObject resBody = ResourceUtils.getLocalTokenByPassAuth(Setup.TEST_CELL1, - account, account, -1); +// JSONObject resBody = ResourceUtils.getLocalTokenByPassAuth(Setup.TEST_CELL1, +// account, account, -1); + HttpResponse httpRes = this.httpReqROPC(this.cellUrl, account, account, null, null, null, null); + JSONObject resBody = (JSONObject) (new JSONParser()).parse(new InputStreamReader(httpRes.getEntity().getContent(), Charsets.UTF_8)); + System.out.println(resBody.toJSONString()); + String tokenStr = (String) resBody.get(OAuth2Helper.Key.ACCESS_TOKEN); + String scope = (String) resBody.get(OAuth2Helper.Key.SCOPE); + assertTrue(tokenStr.startsWith(PasswordChangeAccessToken.PREFIX_ACCESS)); // Change my password. @@ -134,7 +198,9 @@ public final void test_my_password_change_token() throws TokenParseException { // Authenticate again. resBody = ResourceUtils.getLocalTokenByPassAuth(Setup.TEST_CELL1, account, "newPassword", -1); tokenStr = (String) resBody.get(OAuth2Helper.Key.ACCESS_TOKEN); - assertTrue(tokenStr.startsWith(AccountAccessToken.PREFIX_ACCESS)); + assertTrue(tokenStr.startsWith(ResidentLocalAccessToken.PREFIX_ACCESS)); + } catch (Exception e) { + e.printStackTrace(); } finally { AccountUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN, account, -1); } @@ -450,7 +516,7 @@ private PersoniumResponse requesttoMypassword(String headerAuthorization, String // リクエストヘッダをセット HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, "Bearer " + headerAuthorization); - requestheaders.put(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL, headerCredential); + requestheaders.put(CommonUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL, headerCredential); try { res = rest.put(UrlUtils.cellRoot(requestCellName) + "__mypassword", "", @@ -460,4 +526,39 @@ private PersoniumResponse requesttoMypassword(String headerAuthorization, String } return res; } + + private HttpResponse httpReqROPC(String cellUrl, String username, String password, String pTarget, String scope, + String clientId, String clientSecret) throws ClientProtocolException, IOException { + HttpClient client = HttpClientFactory.create(HttpClientFactory.TYPE_DEFAULT); + + String tokenEndpoint = cellUrl + "__token"; + HttpPost post = new HttpPost(tokenEndpoint); + + StringBuilder sb = new StringBuilder(); + sb.append("grant_type=password&username="); + sb.append(username); + sb.append("&password="); + sb.append(password); + if (pTarget != null) { + sb.append("&p_target="); + sb.append(pTarget); + } + if (scope != null) { + sb.append("&scope="); + sb.append(scope); + } + if (clientId != null) { + sb.append("&client_id="); + sb.append(clientId); + sb.append("&client_secret="); + sb.append(clientSecret); + } + + post.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType()); + post.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()); + + HttpEntity reqEntity = new StringEntity(sb.toString()); + post.setEntity(reqEntity); + return client.execute(post); + } } diff --git a/src/test/java/io/personium/test/jersey/cell/auth/SchemaAuthTest.java b/src/test/java/io/personium/test/jersey/cell/auth/SchemaAuthTest.java index 8c5bf8d0a..bd95966e6 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/SchemaAuthTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/SchemaAuthTest.java @@ -28,9 +28,9 @@ import io.personium.common.auth.token.AbstractOAuth2Token.TokenDsigException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; import io.personium.common.auth.token.AbstractOAuth2Token.TokenRootCrtException; -import io.personium.common.auth.token.AccountAccessToken; -import io.personium.common.auth.token.CellLocalAccessToken; -import io.personium.common.auth.token.CellLocalRefreshToken; +import io.personium.common.auth.token.ResidentLocalAccessToken; +import io.personium.common.auth.token.VisitorLocalAccessToken; +import io.personium.common.auth.token.ResidentRefreshToken; import io.personium.common.auth.token.TransCellAccessToken; import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.Box; @@ -53,7 +53,8 @@ import io.personium.test.utils.UserDataUtils; /** - * スキーマ認証のテスト. + * App auth tests. + * App auth used to be called schema auth. */ @RunWith(PersoniumIntegTestRunner.class) @Category({Unit.class, Integration.class, Regression.class }) @@ -72,7 +73,7 @@ public class SchemaAuthTest extends PersoniumTest { static final String DEFAULT_PRIVILEGE = ""; /** - * コンストラクタ. + * Constructor. */ public SchemaAuthTest() { super(new PersoniumCoreApplication()); @@ -83,7 +84,7 @@ public SchemaAuthTest() { * @throws TokenParseException トークンパースエラー */ @Test - public final void スキーマ無しパスワード認証でセルローカルとリフレッシュトークン() throws TokenParseException { + public final void C00_スキーマ無しROPCでセルローカルとリフレッシュトークン() throws TokenParseException { // 認証 JSONObject json = ResourceUtils.getLocalTokenByPassAuth(TEST_CELL1, "account2", "password2", -1); @@ -91,16 +92,16 @@ public SchemaAuthTest() { // トークンチェック String tokenStr = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN); - AccountAccessToken aToken = AccountAccessToken.parse(tokenStr, issuer); + ResidentLocalAccessToken aToken = ResidentLocalAccessToken.parse(tokenStr, issuer); assertNotNull(aToken.getSchema()); String rTokenStr = (String) json.get(OAuth2Helper.Key.REFRESH_TOKEN); - CellLocalRefreshToken rToken = CellLocalRefreshToken.parse(rTokenStr, issuer); + ResidentRefreshToken rToken = ResidentRefreshToken.parse(rTokenStr, issuer); assertNotNull(rToken.getSchema()); // WebDavのスキーマアクセス制御確認 // 自分セルローカルトークン try { - this.cheacResourcesWithNoneSchema(DAV_COLLECTION, DAV_RESOURCE, tokenStr, TEST_CELL1); + this.checkDavAccessWithoutAppAuth(DAV_COLLECTION, DAV_RESOURCE, tokenStr, TEST_CELL1); } finally { // ACLとスキーマレベル設定を元に戻す this.setAclSchema(Setup.TEST_BOX1, DAV_COLLECTION, OAuth2Helper.SchemaLevel.NONE, TEST_CELL1); @@ -108,60 +109,60 @@ public SchemaAuthTest() { } /** - * リソースに対して、スキーマ無しのトークンでアクセス制御を確認. + * access Dav resources with token without app auth and check the access control. */ - private void cheacResourcesWithNoneSchema(String path, String file, String token, String cellPath) { + private void checkDavAccessWithoutAppAuth(String path, String file, String token, String cellPath) { - // スキーマ設定無し→アクセス可能 - this.cheackResourceSchema(path, file, token, "", HttpStatus.SC_OK, Setup.TEST_BOX1, cellPath); - // スキーマ設定NONE→アクセス可能 - this.cheackResourceSchema(path, file, token, + // Succeed: when p:requireSchemaAuthz does not present + this.checkResourceSchema(path, file, token, "", HttpStatus.SC_OK, Setup.TEST_BOX1, cellPath); + // Succeed: when p:requireSchemaAuthz value is NONE + this.checkResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.NONE, HttpStatus.SC_OK, Setup.TEST_BOX1, cellPath); - // スキーマ設定PUBLIC→アクセス不可 - this.cheackResourceSchema(path, file, token, + // Fail: when p:requireSchemaAuthz value is PUBLIC + this.checkResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.PUBLIC, HttpStatus.SC_FORBIDDEN, Setup.TEST_BOX1, cellPath); - // スキーマ設定CONFIDENTIAL→アクセス不可 - this.cheackResourceSchema(path, file, token, + // Fail: when p:requireSchemaAuthz value is CONFIDENTIAL + this.checkResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.CONFIDENTIAL, HttpStatus.SC_FORBIDDEN, Setup.TEST_BOX1, cellPath); } /** - * リソースに対して、スキーマ付トークンでアクセス制御を確認. + * access Dav resources with token with non confidential app auth and check the access control. */ private void checkResourcesWithSchema(String path, String file, String token, String boxName, String cellPath) { - // スキーマ設定無し→アクセス可能 - this.cheackResourceSchema(path, file, token, "", HttpStatus.SC_OK, boxName, cellPath); - // スキーマ設定NONE→アクセス可能 - this.cheackResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.NONE, HttpStatus.SC_OK, + // Succeed: when p:requireSchemaAuthz does not present + this.checkResourceSchema(path, file, token, "", HttpStatus.SC_OK, boxName, cellPath); + // Succeed: when p:requireSchemaAuthz value is NONE + this.checkResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.NONE, HttpStatus.SC_OK, boxName, cellPath); - // スキーマ設定PUBLIC→アクセス可能 - this.cheackResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.PUBLIC, HttpStatus.SC_OK, + // Succeed: when p:requireSchemaAuthz value is PUBLIC + this.checkResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.PUBLIC, HttpStatus.SC_OK, boxName, cellPath); - // スキーマ設定CONFIDENTIAL→アクセス不可 - this.cheackResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.CONFIDENTIAL, HttpStatus.SC_FORBIDDEN, + // Fail: when p:requireSchemaAuthz value is CONFIDENTIAL + this.checkResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.CONFIDENTIAL, HttpStatus.SC_FORBIDDEN, boxName, cellPath); } /** - * リソースに対していconfidentialRoleスキーマ付トークンでアクセス制御を確認. + * access Dav resources with token with confidentialRole app auth and check the access control. */ private void checkResourcesWithWithConfidentialSchema(String path, String file, String token, String cellPath) { // すべてのスキーマ設定でアクセス可能 - this.cheackResourceSchema(path, file, token, "", HttpStatus.SC_OK, Setup.TEST_BOX1, cellPath); - this.cheackResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.NONE, + this.checkResourceSchema(path, file, token, "", HttpStatus.SC_OK, Setup.TEST_BOX1, cellPath); + this.checkResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.NONE, HttpStatus.SC_OK, Setup.TEST_BOX1, cellPath); - this.cheackResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.PUBLIC, + this.checkResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.PUBLIC, HttpStatus.SC_OK, Setup.TEST_BOX1, cellPath); - this.cheackResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.CONFIDENTIAL, + this.checkResourceSchema(path, file, token, OAuth2Helper.SchemaLevel.CONFIDENTIAL, HttpStatus.SC_OK, Setup.TEST_BOX1, cellPath); } /** * リソースアクセスのスキーマ認証制御の確認. */ - private void cheackResourceSchema(String path, String file, String token, + private void checkResourceSchema(String path, String file, String token, String level, int status, String boxName, String cellPath) { // ACLでスキーマレベル設定 this.setAclSchema(boxName, path, level, cellPath); @@ -170,11 +171,11 @@ private void cheackResourceSchema(String path, String file, String token, } /** - * ACLによるスキーマ設定. - * @param box ボックス名 - * @param path コレクション以下のパス - * @param level スキーマレベル - * @param cellPath セル + * ACL configuration using p:requireSchemaAuthz attribute. + * @param box Box name + * @param path path under box + * @param level requireSchemaAuthz value + * @param cellPath cell path */ private void setAclSchema(String box, String path, String level, String cellPath) { String settingFile = ACL_AUTH_TEST_SETTING_FILE; @@ -212,13 +213,13 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * スキーマ無しパスワード認証でトランスセルトークンのチェック. + * C01_スキーマ無しパスワード認証でトランスセルトークンのチェック. * @throws TokenParseException トークンパースエラー * @throws TokenRootCrtException TokenRootCrtException * @throws TokenDsigException TokenDsigException */ @Test - public final void スキーマ無しパスワード認証でトランスセルトークンのチェック() throws TokenParseException, + public final void C01_スキーマ無しパスワード認証でトランスセルトークンのチェック() throws TokenParseException, TokenDsigException, TokenRootCrtException { // 認証 JSONObject json = getTransTokenByPassAuth("account2", "password2"); @@ -230,11 +231,11 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * スキーマ付パスワード認証でセルローカルとリフレッシュトークン. + * C02_スキーマ付パスワード認証でセルローカルとリフレッシュトークン. * @throws TokenParseException トークンパースエラー */ @Test - public final void スキーマ付パスワード認証でセルローカルとリフレッシュトークン() throws TokenParseException { + public final void C02_スキーマ付パスワード認証でセルローカルとリフレッシュトークン() throws TokenParseException { String tokenStr = checkCellLocalWithSchema("account0", "password0", TEST_APP_CELL1, UrlUtils.cellRoot(TEST_APP_CELL1)); @@ -250,23 +251,23 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * スキーマ付パスワード認証でトランスセルトークンのチェック. + * C03_スキーマ付パスワード認証でトランスセルトークンのチェック. * @throws TokenParseException トークンパースエラー * @throws TokenRootCrtException TokenRootCrtException * @throws TokenDsigException TokenDsigException */ @Test - public final void スキーマ付パスワード認証でトランスセルトークンのチェック() throws TokenParseException, + public final void C03_スキーマ付パスワード認証でトランスセルトークンのチェック() throws TokenParseException, TokenDsigException, TokenRootCrtException { checkTransTokenWithSchema("account0", "password0", UrlUtils.cellRoot(TEST_APP_CELL1)); } /** - * confidentialRoleスキーマ付パスワード認証でセルローカルとリフレッシュトークン. + * C04_confidentialRoleスキーマ付パスワード認証でセルローカルとリフレッシュトークン. * @throws TokenParseException トークンパースエラー */ @Test - public final void confidentialRoleスキーマ付パスワード認証でセルローカルとリフレッシュトークン() throws TokenParseException { + public final void C04_confidentialRoleスキーマ付パスワード認証でセルローカルとリフレッシュトークン() throws TokenParseException { String tokenStr = checkCellLocalWithSchema("account1", "password1", TEST_APP_CELL1, UrlUtils.cellRoot(TEST_APP_CELL1) + OAuth2Helper.Key.CONFIDENTIAL_MARKER); @@ -282,24 +283,24 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * confidentialRoleスキーマ付パスワード認証でトランスセルトークンのチェック. + * C05_confidentialRoleスキーマ付パスワード認証でトランスセルトークンのチェック. * @throws TokenParseException トークンパースエラー * @throws TokenRootCrtException TokenRootCrtException * @throws TokenDsigException TokenDsigException */ @Test - public final void confidentialRoleスキーマ付パスワード認証でトランスセルトークンのチェック() throws TokenParseException, + public final void C05_confidentialRoleスキーマ付パスワード認証でトランスセルトークンのチェック() throws TokenParseException, TokenDsigException, TokenRootCrtException { checkTransTokenWithSchema("account1", "password1", UrlUtils.cellRoot(TEST_APP_CELL1) + OAuth2Helper.Key.CONFIDENTIAL_MARKER); } /** - * スキーマ無しトークン認証でセルローカルトークンのチェック. + * C01_スキーマ無しトークン認証でセルローカルトークンのチェック. * @throws TokenParseException トークンパースエラー */ @Test - public final void スキーマ無しトークン認証でセルローカルトークンのチェック() throws TokenParseException { + public final void C06_スキーマ無しトークン認証でセルローカルトークンのチェック() throws TokenParseException { // 認証 JSONObject json = getTransTokenByPassAuth("account2", "password2"); @@ -315,13 +316,13 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le JSONObject json2 = res2.bodyAsJson(); String tokenStr2 = (String) json2.get(OAuth2Helper.Key.ACCESS_TOKEN); - CellLocalAccessToken aToken = CellLocalAccessToken.parse(tokenStr2, issuer); + VisitorLocalAccessToken aToken = VisitorLocalAccessToken.parse(tokenStr2, issuer); assertNotNull(aToken.getSchema()); // WebDavのスキーマアクセス制御確認 // 自分セルローカルトークン try { - this.cheacResourcesWithNoneSchema(DAV_COLLECTION, DAV_RESOURCE, tokenStr2, TEST_CELL2); + this.checkDavAccessWithoutAppAuth(DAV_COLLECTION, DAV_RESOURCE, tokenStr2, TEST_CELL2); } finally { // ACLとスキーマレベル設定を元に戻す this.setAclSchema(Setup.TEST_BOX1, DAV_COLLECTION, OAuth2Helper.SchemaLevel.NONE, TEST_CELL2); @@ -329,11 +330,11 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * スキーマ付トークン認証でセルローカルトークンのチェック. + * C07_スキーマ付トークン認証でセルローカルトークンのチェック. * @throws TokenParseException トークンパースエラー */ @Test - public final void スキーマ付トークン認証でセルローカルトークンのチェック() throws TokenParseException { + public final void C07_スキーマ付トークン認証でセルローカルトークンのチェック() throws TokenParseException { String tokenStr = cheackTokenAuth("account0", "password0", UrlUtils.cellRoot(TEST_APP_CELL1)); @@ -348,11 +349,11 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * confidentialRoleスキーマ付トークン認証でセルローカルトークンのチェック. + * C08_confidentialRoleスキーマ付トークン認証でセルローカルトークンのチェック. * @throws TokenParseException トークンパースエラー */ @Test - public final void confidentialRoleスキーマ付トークン認証でセルローカルトークンのチェック() throws TokenParseException { + public final void C08_confidentialRoleスキーマ付トークン認証でセルローカルトークンのチェック() throws TokenParseException { String tokenStr = cheackTokenAuth("account1", "password1", UrlUtils.cellRoot(TEST_APP_CELL1) + OAuth2Helper.Key.CONFIDENTIAL_MARKER); @@ -368,11 +369,11 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * スキーマ認証時に無効なトークンを検出した場合401が返ることの確認. + * C09_スキーマ認証時に無効なトークンを検出した場合401が返ることの確認. * @throws TokenParseException トークンパースエラー */ @Test - public final void スキーマ認証時に無効なトークンを検出した場合401が返ることの確認() throws TokenParseException { + public final void C09_スキーマ認証時に無効なトークンを検出した場合401が返ることの確認() throws TokenParseException { // テキトーなトークン String token = "hogeracho"; try { @@ -390,11 +391,11 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * Boxレベル$batchでのスキーマ認証制御の確認. + * C10_Boxレベル$batchでのスキーマ認証制御の確認. * @throws TokenParseException TokenParseException */ @Test - public final void Boxレベル$batchでのスキーマ認証制御の確認() throws TokenParseException { + public final void C10_Boxレベル$batchでのスキーマ認証制御の確認() throws TokenParseException { // スキーマ無しの認証トークン取得 String token = ResourceUtils.getMyCellLocalToken(TEST_CELL1, "account0", "password0"); @@ -423,10 +424,10 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * スキーマレベル設定の継承ー自分の設定が優先されること. + * C11_スキーマレベル設定の継承ー自分の設定が優先されること. */ @Test - public final void スキーマレベル設定の継承ー自分の設定が優先されること() { + public final void C11_スキーマレベル設定の継承ー自分の設定が優先されること() { try { // ACL設定 this.setACL(TEST_BOX1, "", ACL_SETTING_FILE); @@ -466,10 +467,10 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * スキーマレベル設定の継承ー自分に設定が無い場合親の設定が有効になること. + * C12_スキーマレベル設定の継承ー自分に設定が無い場合親の設定が有効になること. */ @Test - public final void スキーマレベル設定の継承ー自分に設定が無い場合親の設定が有効になること() { + public final void C12_スキーマレベル設定の継承ー自分に設定が無い場合親の設定が有効になること() { try { // ACL設定 this.setACL(TEST_BOX1, "", ACL_SETTING_FILE); @@ -507,10 +508,10 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * スキーマレベル設定の継承ーデフォルトはスキーマ認証不要であることの確認. + * C13_スキーマレベル設定の継承ーデフォルトはスキーマ認証不要であることの確認. */ @Test - public final void スキーマレベル設定の継承ーデフォルトはスキーマ認証不要であることの確認() { + public final void C13_スキーマレベル設定の継承ーデフォルトはスキーマ認証不要であることの確認() { try { // ACL設定 this.setACL(TEST_BOX1, "", ACL_SETTING_FILE); @@ -532,12 +533,11 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le } /** - * スキーマ認証スキーマ値チェックの確認. - * @throws TokenParseException トークンパースエラー + * C14_AppAuth_Check_BoxSchemaMatch. + * @throws TokenParseException */ - @SuppressWarnings("deprecation") @Test - public final void スキーマ認証スキーマ値チェックの確認() throws TokenParseException { + public final void C14_AppAuth_Check_BoxSchemaMatch() throws TokenParseException { String userCell = "cell20161221"; String schemaCell = "cell20161221schema"; String user = "user"; @@ -550,42 +550,23 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le String aTokenStr = null; try { - // セルの作成 + // Create Cells CellUtils.create(userCell, MASTER_TOKEN, HttpStatus.SC_CREATED); CellUtils.create(schemaCell, MASTER_TOKEN, HttpStatus.SC_CREATED); - // Accountの作成 + // Create Accounts AccountUtils.create(MASTER_TOKEN, userCell, user, pass, HttpStatus.SC_CREATED); AccountUtils.create(MASTER_TOKEN, schemaCell, user, pass, HttpStatus.SC_CREATED); - // Boxの作成 + // Create Boxes BoxUtils.createWithSchema(userCell, boxWithHttpSchemaUrl, MASTER_TOKEN, UrlUtils.cellRoot(schemaCell)); BoxUtils.createWithSchema(userCell, boxWithNonSchemaCellSchemaUrl, MASTER_TOKEN, UrlUtils.cellRoot(userCell)); BoxUtils.createWithSchema(userCell, boxWithLocalUnitSchemaUrl, MASTER_TOKEN, "personium-localunit:/" + schemaCell + "/"); - // Roleの作成 -// RoleUtils.create(userCell, MASTER_TOKEN, boxWithHttpSchemaUrl, role, HttpStatus.SC_CREATED); -// RoleUtils.create(userCell, MASTER_TOKEN, boxWithLocalUnitSchemaUrl, role, HttpStatus.SC_CREATED); - - // RoleとAccountの$links -// ResourceUtils.linkAccountRole(userCell, MASTER_TOKEN, user, boxWithHttpSchemaUrl, -// role, HttpStatus.SC_NO_CONTENT); -// ResourceUtils.linkAccountRole(userCell, MASTER_TOKEN, user, boxWithLocalUnitSchemaUrl, -// role, HttpStatus.SC_NO_CONTENT); - - // BoxにConfidentialレベルの設定 -// this.setAclSchema(boxWithHttpSchemaUrl, "", UrlUtils.roleResource(userCell, boxWithHttpSchemaUrl, ""), -// OAuth2Helper.SchemaLevel.PUBLIC, userCell, role, DEFAULT_PRIVILEGE); -// this.setAclSchema(boxWithNonSchemaCellSchemaUrl, "", -// UrlUtils.roleResource(userCell, boxWithHttpSchemaUrl, ""), -// OAuth2Helper.SchemaLevel.PUBLIC, userCell, role, DEFAULT_PRIVILEGE); -// this.setAclSchema(boxWithLocalUnitSchemaUrl, "", -// UrlUtils.roleResource(userCell, boxWithLocalUnitSchemaUrl, ""), -// OAuth2Helper.SchemaLevel.PUBLIC, userCell, role, DEFAULT_PRIVILEGE); - - // ACLの設定(今回テストではACL設定は無関係のため、ALLで設定) + + // ACL config (This test is not meant to check ACL settings so use principal ALL) DavResourceUtils.setACL(userCell, MASTER_TOKEN, HttpStatus.SC_OK, userCell + "/" + boxWithHttpSchemaUrl, "box/acl-setting-all.txt", role, "", @@ -599,11 +580,11 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le "box/acl-setting-all.txt", role, "", OAuth2Helper.SchemaLevel.PUBLIC); - // スキーマ認証用トランスセルトークンの取得 + // App auth token retrieval JSONObject appAuthJson = getTransTokenByAppAuth(schemaCell, user, pass, UrlUtils.cellRoot(userCell)); String appToken = (String) appAuthJson.get(OAuth2Helper.Key.ACCESS_TOKEN); - // Queryでスキーマ認証 + // ROPC with app auth TResponse res = Http.request("authn/password-cl-cp.txt") .with("remoteCell", userCell) .with("username", user) @@ -618,46 +599,51 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le String rTokenStr = (String) json.get(OAuth2Helper.Key.REFRESH_TOKEN); aTokenStr = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN); - // コレクションの作成(boxWithHttpSchemaUrlはスキーマと、トークンのスキーマが一致するため作成可能) - DavResourceUtils.createWebDavCollection("box/mkcol.txt", userCell, - boxWithHttpSchemaUrl + "/" + colName, - aTokenStr, HttpStatus.SC_CREATED); - - // コレクションの作成(boxWithNonSchemaCellSchemaUrlはスキーマと、トークンのスキーマが一致しないため作成不可) - DavResourceUtils.createWebDavCollection("box/mkcol.txt", userCell, - boxWithNonSchemaCellSchemaUrl + "/" + colName, - aTokenStr, HttpStatus.SC_FORBIDDEN); - - // コレクションの作成(boxWithLocalUnitSchemaUrlはスキーマと、トークンのスキーマが一致するため作成可能) - DavResourceUtils.createWebDavCollection("box/mkcol.txt", userCell, - boxWithLocalUnitSchemaUrl + "/" + colName, - aTokenStr, HttpStatus.SC_CREATED); - - // リフレッシュトークン認証 - TResponse refreshRes = ResourceUtils.refreshTokenAuthCl(userCell, rTokenStr); + // Create Collection (Succeed since boxWithHttpSchemaUrl's schema matches the token schema) + Http.request("box/mkcol.txt") + .with("cellPath", userCell) + .with("path", boxWithHttpSchemaUrl + "/" + colName) + .with("token", aTokenStr) + .returns().statusCode(HttpStatus.SC_CREATED); + + // Create Collection (Fail since boxWithNonSchemaCellSchemaUrl's schema does not matches the token schema) + Http.request("box/mkcol.txt") + .with("cellPath", userCell) + .with("path", boxWithNonSchemaCellSchemaUrl + "/" + colName) + .with("token", aTokenStr) + .returns().statusCode(HttpStatus.SC_FORBIDDEN); + + // Create Collection (Succeed since boxWithLocalUnitSchemaUrl's schema matches the token schema) + Http.request("box/mkcol.txt") + .with("cellPath", userCell) + .with("path", boxWithLocalUnitSchemaUrl + "/" + colName) + .with("token", aTokenStr) + .returns().statusCode(HttpStatus.SC_CREATED); + + // Token Refresh + TResponse refreshRes = Http.request("authn/refresh-cl-cp.txt") + .with("remoteCell", userCell) + .with("refresh_token", rTokenStr) + .with("client_id", UrlUtils.cellRoot(schemaCell)) + .with("client_secret", appToken) + .returns() + .statusCode(HttpStatus.SC_OK); aTokenStr = (String) refreshRes.bodyAsJson().get(OAuth2Helper.Key.ACCESS_TOKEN); } finally { - // コレクションの削除(testbox03はスキーマと、トークンのスキーマが一致するため削除可能) + // delete Collections DavResourceUtils.deleteCollection(userCell, boxWithHttpSchemaUrl, colName, MASTER_TOKEN, -1); - // コレクションの削除(testbox05はスキーマと、トークンのスキーマが一致するため削除可能) DavResourceUtils.deleteCollection(userCell, boxWithLocalUnitSchemaUrl, colName, MASTER_TOKEN, -1); - // RoleとAccountの$linksの削除 -// ResourceUtils.linkAccountRollDelete(userCell, MASTER_TOKEN, user, boxWithHttpSchemaUrl, role); - - // Roleの削除 -// RoleUtils.delete(userCell, MASTER_TOKEN, boxWithHttpSchemaUrl, role); - - // Boxの削除 + // delete Boxes BoxUtils.delete(userCell, MASTER_TOKEN, boxWithHttpSchemaUrl); BoxUtils.delete(userCell, MASTER_TOKEN, boxWithNonSchemaCellSchemaUrl); BoxUtils.delete(userCell, MASTER_TOKEN, boxWithLocalUnitSchemaUrl); - // Accountの削除 + // delete Accounts AccountUtils.delete(schemaCell, MASTER_TOKEN, user, -1); AccountUtils.delete(userCell, MASTER_TOKEN, user, -1); - // セルの削除 + // delete Cells CellUtils.delete(MASTER_TOKEN, schemaCell, -1); CellUtils.delete(MASTER_TOKEN, userCell, -1); } @@ -665,11 +651,11 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le /** - * デフォルトボックスに対するスキーマ認証の確認. + * C15_MainBoxに対するスキーマ認証の確認. * @throws TokenParseException トークンパースエラー */ @Test - public final void デフォルトボックスに対するスキーマ認証の確認() throws TokenParseException { + public final void C15_MainBoxに対するスキーマ認証の確認() throws TokenParseException { String tokenStr = checkCellLocalWithSchema("account0", "password0", TEST_CELL1, UrlUtils.cellRoot(TEST_CELL1)); @@ -678,16 +664,16 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le try { // テスト用のファイルをPUT DavResourceUtils.createWebDavFile(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, "box/dav-put.txt", - "hoge", Box.DEFAULT_BOX_NAME, DAV_RESOURCE, -1); + "hoge", Box.MAIN_BOX_NAME, DAV_RESOURCE, -1); // ACL設定 DavResourceUtils.setACL(TEST_CELL1, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_OK, DAV_RESOURCE, - "box/acl-all-none-schema-level.txt", Box.DEFAULT_BOX_NAME, ""); + "box/acl-all-none-schema-level.txt", Box.MAIN_BOX_NAME, ""); - this.checkResourcesWithSchema("", DAV_RESOURCE, tokenStr, Box.DEFAULT_BOX_NAME, TEST_CELL1); + this.checkResourcesWithSchema("", DAV_RESOURCE, tokenStr, Box.MAIN_BOX_NAME, TEST_CELL1); } finally { // テスト用のファイルを削除 DavResourceUtils.deleteWebDavFile("box/dav-delete.txt", Setup.TEST_CELL1, - AbstractCase.MASTER_TOKEN_NAME, DAV_RESOURCE, -1, Box.DEFAULT_BOX_NAME); + AbstractCase.MASTER_TOKEN_NAME, DAV_RESOURCE, -1, Box.MAIN_BOX_NAME); } } @@ -814,10 +800,10 @@ private String checkCellLocalWithSchema(String account, String pass, String sche // トークンチェック String tokenStr = (String) json.get(OAuth2Helper.Key.ACCESS_TOKEN); - AccountAccessToken aToken = AccountAccessToken.parse(tokenStr, issuer); + ResidentLocalAccessToken aToken = ResidentLocalAccessToken.parse(tokenStr, issuer); assertEquals(schema, aToken.getSchema()); String rTokenStr = (String) json.get(OAuth2Helper.Key.REFRESH_TOKEN); - CellLocalRefreshToken rToken = CellLocalRefreshToken.parse(rTokenStr, issuer); + ResidentRefreshToken rToken = ResidentRefreshToken.parse(rTokenStr, issuer); assertEquals(schema, rToken.getSchema()); return tokenStr; @@ -880,7 +866,7 @@ private String cheackTokenAuth(String account, String pass, String schema) throw JSONObject json2 = res3.bodyAsJson(); String tokenStr2 = (String) json2.get(OAuth2Helper.Key.ACCESS_TOKEN); - CellLocalAccessToken aToken = CellLocalAccessToken.parse(tokenStr2, issuer); + VisitorLocalAccessToken aToken = VisitorLocalAccessToken.parse(tokenStr2, issuer); assertEquals(schema, aToken.getSchema()); return tokenStr2; diff --git a/src/test/java/io/personium/test/jersey/cell/auth/X509AuthTest.java b/src/test/java/io/personium/test/jersey/cell/auth/X509AuthTest.java index f6610062e..dd30c2f79 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/X509AuthTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/X509AuthTest.java @@ -84,7 +84,8 @@ public X509AuthTest() { // TransCellAccessTokenを自作 TransCellAccessToken tcat = new TransCellAccessToken(UrlUtils.cellRoot(Setup.TEST_CELL1), - "https://example/test/#admin", UrlUtils.cellRoot(Setup.TEST_CELL1), new ArrayList(), null); + "https://example/test/#admin", UrlUtils.cellRoot(Setup.TEST_CELL1), new ArrayList(), + null, null); String token = tcat.toTokenString(); // テスト用トークンを作成したら、サーバ側の証明書をデフォルトに再設定 @@ -116,7 +117,8 @@ public X509AuthTest() { // TransCellAccessTokenを自作 TransCellAccessToken tcat = new TransCellAccessToken("https://example/test/", - "https://example/test/#admin", UrlUtils.cellRoot(Setup.TEST_CELL1), new ArrayList(), null); + "https://example/test/#admin", UrlUtils.cellRoot(Setup.TEST_CELL1), new ArrayList(), + null, null); String token = tcat.toTokenString(); // testcell1にトークン認証して400 @@ -157,7 +159,8 @@ public X509AuthTest() { // TransCellAccessTokenを自作 TransCellAccessToken tcat = new TransCellAccessToken("https://localhost/test/", - "https://example/test/#admin", UrlUtils.cellRoot(Setup.TEST_CELL1), new ArrayList(), null); + "https://example/test/#admin", UrlUtils.cellRoot(Setup.TEST_CELL1), new ArrayList(), + null, null); String token = tcat.toTokenString(); // テスト用トークンを作成したら、サーバ側の証明書をデフォルトに再設定 @@ -209,7 +212,8 @@ public X509AuthTest() { // TransCellAccessTokenを自作 TransCellAccessToken tcat = new TransCellAccessToken("https://localhost/test/", - "https://example/test/#admin", UrlUtils.cellRoot(Setup.TEST_CELL1), new ArrayList(), null); + "https://example/test/#admin", UrlUtils.cellRoot(Setup.TEST_CELL1), new ArrayList(), + null, null); String token = tcat.toTokenString(); diff --git a/src/test/java/io/personium/test/jersey/cell/auth/token/TokenAcceptanceTest.java b/src/test/java/io/personium/test/jersey/cell/auth/token/TokenAcceptanceTest.java new file mode 100644 index 000000000..f51d7b926 --- /dev/null +++ b/src/test/java/io/personium/test/jersey/cell/auth/token/TokenAcceptanceTest.java @@ -0,0 +1,295 @@ +/** + * Personium + * Copyright 2019 Personium Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.personium.test.jersey.cell.auth.token; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.json.Json; +import javax.json.JsonObject; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.personium.common.auth.token.AbstractOAuth2Token.TokenDsigException; +import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; +import io.personium.common.auth.token.AbstractOAuth2Token.TokenRootCrtException; +import io.personium.common.auth.token.ResidentRefreshToken; +import io.personium.common.auth.token.Role; +import io.personium.common.auth.token.TransCellAccessToken; +import io.personium.core.auth.OAuth2Helper; +import io.personium.core.rs.PersoniumCoreApplication; +import io.personium.core.utils.HttpClientFactory; +import io.personium.core.utils.UriUtils; +import io.personium.test.categories.Integration; +import io.personium.test.categories.Regression; +import io.personium.test.categories.Unit; +import io.personium.test.jersey.PersoniumIntegTestRunner; +import io.personium.test.jersey.PersoniumTest; +import io.personium.test.setup.Setup; + +/** + * Tests about tokens issuance at the Token Endpoint. + */ +@RunWith(PersoniumIntegTestRunner.class) +@Category({Unit.class, Integration.class, Regression.class }) +public class TokenAcceptanceTest extends PersoniumTest { + + static final int MILLISECS_IN_AN_MINITE = 60 * 1000; + private static Logger log = LoggerFactory.getLogger(TokenAcceptanceTest.class); + + + /** + * Constructor. + */ + public TokenAcceptanceTest() { + super(new PersoniumCoreApplication()); + } + + /** + * Should_FailRefreshingToken_When_NewClientSpecifiedForTokenWithoutSchema. + * @throws IOException + * @throws ClientProtocolException + * @throws TokenRootCrtException + * @throws TokenDsigException + * @throws TokenParseException + */ + @Test + public final void Should_FailRefreshingToken_When_NewClientSpecifiedForTokenWithoutSchema() + throws ClientProtocolException, IOException, TokenParseException, TokenDsigException, TokenRootCrtException { + String appCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL_SCHEMA1 + ":/"; + String usrCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL1 + ":/"; + String appCellUrl = UriUtils.resolveLocalUnit(appCellLocalUnit); + String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); + + // Generate Refresh Token without schema (schema null) + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", null, null); + + // Generate AppAuth Token + List roleList = new ArrayList(); + TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl, appCellUrl + "#account1", + usrCellUrl, roleList, + null, null); + + // Refresh Token + HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), null, appCellUrl, appAuthToken.toTokenString()); + // Should be error + assertEquals(401, res.getStatusLine().getStatusCode()); + log.info(parseJsonResponse(res).toString()); + + } + + /** + * Should_FailRefreshingToken_When_ClientIdNotMatchesSchemaInRefreshToken. + * @throws IOException + * @throws ClientProtocolException + * @throws TokenRootCrtException + * @throws TokenDsigException + * @throws TokenParseException + */ + @Test + public final void Should_FailRefreshingToken_When_ClientIdNotMatchesSchemaInRefreshToken() + throws ClientProtocolException, IOException, TokenParseException, TokenDsigException, TokenRootCrtException { + String appCellLocalUnit1 = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL_SCHEMA1 + ":/"; + String appCellLocalUnit2 = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL_SCHEMA2 + ":/"; + String usrCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL1 + ":/"; + String appCellUrl1 = UriUtils.resolveLocalUnit(appCellLocalUnit1); + String appCellUrl2 = UriUtils.resolveLocalUnit(appCellLocalUnit2); + String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); + + // Generate Refresh Token without schema + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl2, new String [] {"scope1"}); + + // Generate AppAuth Token + List roleList = new ArrayList(); + TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl1, appCellUrl1 + "#account1", + usrCellUrl, roleList, + null, null); + + // Refresh Token + HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl2, appCellUrl1, appAuthToken.toTokenString()); + + // Should be error + assertEquals(401, res.getStatusLine().getStatusCode()); + log.info(parseJsonResponse(res).toString()); + } + + + /** + * Should_SuccessRefrehingToken__When_ClientIdMatchesSchemaInRefreshToken. + * @throws IOException + * @throws ClientProtocolException + * @throws TokenRootCrtException + * @throws TokenDsigException + * @throws TokenParseException + */ + @Test + public final void Should_SuccessRefrehingToken__When_ClientIdMatchesSchemaInRefreshToken() + throws ClientProtocolException, IOException, TokenParseException, TokenDsigException, TokenRootCrtException { + String appCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL_SCHEMA1 + ":/"; + String usrCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL1 + ":/"; + String appCellUrl = UriUtils.resolveLocalUnit(appCellLocalUnit); + String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); + + // Generate Refresh Token + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl, new String[] {"scope1"}); + + // Generate AppAuth Token + List roleList = new ArrayList(); + TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl, appCellUrl + "#account1", + usrCellUrl, roleList, + null, null); + + // Refresh Token + HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl, appCellUrl, appAuthToken.toTokenString()); + assertEquals(200, res.getStatusLine().getStatusCode()); + JsonObject j = parseJsonResponse(res); + + String at = j.getString(OAuth2Helper.Key.ACCESS_TOKEN); + log.info(at); + + TransCellAccessToken tcat = TransCellAccessToken.parse(at); + String aud = tcat.getTarget(); + log.info(aud); + + assertFalse(aud.startsWith(UriUtils.SCHEME_LOCALUNIT)); + assertTrue(aud.startsWith("http")); + } + + /** + * Should_FailRefrehingToken__When_RefreshTokenHasSchemaButNoAppAuth. + * @throws IOException + * @throws ClientProtocolException + * @throws TokenRootCrtException + * @throws TokenDsigException + * @throws TokenParseException + */ + @Test + public final void Should_FailRefrehingToken__When_RefreshTokenHasSchemaButNoAppAuth() + throws ClientProtocolException, IOException, TokenParseException, TokenDsigException, TokenRootCrtException { + String appCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL_SCHEMA1 + ":/"; + String usrCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL1 + ":/"; + String appCellUrl = UriUtils.resolveLocalUnit(appCellLocalUnit); + String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); + + // Generate Refresh Token + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl, new String[] {"scope1"}); + + // Refresh Token + HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), null); + assertEquals(401, res.getStatusLine().getStatusCode()); + } + + + /** + * Should_SuccessRefrehingToken__When_ClientIdNullAndRefreshTokenWithoutSchema. + * @throws IOException + * @throws ClientProtocolException + * @throws TokenRootCrtException + * @throws TokenDsigException + * @throws TokenParseException + */ + @Test + public final void Should_SuccessRefrehingToken__When_ClientIdNullAndRefreshTokenWithoutSchema() + throws ClientProtocolException, IOException, TokenParseException, TokenDsigException, TokenRootCrtException { + String appCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL_SCHEMA1 + ":/"; + String usrCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL1 + ":/"; + String appCellUrl = UriUtils.resolveLocalUnit(appCellLocalUnit); + String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); + + // Generate Refresh Token + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", null, new String[] {"scope1", "scope2"}); + + // Refresh Token + HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl); + assertEquals(200, res.getStatusLine().getStatusCode()); + JsonObject j = parseJsonResponse(res); + + String at = j.getString(OAuth2Helper.Key.ACCESS_TOKEN); + log.info(at); + + TransCellAccessToken tcat = TransCellAccessToken.parse(at); + String aud = tcat.getTarget(); + log.info(aud); + + assertFalse(aud.startsWith(UriUtils.SCHEME_LOCALUNIT)); + assertTrue(aud.startsWith("http")); + } + + + private static JsonObject parseJsonResponse(HttpResponse res) { + try (InputStream is = res.getEntity().getContent()){ + return Json.createReader(is).readObject(); + } catch (UnsupportedOperationException | IOException e) { + throw new RuntimeException(e); + } + } + + private static HttpResponse refreshToken(String cellUrl, String refreshToken, String pTarget) + throws ClientProtocolException, IOException { + return refreshToken(cellUrl, refreshToken, pTarget, null, null); + } + + private static HttpResponse refreshToken(String cellUrl, String refreshToken, String pTarget, String clientId, String clientSecret) + throws ClientProtocolException, IOException { + HttpClient client = HttpClientFactory.create(HttpClientFactory.TYPE_DEFAULT); + + String tokenEndpoint = cellUrl + "__token"; + log.info("Testing against: " + tokenEndpoint); + + HttpPost post = new HttpPost(tokenEndpoint); + + StringBuilder sb = new StringBuilder(); + sb.append("grant_type=refresh_token&refresh_token="); + sb.append(refreshToken); + if (pTarget != null) { + sb.append("&p_target="); + sb.append(pTarget); + } + if (clientId != null) { + sb.append("&client_id="); + sb.append(clientId); + sb.append("&client_secret="); + sb.append(clientSecret); + } + + post.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType()); + post.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()); + + HttpEntity reqEntity = new StringEntity(sb.toString()); + post.setEntity(reqEntity); + return client.execute(post); + } +} + diff --git a/src/test/java/io/personium/test/jersey/cell/auth/token/TokenIssuanceTest.java b/src/test/java/io/personium/test/jersey/cell/auth/token/TokenIssuanceTest.java new file mode 100644 index 000000000..c836124aa --- /dev/null +++ b/src/test/java/io/personium/test/jersey/cell/auth/token/TokenIssuanceTest.java @@ -0,0 +1,169 @@ +/** + * Personium + * Copyright 2019 FUJITSU LIMITED + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.personium.test.jersey.cell.auth.token; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.InputStream; + +import javax.json.Json; +import javax.json.JsonObject; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.personium.common.auth.token.AbstractOAuth2Token.TokenDsigException; +import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; +import io.personium.common.auth.token.AbstractOAuth2Token.TokenRootCrtException; +import io.personium.common.auth.token.ResidentLocalAccessToken; +import io.personium.common.auth.token.TransCellAccessToken; +import io.personium.core.rs.PersoniumCoreApplication; +import io.personium.core.utils.HttpClientFactory; +import io.personium.core.utils.UriUtils; +import io.personium.test.categories.Integration; +import io.personium.test.categories.Regression; +import io.personium.test.categories.Unit; +import io.personium.test.jersey.PersoniumIntegTestRunner; +import io.personium.test.jersey.PersoniumTest; +import io.personium.test.setup.Setup; + +/** + * Tests about tokens issuance at the Token Endpoint. + */ +@RunWith(PersoniumIntegTestRunner.class) +@Category({Unit.class, Integration.class, Regression.class }) +public class TokenIssuanceTest extends PersoniumTest { + + static final int MILLISECS_IN_AN_MINITE = 60 * 1000; + private static Logger log = LoggerFactory.getLogger(TokenIssuanceTest.class); + + + /** + * Constructor. + */ + public TokenIssuanceTest() { + super(new PersoniumCoreApplication()); + } + + /** + * When p_target is localunit scheme URL, then Trans-Cell Access Token issued should have http scheme audience. + * @throws IOException + * @throws ClientProtocolException + * @throws TokenRootCrtException + * @throws TokenDsigException + * @throws TokenParseException + */ + @Test + public final void When_PTargetLocalunitSchemeURL_Then_TCATShouldHaveAudienceHttpSchemeURL () throws ClientProtocolException, IOException, TokenParseException, TokenDsigException, TokenRootCrtException { + String cellUrl = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL1 + ":/"; + String targetUrl = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL2 + ":/"; + cellUrl = UriUtils.resolveLocalUnit(cellUrl); + String at = this.callROPC(cellUrl, "account1", "password1", targetUrl).getString("access_token"); + TransCellAccessToken tcat = TransCellAccessToken.parse(at); + String aud = tcat.getTarget(); + log.info(aud); + + assertFalse(aud.startsWith(UriUtils.SCHEME_LOCALUNIT)); + assertTrue(aud.startsWith("http")); + } + + + /** + * When client_id is localunit scheme URL, then app auth should still work. + * @throws IOException + * @throws ClientProtocolException + * @throws TokenRootCrtException + * @throws TokenDsigException + * @throws TokenParseException + */ + @Test + public final void When_ClientIdLocalunitSchemeURL_Then_StillTheAppAuthShouldWork () throws ClientProtocolException, IOException, TokenParseException, TokenDsigException, TokenRootCrtException { + String appCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL_SCHEMA1 + ":/"; + String usrCellLocalUnit = UriUtils.SCHEME_LOCALUNIT + ":" + Setup.TEST_CELL1 + ":/"; + String appCellUrl = UriUtils.resolveLocalUnit(appCellLocalUnit); + String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); + + String clientSecret = this.callROPC(appCellUrl, "account1", "password1", usrCellUrl).getString("access_token"); + String at = this.callROPC(usrCellUrl, "account1", "password1", null, appCellLocalUnit, clientSecret).getString("access_token"); + log.info("token:" + at); + + ResidentLocalAccessToken aat = ResidentLocalAccessToken.parse(at, usrCellUrl); + + String schema = aat.getSchema(); + log.info(schema); + assertTrue(schema.startsWith(appCellUrl)); + } + + private JsonObject callROPC(String cellUrl, String username, String password, String pTarget) + throws ClientProtocolException, IOException { + return callROPC(cellUrl, username, password, pTarget, null, null); + } + + private JsonObject callROPC(String cellUrl, String username, String password, String pTarget, String clientId, String clientSecret) + throws ClientProtocolException, IOException { + HttpClient client = HttpClientFactory.create(HttpClientFactory.TYPE_DEFAULT); + + String tokenEndpoint = cellUrl + "__token"; + log.info("Testing against: " + tokenEndpoint); + + HttpPost post = new HttpPost(tokenEndpoint); + + StringBuilder sb = new StringBuilder(); + sb.append("grant_type=password&username="); + sb.append(username); + sb.append("&password="); + sb.append(password); + if (pTarget != null) { + sb.append("&p_target="); + sb.append(pTarget); + } + if (clientId != null) { + sb.append("&client_id="); + sb.append(clientId); + sb.append("&client_secret="); + sb.append(clientSecret); + } + + post.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType()); + post.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()); + + HttpEntity reqEntity = new StringEntity(sb.toString()); + post.setEntity(reqEntity); + HttpResponse res = client.execute(post); + + try (InputStream is = res.getEntity().getContent()){ + return Json.createReader(is).readObject(); + } + } + + + +} + diff --git a/src/test/java/io/personium/test/jersey/cell/auth/token/TokenTest.java b/src/test/java/io/personium/test/jersey/cell/auth/token/TokenTest.java index 5b96ca2f1..07d6d0e10 100644 --- a/src/test/java/io/personium/test/jersey/cell/auth/token/TokenTest.java +++ b/src/test/java/io/personium/test/jersey/cell/auth/token/TokenTest.java @@ -28,13 +28,13 @@ import org.junit.runner.RunWith; import io.personium.common.auth.token.AbstractOAuth2Token; -import io.personium.common.auth.token.AccountAccessToken; -import io.personium.common.auth.token.CellLocalAccessToken; -import io.personium.common.auth.token.CellLocalRefreshToken; import io.personium.common.auth.token.PasswordChangeAccessToken; +import io.personium.common.auth.token.ResidentLocalAccessToken; +import io.personium.common.auth.token.ResidentRefreshToken; import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; -import io.personium.common.auth.token.TransCellRefreshToken; +import io.personium.common.auth.token.VisitorLocalAccessToken; +import io.personium.common.auth.token.VisitorRefreshToken; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; @@ -47,7 +47,7 @@ import io.personium.test.utils.ResourceUtils; /** - * トークンのテスト. + * Access Token Acceptance test. */ @RunWith(PersoniumIntegTestRunner.class) @Category({Unit.class, Integration.class, Regression.class }) @@ -60,9 +60,12 @@ public class TokenTest extends PersoniumTest { static final String DAV_RESOURCE = "dav.txt"; static final int MILLISECS_IN_AN_MINITE = 60 * 1000; + static final String SCHEMA_SAMPLE = "scope"; + static final String[] SCOPE_SAMPLE = new String[] {"scope"}; + /** - * コンストラクタ. + * Constructor. */ public TokenTest() { super(new PersoniumCoreApplication()); @@ -78,12 +81,11 @@ public TokenTest() { String subject = issuer + "#account1"; String target = UrlUtils.cellRoot(TEST_CELL2); List roleList = new ArrayList(); - String schema = ""; // 期限切れでないトークンを生成 TransCellAccessToken validToken = new TransCellAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR + MILLISECS_IN_AN_MINITE, - issuer, subject, target, roleList, schema); + issuer, subject, target, roleList, SCHEMA_SAMPLE, SCOPE_SAMPLE); // セルに対してトークン認証 Http.request("authn/saml-cl-c0.txt") .with("remoteCell", TEST_CELL2) @@ -94,7 +96,7 @@ public TokenTest() { // 期限切れのトークンを生成 TransCellAccessToken invalidToken = new TransCellAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR - MILLISECS_IN_AN_MINITE, - issuer, subject, target, roleList, schema); + issuer, subject, target, roleList, SCHEMA_SAMPLE, SCOPE_SAMPLE); // セルに対してトークン認証 Http.request("authn/saml-cl-c0.txt") .with("remoteCell", TEST_CELL2) @@ -114,9 +116,9 @@ public TokenTest() { String schema = ""; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - CellLocalRefreshToken validToken = new CellLocalRefreshToken( - issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 + MILLISECS_IN_AN_MINITE, - issuer, subject, schema); + ResidentRefreshToken validToken = new ResidentRefreshToken( + issuedAt - AbstractOAuth2Token.SECS_IN_A_DAY * 1000 + MILLISECS_IN_AN_MINITE, + issuer, subject, schema, SCOPE_SAMPLE); // アプリセルに対して認証 Http.request("authn/refresh-cl.txt") @@ -126,8 +128,9 @@ public TokenTest() { .statusCode(HttpStatus.SC_OK); // 期限切れのトークンを生成する(IT環境の通信時間を考慮して1分余裕を持たせる) - CellLocalRefreshToken invalidToken = new CellLocalRefreshToken( - issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 - MILLISECS_IN_AN_MINITE, issuer, subject, schema); + ResidentRefreshToken invalidToken = new ResidentRefreshToken( + issuedAt - AbstractOAuth2Token.SECS_IN_A_DAY * 1000 - MILLISECS_IN_AN_MINITE, issuer, subject, + schema, new String[] {"scope1", "scope2", "scope3"}); // アプリセルに対して認証 Http.request("authn/refresh-cl.txt") .with("remoteCell", TEST_CELL1) @@ -148,11 +151,12 @@ public TokenTest() { String subject = origIssuer + "#account1"; List origRoleList = new ArrayList(); String schema = ""; + String[] scope = new String[] {"scope"}; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - TransCellRefreshToken validToken = new TransCellRefreshToken( - id, issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 + MILLISECS_IN_AN_MINITE, - issuer, subject, origIssuer, origRoleList, schema); + VisitorRefreshToken validToken = new VisitorRefreshToken( + id, issuedAt - AbstractOAuth2Token.SECS_IN_A_DAY * 1000 + MILLISECS_IN_AN_MINITE, + issuer, subject, origIssuer, origRoleList, schema, scope); // Refresh Http.request("authn/refresh-cl.txt") .with("remoteCell", TEST_CELL2) @@ -161,9 +165,9 @@ public TokenTest() { .statusCode(HttpStatus.SC_OK); // 期限切れのトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - TransCellRefreshToken invalidToken = new TransCellRefreshToken( - id, issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 - MILLISECS_IN_AN_MINITE, - issuer, subject, origIssuer, origRoleList, schema); + VisitorRefreshToken invalidToken = new VisitorRefreshToken( + id, issuedAt - AbstractOAuth2Token.SECS_IN_A_DAY * 1000 - MILLISECS_IN_AN_MINITE, + issuer, subject, origIssuer, origRoleList, schema, scope); // Refresh Http.request("authn/refresh-cl.txt") .with("remoteCell", TEST_CELL2) @@ -190,7 +194,7 @@ public TokenTest() { // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) TransCellAccessToken validToken = new TransCellAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR + MILLISECS_IN_AN_MINITE, - issuer, subject, target, roleList, schema); + issuer, subject, target, roleList, SCHEMA_SAMPLE, SCOPE_SAMPLE); // セルに対してトークン認証 Http.request("authn/password-cl-cp.txt") .with("remoteCell", TEST_CELL1) @@ -204,7 +208,7 @@ public TokenTest() { // 期限切のトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) TransCellAccessToken invalidToken = new TransCellAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR - MILLISECS_IN_AN_MINITE, - issuer, subject, target, roleList, schema); + issuer, subject, target, roleList, SCHEMA_SAMPLE, SCOPE_SAMPLE); // セルに対してトークン認証 Http.request("authn/password-cl-cp.txt") .with("remoteCell", TEST_CELL1) @@ -225,19 +229,20 @@ public TokenTest() { String issuer = UrlUtils.cellRoot(TEST_CELL1); String subject = "account2"; String schema = ""; + String[] scope = new String[0]; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - AccountAccessToken validToken = new AccountAccessToken( + ResidentLocalAccessToken validToken = new ResidentLocalAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR + MILLISECS_IN_AN_MINITE, - issuer, subject, schema); + issuer, subject, schema, scope); // データアクセス ResourceUtils.retrieve(validToken.toTokenString(), DAV_COLLECTION + DAV_RESOURCE, HttpStatus.SC_OK, TEST_CELL1, Setup.TEST_BOX1); // 期限切れのトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - AccountAccessToken invalidToken = new AccountAccessToken( + ResidentLocalAccessToken invalidToken = new ResidentLocalAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR - MILLISECS_IN_AN_MINITE, - issuer, subject, schema); + issuer, subject, schema, scope); // データアクセス ResourceUtils.retrieve(invalidToken.toTokenString(), DAV_COLLECTION + DAV_RESOURCE, HttpStatus.SC_UNAUTHORIZED, TEST_CELL1, Setup.TEST_BOX1); @@ -256,19 +261,22 @@ public TokenTest() { Role role = new Role(new URL(UrlUtils.roleResource(TEST_CELL1, "__", "role2"))); roleList.add(role); String schema = ""; + String[] scope = new String[] {"scope"}; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - CellLocalAccessToken validToken = new CellLocalAccessToken( + VisitorLocalAccessToken validToken = new VisitorLocalAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR + MILLISECS_IN_AN_MINITE, - issuer, subject, roleList, schema); + AbstractOAuth2Token.ACCESS_TOKEN_EXPIRES_MILLISECS, + issuer, subject, roleList, SCHEMA_SAMPLE, SCOPE_SAMPLE); // データアクセス ResourceUtils.retrieve(validToken.toTokenString(), DAV_COLLECTION + DAV_RESOURCE, HttpStatus.SC_OK, TEST_CELL1, Setup.TEST_BOX1); // 期限切れのトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - CellLocalAccessToken invalidToken = new CellLocalAccessToken( + VisitorLocalAccessToken invalidToken = new VisitorLocalAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR - MILLISECS_IN_AN_MINITE, - issuer, subject, roleList, schema); + AbstractOAuth2Token.ACCESS_TOKEN_EXPIRES_MILLISECS, + issuer, subject, roleList, SCHEMA_SAMPLE, SCOPE_SAMPLE); // データアクセス ResourceUtils.retrieve(invalidToken.toTokenString(), DAV_COLLECTION + DAV_RESOURCE, HttpStatus.SC_UNAUTHORIZED, TEST_CELL1, Setup.TEST_BOX1); @@ -287,12 +295,11 @@ public TokenTest() { List roleList = new ArrayList(); Role role = new Role(new URL(UrlUtils.roleResource(TEST_CELL1, "__", "role2"))); roleList.add(role); - String schema = ""; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) TransCellAccessToken validToken = new TransCellAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR + MILLISECS_IN_AN_MINITE, - issuer, subject, target, roleList, schema); + issuer, subject, target, roleList, SCHEMA_SAMPLE, SCOPE_SAMPLE); // データアクセス ResourceUtils.retrieve(validToken.toTokenString(), DAV_COLLECTION + DAV_RESOURCE, HttpStatus.SC_OK, TEST_CELL2, Setup.TEST_BOX1); @@ -300,7 +307,7 @@ public TokenTest() { // 期限切れのトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) TransCellAccessToken invalidToken = new TransCellAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR - MILLISECS_IN_AN_MINITE, - issuer, subject, target, roleList, schema); + issuer, subject, target, roleList, SCHEMA_SAMPLE, SCOPE_SAMPLE); // データアクセス ResourceUtils.retrieve(invalidToken.toTokenString(), DAV_COLLECTION + DAV_RESOURCE, HttpStatus.SC_UNAUTHORIZED, TEST_CELL2, Setup.TEST_BOX1); @@ -314,12 +321,11 @@ public final void access_by_password_change_access_token() { long issuedAt = new Date().getTime(); String issuer = UrlUtils.cellRoot(TEST_CELL1); String subject = "account2"; - String schema = ""; // Create password change access token. PasswordChangeAccessToken validToken = new PasswordChangeAccessToken( issuedAt, - issuer, subject, schema); + issuer, subject, SCHEMA_SAMPLE, SCOPE_SAMPLE); // Password change access token can not access data. ResourceUtils.retrieve(validToken.toTokenString(), diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/AccountRoleLinkTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/AccountRoleLinkTest.java index e8a9eba86..8eb7a14f3 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/AccountRoleLinkTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/AccountRoleLinkTest.java @@ -24,7 +24,7 @@ import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; @@ -372,7 +372,7 @@ public AccountRoleLinkTest() { // Account登録 TResponse accountRes = AccountUtils.create(MASTER_TOKEN_NAME, Setup.TEST_CELL1, testAccountName, testAccountPass, HttpStatus.SC_CREATED); - accountUrl = PersoniumCoreUtils.decodeUrlComp(accountRes.getLocationHeader()); + accountUrl = CommonUtils.decodeUrlComp(accountRes.getLocationHeader()); // Role登録 RoleUtils.create(Setup.TEST_CELL1, MASTER_TOKEN_NAME, testRoleName, HttpStatus.SC_CREATED); diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/BoxBulkDeletionTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/BoxBulkDeletionTest.java index 6d24c0c5e..16985b8b7 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/BoxBulkDeletionTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/BoxBulkDeletionTest.java @@ -27,7 +27,7 @@ import org.junit.runner.RunWith; import org.odata4j.edm.EdmSimpleType; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.core.rs.PersoniumCoreApplication; @@ -210,7 +210,7 @@ public void error_recursive_header_is_false() { // --------------- BoxUtils.get(cellName, MASTER_TOKEN_NAME, boxName, HttpStatus.SC_OK); PersoniumCoreException expected = PersoniumCoreException.Misc.PRECONDITION_FAILED.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); checkErrorResponseBody(response, expected.getCode(), expected.getMessage()); } finally { BoxUtils.deleteRecursive(cellName, boxName, MASTER_TOKEN_NAME, -1); @@ -247,7 +247,7 @@ public void error_recursive_header_not_exists() { // --------------- BoxUtils.get(cellName, MASTER_TOKEN_NAME, boxName, HttpStatus.SC_OK); PersoniumCoreException expected = PersoniumCoreException.Misc.PRECONDITION_FAILED.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); checkErrorResponseBody(response, expected.getCode(), expected.getMessage()); } finally { BoxUtils.deleteRecursive(cellName, boxName, MASTER_TOKEN_NAME, -1); diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/CellCtlUtils.java b/src/test/java/io/personium/test/jersey/cell/ctl/CellCtlUtils.java index 2852473ec..e36f54e3e 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/CellCtlUtils.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/CellCtlUtils.java @@ -20,7 +20,7 @@ import org.apache.http.HttpStatus; import org.json.simple.JSONObject; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.test.jersey.AbstractCase; import io.personium.test.jersey.PersoniumRequest; import io.personium.test.utils.Http; @@ -268,7 +268,7 @@ public static void deleteExtRole(String cellName, Http.request("cell/extRole/extRole-delete.txt") .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", cellName) - .with("extRoleName", PersoniumCoreUtils.encodeUrlComp(testExtRoleName)) + .with("extRoleName", CommonUtils.encodeUrlComp(testExtRoleName)) .with("relationName", relName) .with("relationBoxName", relBoxName) .returns() @@ -287,7 +287,7 @@ public static void deleteExtRole(String cellName, Http.request("cell/extRole/extRole-delete.txt") .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", cellName) - .with("extRoleName", PersoniumCoreUtils.encodeUrlComp(testExtRoleName)) + .with("extRoleName", CommonUtils.encodeUrlComp(testExtRoleName)) .with("relationName", "'" + relationName + "'") .with("relationBoxName", "null") .returns() @@ -303,7 +303,7 @@ public static void deleteExtRole(String cellName, String testExtRoleName) { Http.request("cell/extRole/extRole-delete.txt") .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", cellName) - .with("extRoleName", PersoniumCoreUtils.encodeUrlComp(testExtRoleName)) + .with("extRoleName", CommonUtils.encodeUrlComp(testExtRoleName)) .with("relationName", "null") .with("relationBoxName", "null") .returns() diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellDeleteTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellDeleteTest.java index 9648f851e..bcf48239a 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellDeleteTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellDeleteTest.java @@ -21,7 +21,7 @@ import org.junit.Test; import org.junit.experimental.categories.Category; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.model.ctl.Relation; import io.personium.core.model.ctl.Role; import io.personium.core.rs.PersoniumCoreApplication; @@ -66,12 +66,12 @@ public void normal_delete_extcell_linked_with_role() { // 準備。ExtCell、ロール作ってリンクさせる。 ExtCellUtils.create(token, cellName, extCellUrl, HttpStatus.SC_CREATED); RoleUtils.create(cellName, token, roleName, boxName, HttpStatus.SC_CREATED); - LinksUtils.createLinksExtCell(cellName, PersoniumCoreUtils.encodeUrlComp(extCellUrl), + LinksUtils.createLinksExtCell(cellName, CommonUtils.encodeUrlComp(extCellUrl), Role.EDM_TYPE_NAME, roleName, boxName, token, HttpStatus.SC_NO_CONTENT); ExtCellUtils.delete(token, cellName, extCellUrl, HttpStatus.SC_NO_CONTENT); } finally { - LinksUtils.deleteLinksExtCell(cellName, PersoniumCoreUtils.encodeUrlComp(extCellUrl), + LinksUtils.deleteLinksExtCell(cellName, CommonUtils.encodeUrlComp(extCellUrl), Role.EDM_TYPE_NAME, roleName, boxName, token, -1); RoleUtils.delete(cellName, token, roleName, boxName, -1); ExtCellUtils.delete(token, cellName, extCellUrl, -1); @@ -97,12 +97,12 @@ public final void normal_delete_extcell_linked_with_relation() { // 準備。ExtCell、Relation作ってリンクさせる。 ExtCellUtils.create(token, cellName, extCellUrl, HttpStatus.SC_CREATED); RelationUtils.create(cellName, token, body, HttpStatus.SC_CREATED); - LinksUtils.createLinksExtCell(cellName, PersoniumCoreUtils.encodeUrlComp(extCellUrl), + LinksUtils.createLinksExtCell(cellName, CommonUtils.encodeUrlComp(extCellUrl), Relation.EDM_TYPE_NAME, relationName, null, token, HttpStatus.SC_NO_CONTENT); ExtCellUtils.delete(token, cellName, extCellUrl, HttpStatus.SC_NO_CONTENT); } finally { - LinksUtils.deleteLinksExtCell(cellName, PersoniumCoreUtils.encodeUrlComp(extCellUrl), + LinksUtils.deleteLinksExtCell(cellName, CommonUtils.encodeUrlComp(extCellUrl), Relation.EDM_TYPE_NAME, relationName, null, token, -1); RelationUtils.delete(cellName, token, relationName, boxName, -1); ExtCellUtils.delete(token, cellName, extCellUrl, -1); diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellListTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellListTest.java index 793b3ae28..68752dab8 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellListTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellListTest.java @@ -31,7 +31,7 @@ import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; @@ -66,7 +66,7 @@ public ExtCellListTest() { @Test public final void test_ExtCell_normal_json() { String expectedMetadataUri = "http://localhost:9998/testcell1/__ctl/ExtCell('" - + PersoniumCoreUtils.encodeUrlComp(testExtCellUrl) + "')"; + + CommonUtils.encodeUrlComp(testExtCellUrl) + "')"; TResponse res = ExtCellUtils.list(token, cellName, "application/json", HttpStatus.SC_OK); JSONObject body = res.bodyAsJson(); @@ -87,7 +87,7 @@ public final void test_ExtCell_normal_json() { */ @Test public final void test_ExtCell_normal_xml() { - String expectedExtCellFunction = "ExtCell('" + PersoniumCoreUtils.encodeUrlComp(testExtCellUrl) + "')"; + String expectedExtCellFunction = "ExtCell('" + CommonUtils.encodeUrlComp(testExtCellUrl) + "')"; String expectedMetadataUri = "http://localhost:9998/testcell1/__ctl/" + expectedExtCellFunction; TResponse res = ExtCellUtils.list(token, cellName, "application/xml", HttpStatus.SC_OK); diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellReadTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellReadTest.java index 0efd21b6f..ce96714e4 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellReadTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/ExtCellReadTest.java @@ -32,7 +32,7 @@ import org.w3c.dom.Element; import org.w3c.dom.NodeList; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; @@ -68,7 +68,7 @@ public ExtCellReadTest() { @Test public final void test_ExtCell_normal_json() { String expectedMetadataUri = "http://localhost:9998/testcell1/__ctl/ExtCell('" - + PersoniumCoreUtils.encodeUrlComp(extCellUrl) + "')"; + + CommonUtils.encodeUrlComp(extCellUrl) + "')"; try { ExtCellUtils.create(token, cellName, extCellUrl, HttpStatus.SC_CREATED); @@ -96,7 +96,7 @@ public final void test_ExtCell_normal_json() { */ @Test public final void test_ExtCell_normal_xml() { - String expectedExtCellFunction = "ExtCell('" + PersoniumCoreUtils.encodeUrlComp(extCellUrl) + "')"; + String expectedExtCellFunction = "ExtCell('" + CommonUtils.encodeUrlComp(extCellUrl) + "')"; String expectedMetadataUri = "http://localhost:9998/testcell1/__ctl/" + expectedExtCellFunction; try { ExtCellUtils.create(token, cellName, extCellUrl, HttpStatus.SC_CREATED); diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleDeleteTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleDeleteTest.java index 99ada4a36..f28daf70b 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleDeleteTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleDeleteTest.java @@ -25,7 +25,7 @@ import org.odata4j.core.ODataConstants; import org.odata4j.core.ODataVersion; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.core.model.ctl.Role; import io.personium.core.rs.PersoniumCoreApplication; @@ -126,7 +126,7 @@ private void deleteExtRole( TResponse res = Http.request("cell/extRole/extRole-delete.txt") .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", cellName) - .with("extRoleName", PersoniumCoreUtils.encodeUrlComp(testExtRoleName)) + .with("extRoleName", CommonUtils.encodeUrlComp(testExtRoleName)) .with("relationName", relationName) .with("relationBoxName", relationBoxName) .returns() @@ -146,7 +146,7 @@ private void deleteExtRole() { Http.request("cell/extRole/extRole-delete-norelation.txt") .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", cellName) - .with("extRoleName", PersoniumCoreUtils.encodeUrlComp(testExtRoleName)) + .with("extRoleName", CommonUtils.encodeUrlComp(testExtRoleName)) .returns() .statusCode(HttpStatus.SC_NOT_FOUND); } @@ -175,12 +175,12 @@ public final void normal_delete_extrole_linked_with_role() { RelationUtils.create(cellName, token, relationBody, -1); ExtRoleUtils.create(token, cellName, extRoleBody, HttpStatus.SC_CREATED); RoleUtils.create(cellName, token, roleName, boxName, HttpStatus.SC_CREATED); - LinksUtils.createLinksExtRole(cellName, PersoniumCoreUtils.encodeUrlComp(extRoleName), + LinksUtils.createLinksExtRole(cellName, CommonUtils.encodeUrlComp(extRoleName), "relation", null, Role.EDM_TYPE_NAME, roleName, null, token, HttpStatus.SC_NO_CONTENT); ExtRoleUtils.delete(cellName, extRoleName, "relation", null, token, HttpStatus.SC_NO_CONTENT); } finally { - LinksUtils.deleteLinksExtRole(cellName, PersoniumCoreUtils.encodeUrlComp(extRoleName), + LinksUtils.deleteLinksExtRole(cellName, CommonUtils.encodeUrlComp(extRoleName), "relation", null, Role.EDM_TYPE_NAME, roleName, null, token, -1); RoleUtils.delete(cellName, token, roleName, boxName, -1); ExtRoleUtils.delete(cellName, extRoleName, "relation", null, token, -1); diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleLinkTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleLinkTest.java index 4317f63f0..9c84d92d0 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleLinkTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/ExtRoleLinkTest.java @@ -20,7 +20,7 @@ import org.junit.Test; import org.junit.experimental.categories.Category; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.model.ctl.Relation; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.test.categories.Integration; @@ -62,7 +62,7 @@ public ExtRoleLinkTest() { CellCtlUtils.createExtRole(testCellName, testExtRoleName, relationName, relationBoxName); String testExtRoleUrl = extRoleUrl(testCellName, - relationBoxName, relationName, PersoniumCoreUtils.encodeUrlComp(testExtRoleName)); + relationBoxName, relationName, CommonUtils.encodeUrlComp(testExtRoleName)); // $links作成 Http.request("cell/link.txt") @@ -91,7 +91,7 @@ public ExtRoleLinkTest() { CellCtlUtils.createRelation(testCellName, relationName, relationBoxName); CellCtlUtils.createExtRole(testCellName, testExtRoleName, relationName, relationBoxName); - LinksUtils.deleteLinksExtRole(testCellName, PersoniumCoreUtils.encodeUrlComp(testExtRoleName), + LinksUtils.deleteLinksExtRole(testCellName, CommonUtils.encodeUrlComp(testExtRoleName), relationName, relationBoxName, Relation.EDM_TYPE_NAME, relationName, relationBoxName, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_BAD_REQUEST); } finally { @@ -113,7 +113,7 @@ public ExtRoleLinkTest() { CellCtlUtils.createExtRole(testCellName, testExtRoleName, relationName, relationBoxName); String testExtRoleUrl = extRoleUrl(testCellName, - relationBoxName, relationName, PersoniumCoreUtils.encodeUrlComp(testExtRoleName)); + relationBoxName, relationName, CommonUtils.encodeUrlComp(testExtRoleName)); // $links取得 Http.request("cell/link-list.txt") diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/hashpassword/SCryptHashPasswordTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/hashpassword/SCryptHashPasswordTest.java index e56b3035b..ba4886cef 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/hashpassword/SCryptHashPasswordTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/hashpassword/SCryptHashPasswordTest.java @@ -34,7 +34,7 @@ import org.odata4j.core.ODataConstants; import org.odata4j.core.ODataVersion; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.core.PersoniumUnitConfig.Security; import io.personium.core.auth.OAuth2Helper; @@ -299,7 +299,7 @@ private PersoniumResponse requestMyPassword(String headerAuthorization, String h // リクエストヘッダをセット HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, "Bearer " + headerAuthorization); - requestheaders.put(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL, headerCredential); + requestheaders.put(CommonUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL, headerCredential); try { res = rest.put(UrlUtils.cellRoot(cellName) + "__mypassword", "", requestheaders); diff --git a/src/test/java/io/personium/test/jersey/cell/ctl/hashpassword/Sha256HashPasswordTest.java b/src/test/java/io/personium/test/jersey/cell/ctl/hashpassword/Sha256HashPasswordTest.java index 0a2701920..1183ea06f 100644 --- a/src/test/java/io/personium/test/jersey/cell/ctl/hashpassword/Sha256HashPasswordTest.java +++ b/src/test/java/io/personium/test/jersey/cell/ctl/hashpassword/Sha256HashPasswordTest.java @@ -34,7 +34,7 @@ import org.odata4j.core.ODataConstants; import org.odata4j.core.ODataVersion; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.core.PersoniumUnitConfig.Security; import io.personium.core.auth.OAuth2Helper; @@ -226,7 +226,7 @@ private PersoniumResponse requestMyPassword(String headerAuthorization, String h // set request header HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, "Bearer " + headerAuthorization); - requestheaders.put(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL, headerCredential); + requestheaders.put(CommonUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL, headerCredential); try { res = rest.put(UrlUtils.cellRoot(cellName) + "__mypassword", "", requestheaders); diff --git a/src/test/java/io/personium/test/setup/Setup.java b/src/test/java/io/personium/test/setup/Setup.java index 969267b68..8b7b3e3f0 100644 --- a/src/test/java/io/personium/test/setup/Setup.java +++ b/src/test/java/io/personium/test/setup/Setup.java @@ -38,7 +38,7 @@ import org.junit.runner.RunWith; import org.odata4j.edm.EdmSimpleType; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.Box; @@ -357,7 +357,7 @@ private List settingExtRole(String extCell) { for (int i = 0; i < NUM_ROLES; i++) { // ExtRole作成 ExtRoleConfig extRole = new ExtRoleConfig(); - extRole.extRole = UrlUtils.roleResource(extCell, Box.DEFAULT_BOX_NAME, "role" + i); + extRole.extRole = UrlUtils.roleResource(extCell, Box.MAIN_BOX_NAME, "role" + i); extRole.relationName = CELL_RELATION; extRole.relationBoxName = null; extRoles.add(extRole); @@ -393,7 +393,7 @@ private void create(Config conf) { HttpStatus.SC_CREATED); // RelationとExtCellの$link for (String extCell : relation.linkExtCell) { - LinksUtils.createLinksExtCell(conf.cellName, PersoniumCoreUtils.encodeUrlComp(extCell), + LinksUtils.createLinksExtCell(conf.cellName, CommonUtils.encodeUrlComp(extCell), Relation.EDM_TYPE_NAME, relation.name, null, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_NO_CONTENT); } @@ -422,7 +422,7 @@ private void create(Config conf) { // ExtRoleとRoleの紐付け if (role.linkExtRole != null) { for (ExtRoleConfig extRole : role.linkExtRole) { - LinksUtils.createLinksExtRole(conf.cellName, PersoniumCoreUtils.encodeUrlComp(extRole.extRole), + LinksUtils.createLinksExtRole(conf.cellName, CommonUtils.encodeUrlComp(extRole.extRole), extRole.relationName, extRole.relationBoxName, Role.EDM_TYPE_NAME, role.roleName, null, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_NO_CONTENT); } @@ -430,7 +430,7 @@ private void create(Config conf) { if ("testcell2".equals(conf.cellName)) { // ExtCellとロールの結びつけ // testcell2のtestxell1向けのExtCellにrole2(readができるロール)を結びつけてやる - this.linkExtCelltoRole(PersoniumCoreUtils.encodeUrlComp(UrlUtils.cellRoot("testcell1")), conf.cellName, + this.linkExtCelltoRole(CommonUtils.encodeUrlComp(UrlUtils.cellRoot("testcell1")), conf.cellName, roleUrl); } } @@ -1286,7 +1286,7 @@ final PersoniumResponse createCell(final Config config) { // Owner指定があればセット String owner = config.owner; if (owner != null) { - requestheaders.put(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_UNIT_USER, owner); + requestheaders.put(CommonUtils.HttpHeaders.X_PERSONIUM_UNIT_USER, owner); } // リクエストボディを生成 diff --git a/src/test/java/io/personium/test/unit/core/UrlUtils.java b/src/test/java/io/personium/test/unit/core/UrlUtils.java index dac44204d..8e26fb0b2 100644 --- a/src/test/java/io/personium/test/unit/core/UrlUtils.java +++ b/src/test/java/io/personium/test/unit/core/UrlUtils.java @@ -444,7 +444,7 @@ public static String userData(final String cellName, public static String roleResource(final String cellName, final String boxName, final String roleName) { String box = null; if (boxName == null) { - box = Box.DEFAULT_BOX_NAME; + box = Box.MAIN_BOX_NAME; } else { box = boxName; } @@ -502,7 +502,7 @@ public static String relationClassUrl(final String cellName, final String relati * @return unit local RelationClassURL */ public static String unitLocalRelationClassUrl(final String cellName, final String relationName) { - return String.format("%s%s/__relation/__/%s", UriUtils.SCHEME_UNIT_URI, cellName, relationName); + return String.format("%s%s/__relation/__/%s", UriUtils.SCHEME_LOCALUNIT + ":/", cellName, relationName); } /** @@ -522,7 +522,7 @@ public static String roleClassUrl(final String cellName, final String roleName) * @return unit local RoleClassURL */ public static String unitLocalRoleClassUrl(final String cellName, final String roleName) { - return String.format("%s%s/__role/__/%s", UriUtils.SCHEME_UNIT_URI, cellName, roleName); + return String.format("%s%s/__role/__/%s", UriUtils.SCHEME_LOCALUNIT + ":/", cellName, roleName); } /** diff --git a/src/test/java/io/personium/test/unit/core/jersey/filter/PersoniumCoreContainerFilterTest.java b/src/test/java/io/personium/test/unit/core/jersey/filter/PersoniumCoreContainerFilterTest.java index dc42101c8..53ea7b6c4 100644 --- a/src/test/java/io/personium/test/unit/core/jersey/filter/PersoniumCoreContainerFilterTest.java +++ b/src/test/java/io/personium/test/unit/core/jersey/filter/PersoniumCoreContainerFilterTest.java @@ -33,7 +33,7 @@ import org.junit.Test; import org.junit.experimental.categories.Category; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.jersey.filter.PersoniumCoreContainerFilter; import io.personium.test.categories.Unit; @@ -63,20 +63,20 @@ public void testFilterContainerRequest() throws Exception { mockPD); MultivaluedMap headers = request.getHeaders(); // メソッドオーバーライド - headers.add(PersoniumCoreUtils.HttpHeaders.X_HTTP_METHOD_OVERRIDE, HttpMethod.OPTIONS); + headers.add(CommonUtils.HttpHeaders.X_HTTP_METHOD_OVERRIDE, HttpMethod.OPTIONS); // ヘッダオーバーライド String authzValue = "Bearer tokenstring"; String acceptValue = "text/html"; String contentTypeValue = "application/xml"; - headers.add(PersoniumCoreUtils.HttpHeaders.X_OVERRIDE, HttpHeaders.AUTHORIZATION + ": " + authzValue); + headers.add(CommonUtils.HttpHeaders.X_OVERRIDE, HttpHeaders.AUTHORIZATION + ": " + authzValue); headers.add(HttpHeaders.ACCEPT, contentTypeValue); - headers.add(PersoniumCoreUtils.HttpHeaders.X_OVERRIDE, HttpHeaders.ACCEPT + ": " + acceptValue); + headers.add(CommonUtils.HttpHeaders.X_OVERRIDE, HttpHeaders.ACCEPT + ": " + acceptValue); headers.add(HttpHeaders.CONTENT_TYPE, contentTypeValue); // X-FORWARDED-* 系のヘッダ設定 String scheme = "https"; String host = "example.org"; - headers.add(PersoniumCoreUtils.HttpHeaders.X_FORWARDED_PROTO, scheme); - headers.add(PersoniumCoreUtils.HttpHeaders.X_FORWARDED_HOST, host); + headers.add(CommonUtils.HttpHeaders.X_FORWARDED_PROTO, scheme); + headers.add(CommonUtils.HttpHeaders.X_FORWARDED_HOST, host); // 被テスト処理の実行 containerFilter.filter(request); diff --git a/src/test/java/io/personium/test/utils/AuthzUtils.java b/src/test/java/io/personium/test/utils/AuthzUtils.java index d1acfa6be..6eefba5e3 100644 --- a/src/test/java/io/personium/test/utils/AuthzUtils.java +++ b/src/test/java/io/personium/test/utils/AuthzUtils.java @@ -22,7 +22,7 @@ import org.apache.commons.lang.CharEncoding; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreMessageUtils; import io.personium.core.model.Box; import io.personium.core.rs.cell.AuthResourceUtils; @@ -341,15 +341,15 @@ public static String createDefaultHtml(String clientId, String redirectUriStr, S paramsList.add(AuthResourceUtils.getJavascript("ajax.js")); paramsList.add(PersoniumCoreMessageUtils.getMessage("PS-AU-0001")); - paramsList.add(clientId + Box.DEFAULT_BOX_NAME + "/profile.json"); - paramsList.add(cellUrl + Box.DEFAULT_BOX_NAME + "/profile.json"); + paramsList.add(clientId + Box.MAIN_BOX_NAME + "/profile.json"); + paramsList.add(cellUrl + Box.MAIN_BOX_NAME + "/profile.json"); paramsList.add(PersoniumCoreMessageUtils.getMessage("PS-AU-0001")); paramsList.add(cellUrl + "__authz"); paramsList.add(PersoniumCoreMessageUtils.getMessage("PS-AU-0002")); Object[] params = paramsList.toArray(); - String html = PersoniumCoreUtils.readStringResource("html/authform.html", CharEncoding.UTF_8); + String html = CommonUtils.readStringResource("html/authform.html", CharEncoding.UTF_8); html = MessageFormat.format(html, params); return html; @@ -378,15 +378,15 @@ public static String createDefaultPasswordChangeHtml(String clientId, String red paramsList.add(AuthResourceUtils.getJavascript("ajax.js")); paramsList.add(PersoniumCoreMessageUtils.getMessage("PS-AU-0001")); - paramsList.add(clientId + Box.DEFAULT_BOX_NAME + "/profile.json"); - paramsList.add(cellUrl + Box.DEFAULT_BOX_NAME + "/profile.json"); + paramsList.add(clientId + Box.MAIN_BOX_NAME + "/profile.json"); + paramsList.add(cellUrl + Box.MAIN_BOX_NAME + "/profile.json"); paramsList.add(PersoniumCoreMessageUtils.getMessage("PS-AU-0001")); paramsList.add(cellUrl + "__authz"); paramsList.add(PersoniumCoreMessageUtils.getMessage("PS-AU-0006")); Object[] params = paramsList.toArray(); - String html = PersoniumCoreUtils.readStringResource("html/authform_passwordchange.html", CharEncoding.UTF_8); + String html = CommonUtils.readStringResource("html/authform_passwordchange.html", CharEncoding.UTF_8); html = MessageFormat.format(html, params); return html; diff --git a/src/test/java/io/personium/test/utils/CellUtils.java b/src/test/java/io/personium/test/utils/CellUtils.java index 6757c0d2e..0ab67fa9e 100644 --- a/src/test/java/io/personium/test/utils/CellUtils.java +++ b/src/test/java/io/personium/test/utils/CellUtils.java @@ -28,7 +28,7 @@ import org.apache.http.HttpStatus; import org.json.simple.JSONObject; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.test.jersey.AbstractCase; import io.personium.test.jersey.PersoniumException; import io.personium.test.jersey.PersoniumRequest; @@ -643,7 +643,7 @@ public static PersoniumResponse changePassword(String cellName, String newPasswo // リクエストヘッダをセット HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, authorization); - requestheaders.put(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL, newPassword); + requestheaders.put(CommonUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL, newPassword); return rest.put(UrlUtils.cellRoot(cellName) + "__mypassword", "", requestheaders); } @@ -675,7 +675,7 @@ public static PersoniumResponse schemaAuthenticateWithBasic( // リクエストヘッダをセット String schemaCellUrl = UrlUtils.cellRoot(schemaCell); String authorization = - PersoniumCoreUtils.createBasicAuthzHeader(schemaCellUrl, schemaAuthenticatedToken); + CommonUtils.createBasicAuthzHeader(schemaCellUrl, schemaAuthenticatedToken); HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); diff --git a/src/test/java/io/personium/test/utils/ExtCellUtils.java b/src/test/java/io/personium/test/utils/ExtCellUtils.java index 856b7da47..354989746 100644 --- a/src/test/java/io/personium/test/utils/ExtCellUtils.java +++ b/src/test/java/io/personium/test/utils/ExtCellUtils.java @@ -20,7 +20,7 @@ import org.json.simple.JSONObject; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; /** * ExtCell用ユーティリティ. @@ -58,7 +58,7 @@ public static TResponse get(final String token, final String cellName, .with("cellPath", cellName) .with("token", token) .with("accept", accept) - .with("url", PersoniumCoreUtils.encodeUrlComp(url)) + .with("url", CommonUtils.encodeUrlComp(url)) .returns() .debug() .statusCode(code); @@ -160,7 +160,7 @@ public static void update(final String token, final String cellName, .with("cellPath", cellName) .with("token", token) .with("accept", "application/xml") - .with("url", PersoniumCoreUtils.encodeUrlComp(url)) + .with("url", CommonUtils.encodeUrlComp(url)) .with("newUrl", newUrl) .returns() .statusCode(code); @@ -180,7 +180,7 @@ public static void updateMerge(final String token, final String cellName, .with("cellPath", cellName) .with("token", token) .with("accept", "application/xml") - .with("url", PersoniumCoreUtils.encodeUrlComp(url)) + .with("url", CommonUtils.encodeUrlComp(url)) .with("body", body) .returns() .statusCode(code); @@ -196,7 +196,7 @@ public static void delete(final String token, final String cellName, final Strin Http.request("cell/extCell-delete.txt") .with("cellPath", cellName) .with("token", token) - .with("url", PersoniumCoreUtils.encodeUrlComp(url)) + .with("url", CommonUtils.encodeUrlComp(url)) .returns(); } @@ -212,7 +212,7 @@ public static void delete(final String token, final String cellName, Http.request("cell/extCell-delete.txt") .with("cellPath", cellName) .with("token", token) - .with("url", PersoniumCoreUtils.encodeUrlComp(url)) + .with("url", CommonUtils.encodeUrlComp(url)) .returns() .statusCode(code); } @@ -231,7 +231,7 @@ public static void extCellAccess(String method, String cellName, String url, Str .with("method", method) .with("cellPath", cellName) .with("token", token) - .with("url", PersoniumCoreUtils.encodeUrlComp(url)) + .with("url", CommonUtils.encodeUrlComp(url)) .with("body", body) .returns() .statusCode(code); diff --git a/src/test/java/io/personium/test/utils/ExtRoleUtils.java b/src/test/java/io/personium/test/utils/ExtRoleUtils.java index f037fc949..6d21bf52d 100644 --- a/src/test/java/io/personium/test/utils/ExtRoleUtils.java +++ b/src/test/java/io/personium/test/utils/ExtRoleUtils.java @@ -22,7 +22,7 @@ import org.json.simple.JSONObject; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; /** * Httpリクエストドキュメントを利用するユーティリティ. @@ -45,7 +45,7 @@ public static TResponse get(final String token, final String cellName, final Str final String relationName, final String relationBoxName, final int code) { TResponse response = Http.request("cell/extRole/extRole-get.txt") .with("cellPath", cellName) - .with("extRoleName", PersoniumCoreUtils.encodeUrlComp(extRoleName)) + .with("extRoleName", CommonUtils.encodeUrlComp(extRoleName)) .with("relationName", relationName) .with("relationBoxName", relationBoxName) .with("token", token) @@ -162,7 +162,7 @@ public static void update(final String token, final String cellName, final Strin final String newRelation, final String newRelationBox, final int code) { Http.request("cell/extRole/extRole-update.txt") .with("cellPath", cellName) - .with("extRoleName", PersoniumCoreUtils.encodeUrlComp(extRoleName)) + .with("extRoleName", CommonUtils.encodeUrlComp(extRoleName)) .with("relationName", relationName) .with("relationBoxName", relationBoxName) .with("newextRoleName", newextRoleName) @@ -186,7 +186,7 @@ public static void update(final String token, final String cellName, final Strin final String relationName, final String relationBoxName, final JSONObject body, final int code) { Http.request("cell/extRole/extRole-update-nobody.txt") .with("cellPath", cellName) - .with("extRoleName", PersoniumCoreUtils.encodeUrlComp(extRoleName)) + .with("extRoleName", CommonUtils.encodeUrlComp(extRoleName)) .with("relationName", relationName) .with("relationBoxName", relationBoxName) .with("token", token) @@ -209,7 +209,7 @@ public static void updateMerge(final String token, final String cellName, final final String relationName, final String relationBoxName, final JSONObject body, final int code) { Http.request("cell/extRole/extRole-update-merge.txt") .with("cellPath", cellName) - .with("extRoleName", PersoniumCoreUtils.encodeUrlComp(extRoleName)) + .with("extRoleName", CommonUtils.encodeUrlComp(extRoleName)) .with("relationName", relationName) .with("relationBoxName", relationBoxName) .with("token", token) @@ -233,7 +233,7 @@ public static void delete(String cellName, String extRoleUrl, String relationBoxNameStr = relationBoxName == null ? "null" : "'" + relationBoxName + "'"; // CHECKSTYLE IGNORE Http.request("cell/extRole/extRole-delete.txt") .with("cellPath", cellName) - .with("extRoleName", PersoniumCoreUtils.encodeUrlComp(extRoleUrl)) + .with("extRoleName", CommonUtils.encodeUrlComp(extRoleUrl)) .with("relationName", relationNameStr) .with("relationBoxName", relationBoxNameStr) .with("token", token) diff --git a/src/test/java/io/personium/test/utils/ReceivedMessageUtils.java b/src/test/java/io/personium/test/utils/ReceivedMessageUtils.java index 516d7959f..87ed9e00f 100644 --- a/src/test/java/io/personium/test/utils/ReceivedMessageUtils.java +++ b/src/test/java/io/personium/test/utils/ReceivedMessageUtils.java @@ -51,7 +51,7 @@ public static TResponse receive( String targetCellUrl = UrlUtils.cellRoot(cellName); String cellUrl = UrlUtils.cellRoot(Setup.TEST_CELL2); List list = new ArrayList(); - TransCellAccessToken ttk = new TransCellAccessToken(cellUrl, cellUrl, targetCellUrl, list, ""); + TransCellAccessToken ttk = new TransCellAccessToken(cellUrl, cellUrl, targetCellUrl, list, "", null); token = ttk.toTokenString(); } TResponse response = Http.request("received-message.txt") diff --git a/src/test/java/io/personium/test/utils/ResourceUtils.java b/src/test/java/io/personium/test/utils/ResourceUtils.java index 757db4ef1..b1ab93f64 100644 --- a/src/test/java/io/personium/test/utils/ResourceUtils.java +++ b/src/test/java/io/personium/test/utils/ResourceUtils.java @@ -22,10 +22,9 @@ import javax.ws.rs.core.MediaType; -import org.apache.http.HttpStatus; import org.json.simple.JSONObject; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.OAuth2Helper; import io.personium.test.jersey.bar.BarInstallTestUtils; @@ -130,8 +129,8 @@ public static TResponse deleteUserDataLinks(String userDataId, // リクエスト実行 TResponse res = Http.request("box/odatacol/delete-link.txt").with("cell", cell).with("box", box) .with("collection", col).with("entityType", entity) - .with("id", PersoniumCoreUtils.encodeUrlComp(userDataId)) - .with("navProp", "_" + navProp).with("navKey", PersoniumCoreUtils.encodeUrlComp(navPropId)) + .with("id", CommonUtils.encodeUrlComp(userDataId)) + .with("navProp", "_" + navProp).with("navKey", CommonUtils.encodeUrlComp(navPropId)) .with("contentType", MediaType.APPLICATION_JSON).with("token", PersoniumUnitConfig.getMasterToken()) .with("ifMatch", "*").returns().statusCode(code); return res; @@ -392,20 +391,6 @@ public static TResponse requestUtilWithAuthSchema(String method, String authoriz return res; } - /** - * リフレッシュトークン認証を実行するユーティリティー. - * @param cellName セル名 - * @param refreshToken リフレッシュトークン - * @return レスポンス - */ - public static TResponse refreshTokenAuthCl(String cellName, String refreshToken) { - TResponse res = Http.request("authn/refresh-cl.txt") - .with("remoteCell", cellName) - .with("refresh_token", refreshToken) - .returns() - .statusCode(HttpStatus.SC_OK); - return res; - } /** * ログ情報取得(PROPFIND). @@ -422,7 +407,7 @@ public static TResponse logCollectionPropfind(String cellName, String accessToken, int code) { return Http.request("cell/log-propfind-with-nobody.txt") - .with("METHOD", io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND) + .with("METHOD", io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND) .with("token", accessToken) .with("cellPath", cellName) .with("collection", collection) diff --git a/src/test/java/io/personium/test/utils/UserDataUtils.java b/src/test/java/io/personium/test/utils/UserDataUtils.java index fa2e75f2d..f1a6be9bf 100644 --- a/src/test/java/io/personium/test/utils/UserDataUtils.java +++ b/src/test/java/io/personium/test/utils/UserDataUtils.java @@ -25,7 +25,7 @@ import org.apache.http.HttpStatus; import org.json.simple.JSONObject; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.test.jersey.AbstractCase; import io.personium.test.jersey.PersoniumRequest; @@ -204,7 +204,7 @@ public static TResponse getWithQuery(final String cellName, .with("box", boxName) .with("collection", colName) .with("entityType", entTypeName) - .with("id", PersoniumCoreUtils.encodeUrlComp(id)) + .with("id", CommonUtils.encodeUrlComp(id)) .with("accept", MediaType.APPLICATION_JSON) .with("token", token) .with("query", query) @@ -603,7 +603,7 @@ public static TResponse delete(String token, .with("box", boxName) .with("collection", colName) .with("entityType", entityType) - .with("id", PersoniumCoreUtils.encodeUrlComp(id)) + .with("id", CommonUtils.encodeUrlComp(id)) .with("token", token) .with("ifMatch", "*") .returns()