From a8868503cb7fc6a33b0917194403885d443abd02 Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Mon, 29 Jul 2019 13:51:08 +0900 Subject: [PATCH 01/69] For v1.7.17 --- pom.xml | 2 +- src/main/resources/personium-unit-config-default.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index f9c23ce4c..1c9170c09 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ io.personium personium-core war - 1.7.16_es6.6.1 + 1.7.17_es6.6.1-SNAPSHOT personium-core Maven Webapp http://maven.apache.org diff --git a/src/main/resources/personium-unit-config-default.properties b/src/main/resources/personium-unit-config-default.properties index 506eef17f..970c9034a 100644 --- a/src/main/resources/personium-unit-config-default.properties +++ b/src/main/resources/personium-unit-config-default.properties @@ -23,7 +23,7 @@ ################################################# # core version -io.personium.core.version=1.7.16 +io.personium.core.version=1.7.17 # thread pool num. io.personium.core.thread.pool.num.io.cell=10 From 5ab18a3fedbc494a4867374ed79b64b7a82e457c Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Mon, 29 Jul 2019 17:28:05 +0900 Subject: [PATCH 02/69] Fix a typo --- src/test/java/io/personium/core/PersoniumCoreLogTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/io/personium/core/PersoniumCoreLogTest.java b/src/test/java/io/personium/core/PersoniumCoreLogTest.java index fd7991f14..2ec594ebc 100644 --- a/src/test/java/io/personium/core/PersoniumCoreLogTest.java +++ b/src/test/java/io/personium/core/PersoniumCoreLogTest.java @@ -32,7 +32,7 @@ import org.slf4j.Marker; /** - * EsModelの単体テストケース. + * PersoniumCoreLogの単体テストケース. */ @RunWith(PersoniumIntegTestRunner.class) From ed79f262d595bf08fb6569ad5bf85ad392e96325 Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Mon, 29 Jul 2019 18:46:41 +0900 Subject: [PATCH 03/69] Add time measurement feature to PersoniumCoreLog --- .../io/personium/core/PersoniumCoreLog.java | 66 +++++++++++++++---- 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/src/main/java/io/personium/core/PersoniumCoreLog.java b/src/main/java/io/personium/core/PersoniumCoreLog.java index 842b0074f..0a26a7b06 100644 --- a/src/main/java/io/personium/core/PersoniumCoreLog.java +++ b/src/main/java/io/personium/core/PersoniumCoreLog.java @@ -360,6 +360,7 @@ public static class Misc { String code; Severity severity; Throwable reason; + long startTime = 0L; /** * Force load inner class. @@ -374,20 +375,31 @@ public static void loadConfig() { /** * constructor. - * @param severity error level - * @param message error message + * @param code log code + * @param severity log level + * @param message message */ - PersoniumCoreLog(final String code, - final Severity severity, - final String message) { + PersoniumCoreLog(final String code, final Severity severity, final String message) { this.code = code; this.severity = severity; this.message = message; } + /** + * constructor. + * @param code log code + * @param severity log level + * @param message message + * @param reason error reason + */ + PersoniumCoreLog(final String code, final Severity severity, final String message, final Throwable reason) { + this(code, severity, message); + this.reason = reason; + } + /** * Factory method. - * @param code error code + * @param code log code * @return PersoniumCoreLog */ public static PersoniumCoreLog create(String code) { @@ -405,8 +417,8 @@ public static PersoniumCoreLog create(String code) { } /** - * Return error code. - * @return error code + * Return log code. + * @return log code */ public String getCode() { return this.code; @@ -432,10 +444,7 @@ public PersoniumCoreLog params(final Object... params) { */ public PersoniumCoreLog reason(final Throwable t) { //Make a clone - PersoniumCoreLog ret = new PersoniumCoreLog(this.code, this.severity, this.message); - //Set cause Exception - ret.reason = t; - return ret; + return new PersoniumCoreLog(this.code, this.severity, this.message, t); } /** @@ -445,10 +454,38 @@ public PersoniumCoreLog reason(final Throwable t) { * 2012-09-09 11:23:47.029 [main] [INFO ] CoreLog [io.personium.core.CoreLogTest#test:22] - JSON Parse Error. */ public void writeLog() { - StackTraceElement[] ste = new Throwable().getStackTrace(); - String logInfo = String.format("[%s] - [%s#%s:%s] - %s", + doWriteLog("[%s] - [%s#%s:%s] - %s", this.code, ste[1].getClassName(), ste[1].getMethodName(), ste[1].getLineNumber(), this.message); + } + + /** + * Log output with time measurement. + */ + public void writeStartLog() { + this.startTime = System.currentTimeMillis(); + writeLog(); + } + + /** + * Log output with time measurement. + * Output example) + * 2012-09-09 11:23:47.029 [main] [INFO ] CoreLog - [Elapsed time: 10ms] - [io.personium.core.CoreLogTest#test:22] - JSON Parse Error. + */ + public void writeEndLog() { + if (this.startTime == 0L) { + writeLog(); + return; + } + StackTraceElement[] ste = new Throwable().getStackTrace(); + final long elapsedTime = System.currentTimeMillis() - this.startTime; + doWriteLog("[%s] - [Elapsed time: %dms] - [%s#%s:%s] - %s", + this.code, elapsedTime, ste[1].getClassName(), ste[1].getMethodName(), ste[1].getLineNumber(), + this.message); + } + + private void doWriteLog(String msgFormat, Object... params) { + String logInfo = String.format(msgFormat, params); switch (this.severity) { case INFO: log.info(logInfo, this.reason); @@ -466,4 +503,5 @@ public void writeLog() { log.error("Message Severity Not Defined"); } } + } From 5daa6d80647a5d662a8c5811c309af61ab3a3557 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Wed, 31 Jul 2019 18:28:53 +0900 Subject: [PATCH 04/69] add support for extended "personium-localunit" url scheme syntax using two colons, which is descritbed in #284 --- .../core/PersoniumCoreException.java | 7 + .../core/rs/unit/UnitCtlResource.java | 2 +- .../io/personium/core/utils/UriUtils.java | 154 +++++++++++++----- .../resources/personium-messages.properties | 1 + .../io/personium/core/utils/UriUtilsTest.java | 47 +++++- .../test/jersey/cell/BoxUrlTest.java | 4 +- .../test/jersey/cell/UnitUserCellTest.java | 2 +- .../io/personium/test/unit/core/UrlUtils.java | 4 +- 8 files changed, 165 insertions(+), 56 deletions(-) diff --git a/src/main/java/io/personium/core/PersoniumCoreException.java b/src/main/java/io/personium/core/PersoniumCoreException.java index 91d246443..e2f54ce3a 100644 --- a/src/main/java/io/personium/core/PersoniumCoreException.java +++ b/src/main/java/io/personium/core/PersoniumCoreException.java @@ -1014,6 +1014,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/rs/unit/UnitCtlResource.java b/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java index 8ad6d33ad..5b5f7bd23 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); } diff --git a/src/main/java/io/personium/core/utils/UriUtils.java b/src/main/java/io/personium/core/utils/UriUtils.java index d5e2e7ac2..5f190b3c3 100644 --- a/src/main/java/io/personium/core/utils/UriUtils.java +++ b/src/main/java/io/personium/core/utils/UriUtils.java @@ -20,6 +20,8 @@ import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.PathSegment; @@ -31,6 +33,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; /** @@ -53,11 +56,22 @@ public class UriUtils { 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 + ":/"; + + + /** 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 localunit scheme with double colons */ + public static final String REGEX_HTTP_SUBDOMAIN = "^(http|https):\\/\\/(.+?)\\.(.*)$"; /** 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 unitUrl, String url) throws PersoniumCoreException { + if (url == null || unitUrl == null) { + throw PersoniumCoreException.Common.INVALID_URL.params("null"); + } List variations = new ArrayList(); variations.add(url); - if (url != null && unitUrl != null) { - String substitute = getUrlSubstitute(unitUrl, url); - if (!url.equals(substitute)) { - variations.add(substitute); - } + String substitute = getUrlSubstitute(unitUrl, 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); - } + if (url == null || unitUrl == null) { + throw PersoniumCoreException.Common.INVALID_URL.params("null"); + } + if (url.startsWith(SCHEME_LOCALUNIT)) { + url = convertSchemeFromLocalUnitToHttp(unitUrl, url); + } else { + url = convertSchemeFromHttpToLocalUnit(unitUrl, url); } return url; } @@ -122,19 +140,42 @@ public static boolean isLocalUnitUrl(String targetUrl) { * @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; - } + if (localUnitSchemeUrl == null || unitUrl == null) { + throw PersoniumCoreException.Common.INVALID_URL.params("null"); + } + 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; } /** @@ -146,25 +187,54 @@ public static String convertSchemeFromLocalUnitToHttp(String unitUrl, String loc */ public static String convertSchemeFromHttpToLocalUnit(String unitUrl, String url) { if (url == null) { - return url; - } - if (url.startsWith(unitUrl)) { - return url.replaceFirst(unitUrl, SCHEME_UNIT_URI); + throw PersoniumCoreException.Common.INVALID_URL.params("null"); } - - // convert to path based url - String pathBased; - try { - pathBased = convertFqdnBaseToPathBase(url); - } catch (URISyntaxException e) { + if (PersoniumUnitConfig.isPathBasedCellUrlEnabled()) { + // path based + if (url.startsWith(unitUrl)) { + // convert when url is localunit + return url.replaceFirst(unitUrl, SCHEME_LOCALUNIT + ":/"); + } + // return as-is when url is foreign return url; + } 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(); } - - if (pathBased != null && pathBased.startsWith(unitUrl)) { - return pathBased.replaceFirst(unitUrl, SCHEME_UNIT_URI); - } - - return url; } /** diff --git a/src/main/resources/personium-messages.properties b/src/main/resources/personium-messages.properties index e998910e1..a1b09b2dc 100644 --- a/src/main/resources/personium-messages.properties +++ b/src/main/resources/personium-messages.properties @@ -370,6 +370,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/test/java/io/personium/core/utils/UriUtilsTest.java b/src/test/java/io/personium/core/utils/UriUtilsTest.java index 4d81478e0..4d2ff026f 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; @@ -54,6 +54,7 @@ public void convertSchemeFromLocalUnitToHttp_Normal_pathBase() throws Exception PowerMockito.doReturn("http://cell.host.domain/") .when(UriUtils.class, "convertPathBaseToFqdnBase", "http://host.domain/cell/"); + // Single Colon assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("http://host.domain/", "personium-localunit:/cell/"), is("http://host.domain/cell/")); @@ -69,6 +70,22 @@ public void convertSchemeFromLocalUnitToHttp_Normal_pathBase() throws Exception assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", "personium-localunit:/cell/box/col/ent?$inlinecount=allpages"), is("https://host.domain/cell/box/col/ent?$inlinecount=allpages")); + + // Double Colons + 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")); + } /** @@ -88,6 +105,7 @@ public void convertSchemeFromLocalUnitToHttp_Normal_fqdnBase() throws Exception PowerMockito.doReturn("https://cell.host.domain/") .when(UriUtils.class, "convertPathBaseToFqdnBase", "https://host.domain/cell/"); + // Single Colon assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("http://host.domain/", "personium-localunit:/cell/"), is("http://cell.host.domain/")); @@ -103,6 +121,15 @@ public void convertSchemeFromLocalUnitToHttp_Normal_fqdnBase() throws Exception assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", "personium-localunit:/cell/box/col/ent?$inlinecount=allpages"), is("https://cell.host.domain/box/col/ent?$inlinecount=allpages")); + + // Double Colons + 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")); + } /** @@ -134,7 +161,7 @@ public void convertSchemeFromHttpToLocalUnit_Normal_url_is_fqdn_base() throws Ex .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/")); + assertThat(actual, is("personium-localunit:cell:/")); } /** @@ -161,8 +188,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("http://host.domain/", null); + } catch(PersoniumCoreException e) { + assertEquals(e.getCode(), "PR500-CM-0003"); + + } } /** 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..dbaf01118 100644 --- a/src/test/java/io/personium/test/jersey/cell/BoxUrlTest.java +++ b/src/test/java/io/personium/test/jersey/cell/BoxUrlTest.java @@ -98,7 +98,7 @@ public BoxUrlTest() { // 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); // テスト実施 PersoniumRestAdapter rest = new PersoniumRestAdapter(); @@ -137,7 +137,7 @@ public BoxUrlTest() { HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); - String localunitUrl = UriUtils.SCHEME_UNIT_URI + Setup.TEST_CELL_SCHEMA1 + "/"; + String localunitUrl = UriUtils.SCHEME_LOCALUNIT + ":/" + Setup.TEST_CELL_SCHEMA1 + "/"; res = rest.getAcceptEncodingGzip( UrlUtils.boxUrl(Setup.TEST_CELL1, localunitUrl), requestheaders); assertEquals(HttpStatus.SC_OK, res.getStatusCode()); 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..b137f8160 100644 --- a/src/test/java/io/personium/test/jersey/cell/UnitUserCellTest.java +++ b/src/test/java/io/personium/test/jersey/cell/UnitUserCellTest.java @@ -95,7 +95,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"); 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..a0fc604f4 100644 --- a/src/test/java/io/personium/test/unit/core/UrlUtils.java +++ b/src/test/java/io/personium/test/unit/core/UrlUtils.java @@ -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); } /** From 1b7836f13fbe739ee1a23f1e7414584e915aa4cd Mon Sep 17 00:00:00 2001 From: akioshimono Date: Wed, 31 Jul 2019 18:54:30 +0900 Subject: [PATCH 05/69] refactor to change from DEFAULT_BOX (old term) to MAIN_BOX --- .../io/personium/core/auth/AccessContext.java | 6 +-- .../java/io/personium/core/model/Box.java | 4 +- .../core/model/impl/es/CellEsImpl.java | 6 +-- .../core/model/impl/fs/DavCmpFsImpl.java | 2 +- .../io/personium/core/rs/box/BoxResource.java | 2 +- .../core/rs/cell/AuthzEndPointResource.java | 8 ++-- .../personium/core/rs/cell/CellResource.java | 2 +- .../core/rs/cell/TokenEndPointResource.java | 2 +- .../test/jersey/bar/BarInstallTest.java | 2 +- .../test/jersey/box/CollectionTest.java | 38 +++++++++---------- .../jersey/box/acl/AclAlterSchemaTest.java | 2 +- .../col/MoveCollectionAccessControlTest.java | 4 +- .../dav/col/MoveODataCollectionAclTest.java | 4 +- .../dav/col/MoveServiceCollectionAclTest.java | 4 +- .../col/ODataCollectionAccessControlTest.java | 2 +- .../ServiceCollectionAccessControlTest.java | 2 +- .../WebDAVCollectionAccessControlTest.java | 2 +- .../box/dav/file/FileAccessControlTest.java | 2 +- .../dav/file/MoveFileAccessControlTest.java | 2 +- .../MoveServiceSourceAccessControlTest.java | 2 +- .../file/ServiceSourceAccessControlTest.java | 2 +- .../personium/test/jersey/cell/AclTest.java | 20 +++++----- .../test/jersey/cell/DefaultBoxTest.java | 22 +++++------ .../test/jersey/cell/auth/AuthCheckTest.java | 14 +++---- .../test/jersey/cell/auth/AuthCookieTest.java | 10 ++--- .../test/jersey/cell/auth/SchemaAuthTest.java | 8 ++-- .../java/io/personium/test/setup/Setup.java | 2 +- .../io/personium/test/unit/core/UrlUtils.java | 2 +- .../io/personium/test/utils/AuthzUtils.java | 8 ++-- 29 files changed, 93 insertions(+), 93 deletions(-) diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index bf3b27de6..e1e35843f 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -896,12 +896,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(); 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/impl/es/CellEsImpl.java b/src/main/java/io/personium/core/model/impl/es/CellEsImpl.java index c88f74fb0..afec45f5c 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 @@ -329,7 +329,7 @@ public boolean isEmpty() { } // check that Main Box is empty - Box defaultBox = this.getBoxForName(Box.DEFAULT_BOX_NAME); + Box defaultBox = this.getBoxForName(Box.MAIN_BOX_NAME); BoxCmp defaultBoxCmp = ModelFactory.boxCmp(defaultBox); if (!defaultBoxCmp.isEmpty()) { return false; @@ -433,7 +433,7 @@ public void run() { @Override public Box getBoxForName(String boxName) { - if (Box.DEFAULT_BOX_NAME.equals(boxName)) { + if (Box.MAIN_BOX_NAME.equals(boxName)) { return new Box(this, null); } @@ -668,7 +668,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) { 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 f6090b5ac..62e05ebcb 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 @@ -1153,7 +1153,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/rs/box/BoxResource.java b/src/main/java/io/personium/core/rs/box/BoxResource.java index be21883d6..9e31d6044 100644 --- a/src/main/java/io/personium/core/rs/box/BoxResource.java +++ b/src/main/java/io/personium/core/rs/box/BoxResource.java @@ -443,7 +443,7 @@ public Response mkcol( //TODO findBugs countermeasure ↓ log.debug(requestKey); - if (Box.DEFAULT_BOX_NAME.equals(this.boxName)) { + if (Box.MAIN_BOX_NAME.equals(this.boxName)) { throw PersoniumCoreException.Misc.METHOD_NOT_ALLOWED; } 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..9daca390e 100644 --- a/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java @@ -1012,9 +1012,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 @@ -1084,9 +1084,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 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..fe7441894 100644 --- a/src/main/java/io/personium/core/rs/cell/CellResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellResource.java @@ -385,7 +385,7 @@ public RuleResource rule() { */ @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); } 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..9da8caa60 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -409,7 +409,7 @@ public static String clientAuth(final String clientId, final String clientSecret //Give # c if the role is a confidential value String confidentialRoleUrl = String.format( OAuth2Helper.Key.CONFIDENTIAL_ROLE_URL_FORMAT, - tcToken.getIssuer(), Box.DEFAULT_BOX_NAME); + tcToken.getIssuer(), Box.MAIN_BOX_NAME); for (Role role : tcToken.getRoles()) { if (confidentialRoleUrl.equals(role.createUrl())) { //Successful authentication. 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..b662f3787 100644 --- a/src/test/java/io/personium/test/jersey/bar/BarInstallTest.java +++ b/src/test/java/io/personium/test/jersey/bar/BarInstallTest.java @@ -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); 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..aa59f3675 100644 --- a/src/test/java/io/personium/test/jersey/box/CollectionTest.java +++ b/src/test/java/io/personium/test/jersey/box/CollectionTest.java @@ -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/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/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/cell/AclTest.java b/src/test/java/io/personium/test/jersey/cell/AclTest.java index fa264b02c..4ca398c88 100644 --- a/src/test/java/io/personium/test/jersey/cell/AclTest.java +++ b/src/test/java/io/personium/test/jersey/cell/AclTest.java @@ -128,7 +128,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の設定を元に戻す @@ -185,7 +185,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); @@ -282,7 +282,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 +359,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 +436,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 +557,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 +630,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 +667,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 +731,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 +797,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 { // ロールの削除 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/auth/AuthCheckTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthCheckTest.java index a6f53a6e7..4bee3dde6 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 @@ -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 { @@ -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, @@ -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が入っていないこと) 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..ca254af58 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 @@ -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/SchemaAuthTest.java b/src/test/java/io/personium/test/jersey/cell/auth/SchemaAuthTest.java index 8c5bf8d0a..6917fea59 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 @@ -678,16 +678,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); } } diff --git a/src/test/java/io/personium/test/setup/Setup.java b/src/test/java/io/personium/test/setup/Setup.java index 969267b68..130ec9a56 100644 --- a/src/test/java/io/personium/test/setup/Setup.java +++ b/src/test/java/io/personium/test/setup/Setup.java @@ -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); 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 a0fc604f4..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; } diff --git a/src/test/java/io/personium/test/utils/AuthzUtils.java b/src/test/java/io/personium/test/utils/AuthzUtils.java index d1acfa6be..365a137a8 100644 --- a/src/test/java/io/personium/test/utils/AuthzUtils.java +++ b/src/test/java/io/personium/test/utils/AuthzUtils.java @@ -341,8 +341,8 @@ 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")); @@ -378,8 +378,8 @@ 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")); From d3ac089d667c2df288d6b5c38b0a78c6255d1d5c Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 4 Aug 2019 00:34:34 +0900 Subject: [PATCH 06/69] refactoring. UriUtils class does not need Unit URL since it can be obtained from PersoniumUnitConfig statically. --- .../personium/core/PersoniumUnitConfig.java | 8 +- .../io/personium/core/auth/AccessContext.java | 6 +- .../io/personium/core/model/CellRsCmp.java | 7 +- .../core/model/impl/es/CellEsImpl.java | 8 +- .../impl/es/odata/MessageODataProducer.java | 12 +- .../impl/es/odata/UnitCtlODataProducer.java | 3 +- .../personium/core/rs/box/StreamResource.java | 5 +- .../core/rs/cell/CellCtlResource.java | 11 +- .../core/rs/cell/TokenEndPointResource.java | 3 +- .../core/rs/unit/UnitCtlResource.java | 4 +- .../io/personium/core/rule/RuleManager.java | 8 +- .../snapshot/SnapshotFileImportRunner.java | 2 +- .../io/personium/core/utils/UriUtils.java | 43 +++--- .../io/personium/core/utils/UriUtilsTest.java | 141 +++++++++--------- 14 files changed, 131 insertions(+), 130 deletions(-) diff --git a/src/main/java/io/personium/core/PersoniumUnitConfig.java b/src/main/java/io/personium/core/PersoniumUnitConfig.java index 3fbf799b4..6ca493b78 100644 --- a/src/main/java/io/personium/core/PersoniumUnitConfig.java +++ b/src/main/java/io/personium/core/PersoniumUnitConfig.java @@ -537,14 +537,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; } @@ -1613,8 +1613,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 e1e35843f..e828575c4 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -532,7 +532,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. @@ -887,8 +887,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(); diff --git a/src/main/java/io/personium/core/model/CellRsCmp.java b/src/main/java/io/personium/core/model/CellRsCmp.java index 591b0135a..baa951c0e 100644 --- a/src/main/java/io/personium/core/model/CellRsCmp.java +++ b/src/main/java/io/personium/core/model/CellRsCmp.java @@ -217,7 +217,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 +245,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 +274,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); 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 afec45f5c..af7e172e8 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 @@ -136,7 +136,7 @@ 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); + cell.owner = UriUtils.convertSchemeFromLocalUnitToHttp(cell.owner); } return cell; } @@ -466,7 +466,7 @@ public Box getBoxForName(String boxName) { @Override public Box getBoxForSchema(String boxSchema) { //Retrieving the schema name list (including aliases) - List boxSchemas = UriUtils.getUrlVariations(this.getUnitUrl(), boxSchema); + List boxSchemas = UriUtils.getUrlVariations(boxSchema); ODataProducer op = ModelFactory.ODataCtl.cellCtl(this); for (int i = 0; i < boxSchemas.size(); i++) { @@ -773,7 +773,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 +822,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); 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..3c71e6b1a 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 @@ -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/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/rs/box/StreamResource.java b/src/main/java/io/personium/core/rs/box/StreamResource.java index 3e2d8d631..25699bd98 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; @@ -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("/"))) 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..19d98e5a2 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; @@ -285,8 +284,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 +304,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(); } 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 9da8caa60..61d58242c 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -152,8 +152,7 @@ public final Response token(@Context final UriInfo uriInfo, String pCookie = formParams.getFirst("p_cookie"); // Accept unit local scheme url. - String target = UriUtils.convertSchemeFromLocalUnitToHttp( - cell.getUnitUrl(), pTarget); + String target = UriUtils.convertSchemeFromLocalUnitToHttp(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); 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 5b5f7bd23..f9ff74907 100644 --- a/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java +++ b/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java @@ -135,7 +135,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); } } @@ -236,7 +236,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/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/snapshot/SnapshotFileImportRunner.java b/src/main/java/io/personium/core/snapshot/SnapshotFileImportRunner.java index 39afac4b2..7ef7f6a85 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.getOwner()); h.put("Owner", owner); map.put(OEntityDocHandler.KEY_UPDATED, System.currentTimeMillis()); diff --git a/src/main/java/io/personium/core/utils/UriUtils.java b/src/main/java/io/personium/core/utils/UriUtils.java index 5f190b3c3..2c5184ea6 100644 --- a/src/main/java/io/personium/core/utils/UriUtils.java +++ b/src/main/java/io/personium/core/utils/UriUtils.java @@ -37,25 +37,24 @@ 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. */ /** LOCAL_CELL ADDITION. */ public static final String SCHEME_CELL_URI = SCHEME_LOCALCELL + ":/"; /** LOCAL_BOX ADDITION. */ @@ -70,10 +69,10 @@ public class UriUtils { public static final Pattern REGEX_LOCALUNIT_DOUBLE_COLONS = Pattern.compile("^" + SCHEME_LOCALUNIT + ":(.+?):(.*)$"); - /** Regular expression for matching localunit scheme with double colons */ + /** Regular expression for matching Cell URL */ public static final String REGEX_HTTP_SUBDOMAIN = "^(http|https):\\/\\/(.+?)\\.(.*)$"; - /** SLASH. */ + /** String Slash. */ public static final String STRING_SLASH = "/"; /** @@ -89,13 +88,13 @@ private UriUtils() { * @return ArrayList * @throws URISyntaxException */ - public static List getUrlVariations(String unitUrl, String url) throws PersoniumCoreException { - if (url == null || unitUrl == null) { + public static List getUrlVariations(String url) throws PersoniumCoreException { + if (url == null) { throw PersoniumCoreException.Common.INVALID_URL.params("null"); } List variations = new ArrayList(); variations.add(url); - String substitute = getUrlSubstitute(unitUrl, url); + String substitute = getUrlSubstitute(url); if (!url.equals(substitute)) { variations.add(substitute); } @@ -109,14 +108,14 @@ public static List getUrlVariations(String unitUrl, String url) throws P * @return utl String * @throws URISyntaxException */ - public static String getUrlSubstitute(String unitUrl, String url) { - if (url == null || unitUrl == null) { + public static String getUrlSubstitute(String url) { + if (url == null) { throw PersoniumCoreException.Common.INVALID_URL.params("null"); } if (url.startsWith(SCHEME_LOCALUNIT)) { - url = convertSchemeFromLocalUnitToHttp(unitUrl, url); + url = convertSchemeFromLocalUnitToHttp(url); } else { - url = convertSchemeFromHttpToLocalUnit(unitUrl, url); + url = convertSchemeFromHttpToLocalUnit(url); } return url; } @@ -139,10 +138,11 @@ public static boolean isLocalUnitUrl(String targetUrl) { * @param localUnitSchemeUrl local unit url * @return url string with http(s) scheme */ - public static String convertSchemeFromLocalUnitToHttp(String unitUrl, String localUnitSchemeUrl) { - if (localUnitSchemeUrl == null || unitUrl == null) { + public static String convertSchemeFromLocalUnitToHttp(String localUnitSchemeUrl) { + if (localUnitSchemeUrl == null) { throw PersoniumCoreException.Common.INVALID_URL.params("null"); } + String unitUrl = PersoniumUnitConfig.getBaseUrl(); Matcher localUnitDoubleColons = REGEX_LOCALUNIT_DOUBLE_COLONS.matcher(localUnitSchemeUrl); Matcher localUnitSingleColon = REGEX_LOCALUNIT_SINGLE_COLON.matcher(localUnitSchemeUrl); String pathBased = localUnitSchemeUrl; @@ -185,10 +185,11 @@ public static String convertSchemeFromLocalUnitToHttp(String unitUrl, String loc * @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) { throw PersoniumCoreException.Common.INVALID_URL.params("null"); } + String unitUrl = PersoniumUnitConfig.getBaseUrl(); if (PersoniumUnitConfig.isPathBasedCellUrlEnabled()) { // path based if (url.startsWith(unitUrl)) { diff --git a/src/test/java/io/personium/core/utils/UriUtilsTest.java b/src/test/java/io/personium/core/utils/UriUtilsTest.java index 4d2ff026f..fc308f62f 100644 --- a/src/test/java/io/personium/core/utils/UriUtilsTest.java +++ b/src/test/java/io/personium/core/utils/UriUtilsTest.java @@ -50,42 +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"); + // Single Colon - 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")); + 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("http://host.domain/", "personium-localunit:cell:"), - is("http://host.domain/cell/")); + UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:"), + is("https://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")); - + 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")); } /** @@ -98,36 +96,40 @@ 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"); + .when(PersoniumUnitConfig.class, "isPathBasedCellUrlEnabled"); + PowerMockito.doReturn("https://host.domain/") + .when(PersoniumUnitConfig.class, "getBaseUrl"); + /* 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/"); + */ // Single Colon - 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")); + 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("http://host.domain/", "personium-localunit:cell:"), - is("http://cell.host.domain/")); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", "personium-localunit:cell:"), + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:"), is("https://cell.host.domain/")); - assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("https://host.domain/", "personium-localunit:cell:#account"), + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:"), + is("https://cell.host.domain/")); + assertThat(UriUtils.convertSchemeFromLocalUnitToHttp("personium-localunit:cell:#account"), is("https://cell.host.domain/#account")); } @@ -140,12 +142,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/")); } /** @@ -156,11 +160,10 @@ 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/"); + PowerMockito.spy(PersoniumUnitConfig.class); + PowerMockito.doReturn("http://unit.example/") + .when(PersoniumUnitConfig.class, "getBaseUrl"); + String actual = UriUtils.convertSchemeFromHttpToLocalUnit("http://cell.unit.example/"); assertThat(actual, is("personium-localunit:cell:/")); } @@ -172,12 +175,17 @@ public void convertSchemeFromHttpToLocalUnit_Normal_url_is_fqdn_base() throws Ex */ @Test public void convertSchemeFromHttpToLocalUnit_Normal_url_not_starts_with_uniturl() throws Exception { + PowerMockito.spy(PersoniumUnitConfig.class); + PowerMockito.doReturn("http://unit.example/") + .when(PersoniumUnitConfig.class, "getBaseUrl"); +/* 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/")); + */ + assertThat( + UriUtils.convertSchemeFromHttpToLocalUnit("http://otherhost.otherdomain/cell/"), + is("http://otherhost.otherdomain/cell/")); } /** @@ -189,7 +197,7 @@ public void convertSchemeFromHttpToLocalUnit_Normal_url_not_starts_with_uniturl( @Test public void convertSchemeFromHttpToLocalUnit_Normal_url_is_null() throws Exception { try { - UriUtils.convertSchemeFromHttpToLocalUnit("http://host.domain/", null); + UriUtils.convertSchemeFromHttpToLocalUnit(null); } catch(PersoniumCoreException e) { assertEquals(e.getCode(), "PR500-CM-0003"); @@ -204,8 +212,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")); } /** From 4dbfcaf2da192394df76a50bbba5f15beb6b4625 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 4 Aug 2019 04:34:58 +0900 Subject: [PATCH 07/69] set version 1.7.18 --- .../personium-unit-config-default.properties | 2 +- .../io/personium/core/utils/UriUtilsTest.java | 37 ++++++++++++------- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/src/main/resources/personium-unit-config-default.properties b/src/main/resources/personium-unit-config-default.properties index 506eef17f..0635d956b 100644 --- a/src/main/resources/personium-unit-config-default.properties +++ b/src/main/resources/personium-unit-config-default.properties @@ -23,7 +23,7 @@ ################################################# # core version -io.personium.core.version=1.7.16 +io.personium.core.version=1.7.18 # thread pool num. io.personium.core.thread.pool.num.io.cell=10 diff --git a/src/test/java/io/personium/core/utils/UriUtilsTest.java b/src/test/java/io/personium/core/utils/UriUtilsTest.java index fc308f62f..c5ce8e913 100644 --- a/src/test/java/io/personium/core/utils/UriUtilsTest.java +++ b/src/test/java/io/personium/core/utils/UriUtilsTest.java @@ -99,13 +99,6 @@ public void convertSchemeFromLocalUnitToHttp_Normal_fqdnBase() throws Exception .when(PersoniumUnitConfig.class, "isPathBasedCellUrlEnabled"); PowerMockito.doReturn("https://host.domain/") .when(PersoniumUnitConfig.class, "getBaseUrl"); - /* - 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/"); - */ // Single Colon assertThat( @@ -161,10 +154,30 @@ public void convertSchemeFromHttpToLocalUnit_Normal_url_starts_with_uniturl() th @Test public void convertSchemeFromHttpToLocalUnit_Normal_url_is_fqdn_base() throws Exception { PowerMockito.spy(PersoniumUnitConfig.class); + PowerMockito.doReturn(false) + .when(PersoniumUnitConfig.class, "isPathBasedCellUrlEnabled"); PowerMockito.doReturn("http://unit.example/") .when(PersoniumUnitConfig.class, "getBaseUrl"); - String actual = UriUtils.convertSchemeFromHttpToLocalUnit("http://cell.unit.example/"); - assertThat(actual, is("personium-localunit:cell:/")); + 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:/")); } /** @@ -178,11 +191,7 @@ public void convertSchemeFromHttpToLocalUnit_Normal_url_not_starts_with_uniturl( PowerMockito.spy(PersoniumUnitConfig.class); PowerMockito.doReturn("http://unit.example/") .when(PersoniumUnitConfig.class, "getBaseUrl"); -/* - PowerMockito.spy(UriUtils.class); - PowerMockito.doReturn("http://otherdomain/otherhost/cell/") - .when(UriUtils.class, "convertFqdnBaseToPathBase", "http://otherhost.otherdomain/cell/"); - */ + assertThat( UriUtils.convertSchemeFromHttpToLocalUnit("http://otherhost.otherdomain/cell/"), is("http://otherhost.otherdomain/cell/")); From 4680053c62185eb82614017c0fbb83348454aa89 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 4 Aug 2019 04:39:09 +0900 Subject: [PATCH 08/69] Introduce URL equality util function ignoring port in order to make current jersey test work. --- .../core/model/impl/es/CellEsImpl.java | 2 +- .../io/personium/core/utils/UriUtils.java | 46 +++++++++++++++---- 2 files changed, 39 insertions(+), 9 deletions(-) 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 af7e172e8..034ec971d 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 @@ -656,7 +656,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; } diff --git a/src/main/java/io/personium/core/utils/UriUtils.java b/src/main/java/io/personium/core/utils/UriUtils.java index 2c5184ea6..146f51a99 100644 --- a/src/main/java/io/personium/core/utils/UriUtils.java +++ b/src/main/java/io/personium/core/utils/UriUtils.java @@ -20,6 +20,7 @@ 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; @@ -134,13 +135,14 @@ public static boolean isLocalUnitUrl(String targetUrl) { /** * Convert scheme from LocalUnit to http(s). + * If the he given value does not match localunit schem, the given value is returned as-is. * @param unitUrl unit url * @param localUnitSchemeUrl local unit url * @return url string with http(s) scheme */ public static String convertSchemeFromLocalUnitToHttp(String localUnitSchemeUrl) { if (localUnitSchemeUrl == null) { - throw PersoniumCoreException.Common.INVALID_URL.params("null"); + return null; } String unitUrl = PersoniumUnitConfig.getBaseUrl(); Matcher localUnitDoubleColons = REGEX_LOCALUNIT_DOUBLE_COLONS.matcher(localUnitSchemeUrl); @@ -180,24 +182,26 @@ public static String convertSchemeFromLocalUnitToHttp(String 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 url) { if (url == null) { - throw PersoniumCoreException.Common.INVALID_URL.params("null"); + return null; } String unitUrl = PersoniumUnitConfig.getBaseUrl(); if (PersoniumUnitConfig.isPathBasedCellUrlEnabled()) { // path based - if (url.startsWith(unitUrl)) { - // convert when url is localunit - return url.replaceFirst(unitUrl, SCHEME_LOCALUNIT + ":/"); + if (!url.startsWith(unitUrl)) { + // return as-is when url is foreign + return url; } - // 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)) { @@ -516,4 +520,30 @@ 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; + } + } } From 6b4d1ce010d9ff272e449d1f827bc1571172777a Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 4 Aug 2019 08:18:03 +0900 Subject: [PATCH 09/69] Unit test modification after removing Unit URL parameter from UriUtils class methods. --- .../impl/es/odata/MessageODataProducerTest.java | 12 ++++++------ .../impl/es/odata/UnitCtlODataProducerTest.java | 2 +- .../personium/core/rs/unit/UnitCtlResourceTest.java | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) 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/rs/unit/UnitCtlResourceTest.java b/src/test/java/io/personium/core/rs/unit/UnitCtlResourceTest.java index 02c3097dc..a252fd64f 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"); @@ -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(); From ce1260ced307752b6030af13cc328ed5f56b126c Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 4 Aug 2019 10:53:16 +0900 Subject: [PATCH 10/69] Let box url discovery api accept the personium-localunit scheme url with double colons. --- .../core/rs/cell/BoxUrlResource.java | 2 ++ .../io/personium/core/utils/ODataUtils.java | 25 ++++++------------- .../io/personium/core/utils/UriUtils.java | 4 +++ .../core/PersoniumUnitConfigTest.java | 11 ++++---- .../test/jersey/cell/BoxUrlTest.java | 6 ++--- 5 files changed, 22 insertions(+), 26 deletions(-) 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..f59c658f3 100644 --- a/src/main/java/io/personium/core/rs/cell/BoxUrlResource.java +++ b/src/main/java/io/personium/core/rs/cell/BoxUrlResource.java @@ -36,6 +36,7 @@ import io.personium.core.model.DavRsCmp; import io.personium.core.model.ModelFactory; import io.personium.core.utils.ODataUtils; +import io.personium.core.utils.UriUtils; /** * JOX-RS Resource for obtaining Box URL. @@ -86,6 +87,7 @@ public final Response boxUrl(@QueryParam("schema") final String querySchema) { if (schema == null || schema.length() == 0) { box = this.cellRsCmp.getBox(); } else { + schema = UriUtils.resolveLocalUnit(schema); //Acquire Box from schema information box = this.cellRsCmp.getCell().getBoxForSchema(schema); } 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/UriUtils.java b/src/main/java/io/personium/core/utils/UriUtils.java index 146f51a99..759ee8f97 100644 --- a/src/main/java/io/personium/core/utils/UriUtils.java +++ b/src/main/java/io/personium/core/utils/UriUtils.java @@ -546,4 +546,8 @@ public static boolean equalIgnoringPort(String url1, String url2) { return false; } } + + public static String resolveLocalUnit(String url) { + return UriUtils.convertSchemeFromLocalUnitToHttp(url); + } } diff --git a/src/test/java/io/personium/core/PersoniumUnitConfigTest.java b/src/test/java/io/personium/core/PersoniumUnitConfigTest.java index 0c02c41f7..423f07d80 100644 --- a/src/test/java/io/personium/core/PersoniumUnitConfigTest.java +++ b/src/test/java/io/personium/core/PersoniumUnitConfigTest.java @@ -19,13 +19,12 @@ 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.test.categories.Unit; @@ -51,8 +50,8 @@ public void getBaseUrl_Noraml() throws Exception { PowerMockito.doReturn("host.domain").when(PersoniumCoreUtils.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("http").when(PersoniumUnitConfig.class, "getUnitScheme"); 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 dbaf01118..7e93fd4e9 100644 --- a/src/test/java/io/personium/test/jersey/cell/BoxUrlTest.java +++ b/src/test/java/io/personium/test/jersey/cell/BoxUrlTest.java @@ -137,9 +137,9 @@ public BoxUrlTest() { HashMap requestheaders = new HashMap(); requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); - String localunitUrl = UriUtils.SCHEME_LOCALUNIT + ":/" + 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)); From 026897875f552ab2b97b2afc8c238074ba1c0982 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 4 Aug 2019 11:33:43 +0900 Subject: [PATCH 11/69] translate Test Method name to English --- .../personium/core/rs/cell/BoxUrlResource.java | 2 -- .../personium/test/jersey/cell/BoxUrlTest.java | 18 +++++++++--------- 2 files changed, 9 insertions(+), 11 deletions(-) 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 f59c658f3..82d96c9e1 100644 --- a/src/main/java/io/personium/core/rs/cell/BoxUrlResource.java +++ b/src/main/java/io/personium/core/rs/cell/BoxUrlResource.java @@ -36,7 +36,6 @@ import io.personium.core.model.DavRsCmp; import io.personium.core.model.ModelFactory; import io.personium.core.utils.ODataUtils; -import io.personium.core.utils.UriUtils; /** * JOX-RS Resource for obtaining Box URL. @@ -87,7 +86,6 @@ public final Response boxUrl(@QueryParam("schema") final String querySchema) { if (schema == null || schema.length() == 0) { box = this.cellRsCmp.getBox(); } else { - schema = UriUtils.resolveLocalUnit(schema); //Acquire Box from schema information box = this.cellRsCmp.getCell().getBoxForSchema(schema); } 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 7e93fd4e9..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_LOCALUNIT + ":/" + 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(); From 3afdb8008abe8f76c588eb2f76036e7dbdf301fc Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 4 Aug 2019 14:14:09 +0900 Subject: [PATCH 12/69] getUrlVariations should return zero length list when given null --- src/main/java/io/personium/core/utils/UriUtils.java | 4 ++-- .../io/personium/test/jersey/cell/MessageApproveTest.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/personium/core/utils/UriUtils.java b/src/main/java/io/personium/core/utils/UriUtils.java index 759ee8f97..32c4a5692 100644 --- a/src/main/java/io/personium/core/utils/UriUtils.java +++ b/src/main/java/io/personium/core/utils/UriUtils.java @@ -90,10 +90,10 @@ private UriUtils() { * @throws URISyntaxException */ public static List getUrlVariations(String url) throws PersoniumCoreException { + List variations = new ArrayList(); if (url == null) { - throw PersoniumCoreException.Common.INVALID_URL.params("null"); + return variations; } - List variations = new ArrayList(); variations.add(url); String substitute = getUrlSubstitute(url); if (!url.equals(substitute)) { 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..d46380540 100644 --- a/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java +++ b/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java @@ -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()); From 60216f48202d4809af075398170c8f8d2719a7a5 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Mon, 5 Aug 2019 03:33:22 +0900 Subject: [PATCH 13/69] Fix the tests so that it uses new double colon syntax in the personium-localunit URL scheme. --- .../test/jersey/cell/auth/AuthTest.java | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) 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..7bc674bf1 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 @@ -125,7 +125,7 @@ public class AuthTest extends PersoniumTest { static final int READ_PROP = 7; /** - * コンストラクタ. + * Constructor. */ public AuthTest() { super(new PersoniumCoreApplication()); @@ -394,22 +394,23 @@ 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を割当。 @@ -518,7 +519,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 +527,7 @@ public AuthTest() { // main box を使用(box1にはACL設定がありテストには不適切であるため) String testBox = "__"; - // dcTargetの値がhttpの場合 + // When p_target URL is http try { // テスト準備 (MASTER_TOKENで実施) // 1.ExtCell更新 From efa20238029635cacf04c5d1bbe38083bd89f57a Mon Sep 17 00:00:00 2001 From: akioshimono Date: Mon, 5 Aug 2019 04:34:07 +0900 Subject: [PATCH 14/69] minor refactoring --- .../core/rs/cell/TokenEndPointResource.java | 60 ++++++++++--------- .../io/personium/core/utils/UriUtils.java | 1 - .../rs/cell/TokenEndPointResourceTest.java | 2 +- .../test/jersey/cell/UnitUserCellTest.java | 4 +- 4 files changed, 34 insertions(+), 33 deletions(-) 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 61d58242c..fc02a7af8 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -90,13 +90,9 @@ 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; @@ -119,10 +115,11 @@ public TokenEndPointResource(final Cell cell, final 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 @@ -151,11 +148,16 @@ public final Response token(@Context final UriInfo uriInfo, String rTokenExpiresInStr = formParams.getFirst(Key.REFRESH_TOKEN_EXPIRES_IN); String pCookie = formParams.getFirst("p_cookie"); - // Accept unit local scheme url. + // relsolve personium-localunit scheme url. String target = UriUtils.convertSchemeFromLocalUnitToHttp(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); + } + // Do not issue cookie if p_target exists, regardless of the p_cookie parameter. if (null != pTarget) { issueCookie = false; } else { @@ -166,8 +168,8 @@ 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. + // Authenticate client first if necessary. + // If neither Scope nor authzHeader nor clientId exists, client authentication is not performed. if (clientId != null || authzHeader != null) { schema = clientAuth(clientId, clientSecret, authzHeader, cell.getUrl()); } @@ -313,28 +315,28 @@ private Response callAuthPlugins(String grantType, MultivaluedMap Date: Mon, 5 Aug 2019 06:56:54 +0900 Subject: [PATCH 15/69] refactor so that it will be clear that the Cell owner is persisted in the personium-unitlocal format whenever possible. --- .../io/personium/core/auth/AccessContext.java | 4 +- .../personium/core/bar/BarFileInstaller.java | 2 +- .../core/eventlog/ArchiveLogCollection.java | 2 +- .../java/io/personium/core/model/Cell.java | 13 +++- .../io/personium/core/model/ModelFactory.java | 25 +++---- .../core/model/impl/es/CellEsImpl.java | 12 ++- .../personium/core/model/impl/es/EsModel.java | 6 +- .../core/model/impl/fs/DavCmpFsImpl.java | 2 +- .../personium/core/rs/cell/CellResource.java | 4 +- .../personium/core/rs/cell/LogResource.java | 4 +- .../core/rs/cell/TokenEndPointResource.java | 9 ++- .../core/rs/unit/UnitCtlResource.java | 2 +- .../personium/core/rule/action/LogAction.java | 2 +- .../snapshot/SnapshotFileImportRunner.java | 2 +- .../core/auth/AccessContextTest.java | 16 ++-- .../core/rule/action/ActionFactoryTest.java | 10 +-- .../test/jersey/cell/UnitUserCellTest.java | 75 ++++++++++++++++++- 17 files changed, 136 insertions(+), 54 deletions(-) diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index e828575c4..b799d0251 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -396,7 +396,7 @@ public boolean isUnitUserToken() { || 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; } @@ -414,7 +414,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. diff --git a/src/main/java/io/personium/core/bar/BarFileInstaller.java b/src/main/java/io/personium/core/bar/BarFileInstaller.java index 3dc413629..701d5f22b 100644 --- a/src/main/java/io/personium/core/bar/BarFileInstaller.java +++ b/src/main/java/io/personium/core/bar/BarFileInstaller.java @@ -311,7 +311,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/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/model/Cell.java b/src/main/java/io/personium/core/model/Cell.java index 3dc7fa1fc..1d0b79f3d 100644 --- a/src/main/java/io/personium/core/model/Cell.java +++ b/src/main/java/io/personium/core/model/Cell.java @@ -104,11 +104,16 @@ public interface Cell { String getUnitUrl(); /** - * It gets the URI of the Cell of the Owner Unit User. - * @return Cell name + * Returns the normalized URI of the owner Unit User of this Cell. + * @return normalized owner url. */ - String getOwner(); + String getOwnerNormalized(); + /** + * Returns the raw URI of the owner Unit User of this Cell. + * @return raw owner url. + */ + String getOwnerRaw(); /** * It gets the prefix without Unit User name of the Cell. * @return . @@ -209,4 +214,6 @@ public interface Cell { * @return internal id of the given role */ String roleResourceUrlToId(String roleUrl, String baseUrl); + + } 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/impl/es/CellEsImpl.java b/src/main/java/io/personium/core/model/impl/es/CellEsImpl.java index 034ec971d..04eea6f4b 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 @@ -136,7 +136,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.owner); } return cell; } @@ -262,7 +261,7 @@ public String getFqdnBaseUrl() { return UriUtils.convertPathBaseToFqdnBase(url); } catch (URISyntaxException e) { // Usually it does not occur. - throw PersoniumCoreException.Server.UNKNOWN_ERROR; + throw PersoniumCoreException.Server.UNKNOWN_ERROR.reason(e); } } @@ -284,10 +283,15 @@ public String getUnitUrl() { } @Override - public String getOwner() { + public String getOwnerNormalized() { + return UriUtils.convertSchemeFromLocalUnitToHttp(this.owner); + } + @Override + public String getOwnerRaw() { return this.owner; } + @Override public String getDataBundleNameWithOutPrefix() { String unitUserName; @@ -374,7 +378,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); 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/fs/DavCmpFsImpl.java b/src/main/java/io/personium/core/model/impl/fs/DavCmpFsImpl.java index 62e05ebcb..8c30015ac 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 @@ -1033,7 +1033,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; 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 fe7441894..530a68064 100644 --- a/src/main/java/io/personium/core/rs/cell/CellResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellResource.java @@ -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"; @@ -224,7 +224,7 @@ public Response cellBulkDeletion( } //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(); 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..06233d875 100644 --- a/src/main/java/io/personium/core/rs/cell/LogResource.java +++ b/src/main/java/io/personium/core/rs/cell/LogResource.java @@ -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); @@ -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/TokenEndPointResource.java b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java index fc02a7af8..92fb37a2e 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -155,6 +155,7 @@ public final Response token(@Context final UriInfo uriInfo, 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. @@ -641,13 +642,13 @@ 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); } else { @@ -903,13 +904,13 @@ 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); } 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 f9ff74907..a28ecdae2 100644 --- a/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java +++ b/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java @@ -187,7 +187,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) { 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/snapshot/SnapshotFileImportRunner.java b/src/main/java/io/personium/core/snapshot/SnapshotFileImportRunner.java index 7ef7f6a85..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.getOwner()); + String owner = UriUtils.convertSchemeFromHttpToLocalUnit(targetCell.getOwnerNormalized()); h.put("Owner", owner); map.put(OEntityDocHandler.KEY_UPDATED, System.currentTimeMillis()); diff --git a/src/test/java/io/personium/core/auth/AccessContextTest.java b/src/test/java/io/personium/core/auth/AccessContextTest.java index 6b2869d7c..ee88f35df 100644 --- a/src/test/java/io/personium/core/auth/AccessContextTest.java +++ b/src/test/java/io/personium/core/auth/AccessContextTest.java @@ -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,7 +250,7 @@ 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を設定する @@ -275,13 +275,13 @@ 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", cell.getOwnerNormalized(), null, UrlUtils.getBaseUrl() + "/cellowner"); String tokenString = token.toTokenString(); @@ -305,14 +305,14 @@ 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を設定する @@ -339,14 +339,14 @@ 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を設定する 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/test/jersey/cell/UnitUserCellTest.java b/src/test/java/io/personium/test/jersey/cell/UnitUserCellTest.java index a249828c4..4e07077ec 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"; @@ -140,9 +148,70 @@ public static void afterClass() { /** * ユニットユーザートークンでセル作成を行いオーナーが設定されることを確認. + * @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, -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 ユニットユーザートークンでセル作成を行いオーナーが設定されることを確認() { + 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() { } } + /** * ユニットアドミンロールをもつユニットユーザートークンでセル作成を行いオーナーが設定されないことを確認. */ From 90a741ccfcd36ad3416aebf60f742e8fad3d427d Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Tue, 30 Jul 2019 13:31:37 +0900 Subject: [PATCH 16/69] Add engine relay log --- .../io/personium/core/PersoniumCoreLog.java | 11 ++++++ .../PersoniumEngineSvcCollectionResource.java | 38 +++++++++++++------ .../resources/personium-log-level.properties | 2 + .../resources/personium-messages.properties | 3 ++ 4 files changed, 42 insertions(+), 12 deletions(-) diff --git a/src/main/java/io/personium/core/PersoniumCoreLog.java b/src/main/java/io/personium/core/PersoniumCoreLog.java index 0a26a7b06..c3d015c64 100644 --- a/src/main/java/io/personium/core/PersoniumCoreLog.java +++ b/src/main/java/io/personium/core/PersoniumCoreLog.java @@ -187,6 +187,16 @@ public static class OIDC { public static final PersoniumCoreLog ACCOUNT_IS_DEACTIVATED = create("PL-OI-0005"); } + /** + * Service collection. + */ + public static class ServiceCollection { + /** + * Personium-Engine reley starts/ends. + */ + public static final PersoniumCoreLog SC_ENGINE_RELAY = create("PL-SC-0001"); + } + /** * Server internal error. * Throw when a process can not be continued due to a server side failure or bug, which is to indicate the cause of the problem. Basically, when exceptions occur in category of WARN or more log output @@ -371,6 +381,7 @@ public static void loadConfig() { new Server(); new Dav(); new Misc(); + new ServiceCollection(); } /** diff --git a/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java index 85dd66711..04acdfb3c 100644 --- a/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java @@ -61,6 +61,7 @@ import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreException; +import io.personium.core.PersoniumCoreLog; import io.personium.core.PersoniumUnitConfig; import io.personium.core.annotations.ACL; import io.personium.core.annotations.MOVE; @@ -90,6 +91,7 @@ public class PersoniumEngineSvcCollectionResource { DavCmp davCmp = null; DavCollectionResource dcr = null; DavRsCmp davRsCmp; + PersoniumCoreLog relayLog = null; /** * constructor. @@ -483,26 +485,19 @@ private Response relaycommon( // CHECKSTYLE IGNORE - Necessary processing } } - if (log.isDebugEnabled()) { - log.debug("[EngineRelay]" + req.getMethod() + " " + req.getURI()); - Header[] reqHeaders = req.getAllHeaders(); - for (int i = 0; i < reqHeaders.length; i++) { - log.debug("RelayHeader[" + reqHeaders[i].getName() + "] : " + reqHeaders[i].getValue()); - } - } - // prepare event PersoniumEvent event = createEvent(path); EventBus eventBus = this.davRsCmp.getAccessContext().getCell().getEventBus(); + // write relay log + setRelayLog(req); + this.relayLog.writeStartLog(); + debugRelayHeader(req); + //Throw a request to the Engine HttpResponse objResponse = null; try { objResponse = client.execute(req); - // post event to EventBus - String info = Integer.toString(objResponse.getStatusLine().getStatusCode()); - event.setInfo(info); - eventBus.post(event); } catch (ClientProtocolException e) { // post event to EventBus event.setInfo("500"); @@ -516,6 +511,12 @@ private Response relaycommon( // CHECKSTYLE IGNORE - Necessary processing closeHttpClient(client, objResponse); throw PersoniumCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(ioe); } + this.relayLog.writeEndLog(); + + // post event to EventBus + String info = Integer.toString(objResponse.getStatusLine().getStatusCode()); + event.setInfo(info); + eventBus.post(event); //Add status code ResponseBuilder res = Response.status(objResponse.getStatusLine().getStatusCode()); @@ -595,6 +596,19 @@ private String getRequestKey(DavRsCmp rsCmp) { return getRequestKey(rsCmp.getParent()); } + private void setRelayLog(HttpUriRequest req) { + this.relayLog = PersoniumCoreLog.ServiceCollection.SC_ENGINE_RELAY.params(req.getMethod(), req.getURI()); + } + + private void debugRelayHeader(HttpUriRequest req) { + if (log.isDebugEnabled()) { + Header[] reqHeaders = req.getAllHeaders(); + for (int i = 0; i < reqHeaders.length; i++) { + log.debug("RelayHeader[" + reqHeaders[i].getName() + "] : " + reqHeaders[i].getValue()); + } + } + } + /** * Processing of the MOVE method. * @param headers header information diff --git a/src/main/resources/personium-log-level.properties b/src/main/resources/personium-log-level.properties index 1c175c40a..bc8fbdce4 100644 --- a/src/main/resources/personium-log-level.properties +++ b/src/main/resources/personium-log-level.properties @@ -64,6 +64,8 @@ io.personium.core.loglevel.PL-OI-0002=info io.personium.core.loglevel.PL-OI-0003=info io.personium.core.loglevel.PL-OI-0004=info +# ServiceCollection +io.personium.core.loglevel.PL-SC-0001=info # Elastic Search io.personium.core.loglevel.PL-ES-0001=info diff --git a/src/main/resources/personium-messages.properties b/src/main/resources/personium-messages.properties index e998910e1..7a416f2a2 100644 --- a/src/main/resources/personium-messages.properties +++ b/src/main/resources/personium-messages.properties @@ -437,6 +437,9 @@ io.personium.core.msg.PL-OI-0003=Invalid account Name={0}. io.personium.core.msg.PL-OI-0004=Issuer={0} not Google authorized. io.personium.core.msg.PL-OI-0005=Account is deactivated. [{0}] [{1}] [{2}] +## ServiceCollection +io.personium.core.msg.PL-SC-0001=[EngineRelay] method={0} Url={1} + ## Elastic Search io.personium.core.msg.PL-ES-0001=Connected to {0} io.personium.core.msg.PL-ES-0002=ESReq index={0} type={1} node={2} reqType={4} data={3} From 1ebf4d58d2804cbbf97d42d04566fbe6f23221b3 Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Tue, 30 Jul 2019 16:04:51 +0900 Subject: [PATCH 17/69] Add functions to PersoniumCoreLog --- .../io/personium/core/PersoniumCoreLog.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/main/java/io/personium/core/PersoniumCoreLog.java b/src/main/java/io/personium/core/PersoniumCoreLog.java index c3d015c64..483d190a0 100644 --- a/src/main/java/io/personium/core/PersoniumCoreLog.java +++ b/src/main/java/io/personium/core/PersoniumCoreLog.java @@ -72,6 +72,12 @@ public static class Dav { * {0}: UUID of binary data */ public static final PersoniumCoreLog FILE_DELETE_FAIL = create("PL-DV-0004"); + /** + * Write file. + * {0}: File path + * {1}: File size + */ + public static final PersoniumCoreLog FILE_OPERATION = create("PL-DV-0005"); } /** @@ -427,6 +433,14 @@ public static PersoniumCoreLog create(String code) { return new PersoniumCoreLog(code, severity, message); } + /** + * It creates a new log instance. + * @return PersoniumCoreLog + */ + public PersoniumCoreLog create() { + return new PersoniumCoreLog(this.code, this.severity, this.message); + } + /** * Return log code. * @return log code @@ -448,6 +462,15 @@ public PersoniumCoreLog params(final Object... params) { return ret; } + /** + * It set a message with a parameter substitution, and the expression of {1} {2} etc. on the error message is a keyword for parameter substitution. + * @param params Additional message + */ + public void setParams(final Object... params) { + String messageFormat = PersoniumCoreMessageUtils.getMessage(code); + this.message = MessageFormat.format(messageFormat, params); + } + /** * Cause Create and return an exception added. * @param t cause exception From 4bf23614c754400eceb4cac8b514e58a9301c443 Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Tue, 30 Jul 2019 16:09:06 +0900 Subject: [PATCH 18/69] Add I/O log for WebDAV operation --- .../model/file/StreamingOutputForDavFile.java | 13 ++++++++++++- .../StreamingOutputForDavFileWithRange.java | 9 +++++++++ .../core/model/impl/fs/DavCmpFsImpl.java | 19 ++++++++++++++++++- .../core/model/impl/fs/DavMetadataFile.java | 11 ++++++++--- .../resources/personium-log-level.properties | 1 + .../resources/personium-messages.properties | 1 + 6 files changed, 49 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java index 95f74af1f..5bf8bbaad 100644 --- a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java +++ b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java @@ -32,6 +32,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import io.personium.core.PersoniumCoreLog; import io.personium.core.PersoniumUnitConfig; /** @@ -40,6 +41,9 @@ public class StreamingOutputForDavFile implements StreamingOutput { private static Logger logger = LoggerFactory.getLogger(StreamingOutputForDavFile.class); + private static final int KILO_BYTES = 1000; + private String fileFullPath; + private PersoniumCoreLog fileOperationLog = PersoniumCoreLog.Dav.FILE_OPERATION.create(); /** * Maximum number of retries at the time of reading / writing Dav file, hard link creation / file name modification. @@ -73,6 +77,7 @@ public StreamingOutputForDavFile(String fileFullPath, String cellId, String encr if (!Files.exists(Paths.get(fileFullPath))) { throw new BinaryDataNotFoundException(fileFullPath); } + this.fileFullPath = fileFullPath; //Generate a unique name to create a read-only hard link. String hardLinkName = UniqueNameComposer.compose(fileFullPath); @@ -113,13 +118,19 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti if (null == hardLinkInput) { throw new WebApplicationException(new BinaryDataNotFoundException(hardLinkPath.toString())); } + this.fileOperationLog.setParams(fileFullPath, 0); + this.fileOperationLog.writeStartLog(); + + int writtenBytes = 0; try { - IOUtils.copy(hardLinkInput, output); + writtenBytes = IOUtils.copy(hardLinkInput, output); } finally { IOUtils.closeQuietly(hardLinkInput); //Cleanup. Delete the reading hard link for yourself. Files.delete(hardLinkPath); } + this.fileOperationLog.setParams(fileFullPath, writtenBytes / KILO_BYTES); + this.fileOperationLog.writeEndLog(); } } diff --git a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java index 5437d5198..a1b0c1e47 100644 --- a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java +++ b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java @@ -37,6 +37,10 @@ public class StreamingOutputForDavFileWithRange extends StreamingOutputForDavFil private RangeHeaderHandler range = null; private long fileSize = 0; + private String fileFullPath; + private PersoniumCoreLog fileOperationLog = PersoniumCoreLog.Dav.FILE_OPERATION.create(); + + private static final int KILO_BYTES = 1000; /** * constructor. @@ -55,10 +59,13 @@ public StreamingOutputForDavFileWithRange(final String fileFullPath, super(fileFullPath, cellId, encryptionType); this.range = range; this.fileSize = fileSize; + this.fileFullPath = fileFullPath; } @Override public void write(OutputStream output) throws IOException, WebApplicationException { + this.fileOperationLog.setParams(fileFullPath, 0); + this.fileOperationLog.writeStartLog(); try { //Because it does not correspond to MultiPart, it processes only the first byte-renge-set. int rangeIndex = 0; @@ -84,6 +91,8 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti } output.write((char) chr); } + this.fileOperationLog.setParams(fileFullPath, fileSize / KILO_BYTES); + this.fileOperationLog.writeEndLog(); } finally { IOUtils.closeQuietly(hardLinkInput); Files.delete(hardLinkPath); 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 f6090b5ac..1dd72effa 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 @@ -118,12 +118,14 @@ public class DavCmpFsImpl implements DavCmp { DavCmpFsImpl parent; List ownerRepresentativeAccounts = new ArrayList(); boolean isPhantom = false; + private final PersoniumCoreLog fileOperationLog = PersoniumCoreLog.Dav.FILE_OPERATION.create(); /** * Fixed File Name for storing file. */ public static final String CONTENT_FILE_NAME = "content"; private static final String TEMP_FILE_NAME = "tmp"; + private static final int KILO_BYTES = 1000; /* * logger. @@ -581,6 +583,8 @@ protected ResponseBuilder doPutForCreate(final String contentType, final InputSt DataCryptor cryptor = new DataCryptor(getCellId()); input = cryptor.encode(inputStream, PersoniumUnitConfig.isDavEncryptEnabled()); + this.fileOperationLog.setParams(getContentFilePath(), 0); + this.fileOperationLog.writeStartLog(); BufferedInputStream bufferedInput = new BufferedInputStream(input); try { // create new directory. @@ -597,6 +601,8 @@ protected ResponseBuilder doPutForCreate(final String contentType, final InputSt if (PersoniumUnitConfig.getFsyncEnabled()) { sync(newFile); } + this.fileOperationLog.setParams(getContentFilePath(), writtenBytes / KILO_BYTES); + this.fileOperationLog.writeEndLog(); // create new metadata file. this.metaFile = DavMetadataFile.prepareNewFile(this, DavCmp.TYPE_DAV_FILE); @@ -636,6 +642,8 @@ protected ResponseBuilder doPutForUpdate(final String contentType, final InputSt throw PersoniumCoreException.Dav.ETAG_NOT_MATCH; } + this.fileOperationLog.setParams(getContentFilePath(), 0); + this.fileOperationLog.writeStartLog(); try { // Update Content InputStream input = inputStream; @@ -658,6 +666,8 @@ protected ResponseBuilder doPutForUpdate(final String contentType, final InputSt writtenBytes = ((CipherInputStream) input).getReadLengthBeforEncryption(); encryptionType = DataCryptor.ENCRYPTION_TYPE_AES; } + this.fileOperationLog.setParams(getContentFilePath(), writtenBytes / KILO_BYTES); + this.fileOperationLog.writeEndLog(); // Update Metadata this.metaFile.setUpdated(now); @@ -689,8 +699,9 @@ public final ResponseBuilder get(final String rangeHeaderField) { //Range header analysis processing final RangeHeaderHandler range = RangeHeaderHandler.parse(rangeHeaderField, fileSize); + this.fileOperationLog.setParams(fileFullPath, fileSize / KILO_BYTES); + this.fileOperationLog.writeStartLog(); try { - //Differentiate between processing with Range header specification if (!range.isValid()) { //Return whole file @@ -714,6 +725,7 @@ public final ResponseBuilder get(final String rangeHeaderField) { res = davFileResponseForRange(sout, contentType, range); } } + this.fileOperationLog.writeEndLog(); return res.header(HttpHeaders.ETAG, getEtag()).header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); @@ -996,11 +1008,16 @@ public ResponseBuilder delete(final String ifMatch, boolean recursive) { * Exec delete. */ protected void doDelete() { + this.fileOperationLog.setParams(getContentFilePath(), getContentLength() / KILO_BYTES); + this.fileOperationLog.writeStartLog(); + try { FileUtils.deleteDirectory(this.fsDir); } catch (IOException e) { throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(e); } + + this.fileOperationLog.writeEndLog(); } /** diff --git a/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java b/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java index e58f787b4..d0da0340f 100644 --- a/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java +++ b/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java @@ -33,6 +33,7 @@ import io.personium.common.es.util.PersoniumUUID; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; +import io.personium.core.PersoniumCoreLog; /** * a class for handling internal fs file storing Dav metadata. @@ -49,10 +50,11 @@ public class DavMetadataFile { private static final long META_LOAD_RETRY_WAIT = 100L; /** Maximum number of metafile reading retries. */ private static final int META_LOAD_RETRY_MAX = 5; + private static final int KILO_BYTES = 1000; File file; - JSONObject json = new JSONObject(); + private final PersoniumCoreLog fileOperationLog = PersoniumCoreLog.Dav.FILE_OPERATION.create(); /** JSON Key for ID. */ private static final String KEY_ID = "i"; @@ -208,9 +210,12 @@ private void doLoad() throws PersoniumCoreException { * save to the file. */ public void save() { - log.debug("save started."); this.incrementVersion(); String jsonStr = JSONObject.toJSONString(this.getJSON()); + + this.fileOperationLog.setParams(this.file.toPath(), jsonStr.getBytes(Charsets.UTF_8).length / KILO_BYTES); + this.fileOperationLog.writeStartLog(); + try { if (PersoniumUnitConfig.getFsyncEnabled()) { Files.write(this.file.toPath(), jsonStr.getBytes(Charsets.UTF_8), @@ -221,7 +226,7 @@ public void save() { } catch (IOException e) { throw new RuntimeException(e); } - log.debug("save ended."); + this.fileOperationLog.writeEndLog(); } private void incrementVersion() { diff --git a/src/main/resources/personium-log-level.properties b/src/main/resources/personium-log-level.properties index bc8fbdce4..7c6eb486f 100644 --- a/src/main/resources/personium-log-level.properties +++ b/src/main/resources/personium-log-level.properties @@ -44,6 +44,7 @@ io.personium.core.loglevel.PL-SV-0020=error # Dav io.personium.core.loglevel.PL-DV-0001=info io.personium.core.loglevel.PL-DV-0002=info +io.personium.core.loglevel.PL-DV-0005=debug io.personium.core.loglevel.PR503-DV-0001=info # Auth diff --git a/src/main/resources/personium-messages.properties b/src/main/resources/personium-messages.properties index 7a416f2a2..8cb3f8275 100644 --- a/src/main/resources/personium-messages.properties +++ b/src/main/resources/personium-messages.properties @@ -391,6 +391,7 @@ io.personium.core.msg.PL-DV-0001=Role not found at [{0}]. io.personium.core.msg.PL-DV-0002=Requested range not satisfiable at [{0}]. io.personium.core.msg.PL-DV-0003=Dav file too short at [{0}.size={1},range={2}]. io.personium.core.msg.PL-DV-0004=Failed to delete binary data. id={0} +io.personium.core.msg.PL-DV-0005=Operated a file. [path={0},size={1}KB] ## Server io.personium.core.msg.PL-SV-0001=Authentic Data Store Entity Create Fail. Message={0} From e77d5126820aadcde2d4599cb281b77dd45e9de1 Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Wed, 31 Jul 2019 17:09:38 +0900 Subject: [PATCH 19/69] Add PersoniumMeasurementLog --- .../io/personium/core/PersoniumCoreLog.java | 70 +++-------- .../core/PersoniumMeasurmentLog.java | 113 ++++++++++++++++++ .../personium/core/PersoniumUnitConfig.java | 1 + .../model/file/StreamingOutputForDavFile.java | 15 +-- .../StreamingOutputForDavFileWithRange.java | 18 +-- .../core/model/impl/fs/DavCmpFsImpl.java | 46 ++++--- .../core/model/impl/fs/DavMetadataFile.java | 13 +- .../PersoniumEngineSvcCollectionResource.java | 14 +-- .../resources/personium-log-level.properties | 2 + .../resources/personium-messages.properties | 6 +- 10 files changed, 201 insertions(+), 97 deletions(-) create mode 100644 src/main/java/io/personium/core/PersoniumMeasurmentLog.java diff --git a/src/main/java/io/personium/core/PersoniumCoreLog.java b/src/main/java/io/personium/core/PersoniumCoreLog.java index 483d190a0..6c9000e8e 100644 --- a/src/main/java/io/personium/core/PersoniumCoreLog.java +++ b/src/main/java/io/personium/core/PersoniumCoreLog.java @@ -26,7 +26,7 @@ /** * Log message creation class. */ -public final class PersoniumCoreLog { +public class PersoniumCoreLog { static Logger log = LoggerFactory.getLogger(PersoniumCoreLog.class); @@ -77,7 +77,7 @@ public static class Dav { * {0}: File path * {1}: File size */ - public static final PersoniumCoreLog FILE_OPERATION = create("PL-DV-0005"); + public static final PersoniumCoreLog FILE_OPERATION_START = create("PL-DV-0005"); } /** @@ -193,16 +193,6 @@ public static class OIDC { public static final PersoniumCoreLog ACCOUNT_IS_DEACTIVATED = create("PL-OI-0005"); } - /** - * Service collection. - */ - public static class ServiceCollection { - /** - * Personium-Engine reley starts/ends. - */ - public static final PersoniumCoreLog SC_ENGINE_RELAY = create("PL-SC-0001"); - } - /** * Server internal error. * Throw when a process can not be continued due to a server side failure or bug, which is to indicate the cause of the problem. Basically, when exceptions occur in category of WARN or more log output @@ -321,6 +311,16 @@ public static class Server { */ public static final PersoniumCoreLog WRITE_ADS_FAILURE_LOG_INFO = create("PL-SV-0021"); } + /** + * Service collection. + */ + + public static class ServiceCollection { + /** + * Personium-Engine reley starts. + */ + public static final PersoniumCoreLog SC_ENGINE_RELAY_START = create("PL-SC-0001"); + } /** * ElasticSearch. @@ -376,7 +376,6 @@ public static class Misc { String code; Severity severity; Throwable reason; - long startTime = 0L; /** * Force load inner class. @@ -433,14 +432,6 @@ public static PersoniumCoreLog create(String code) { return new PersoniumCoreLog(code, severity, message); } - /** - * It creates a new log instance. - * @return PersoniumCoreLog - */ - public PersoniumCoreLog create() { - return new PersoniumCoreLog(this.code, this.severity, this.message); - } - /** * Return log code. * @return log code @@ -462,15 +453,6 @@ public PersoniumCoreLog params(final Object... params) { return ret; } - /** - * It set a message with a parameter substitution, and the expression of {1} {2} etc. on the error message is a keyword for parameter substitution. - * @param params Additional message - */ - public void setParams(final Object... params) { - String messageFormat = PersoniumCoreMessageUtils.getMessage(code); - this.message = MessageFormat.format(messageFormat, params); - } - /** * Cause Create and return an exception added. * @param t cause exception @@ -494,31 +476,11 @@ public void writeLog() { } /** - * Log output with time measurement. + * Write log with message format and params. + * @param msgFormat message format + * @param params parameters for message formatting */ - public void writeStartLog() { - this.startTime = System.currentTimeMillis(); - writeLog(); - } - - /** - * Log output with time measurement. - * Output example) - * 2012-09-09 11:23:47.029 [main] [INFO ] CoreLog - [Elapsed time: 10ms] - [io.personium.core.CoreLogTest#test:22] - JSON Parse Error. - */ - public void writeEndLog() { - if (this.startTime == 0L) { - writeLog(); - return; - } - StackTraceElement[] ste = new Throwable().getStackTrace(); - final long elapsedTime = System.currentTimeMillis() - this.startTime; - doWriteLog("[%s] - [Elapsed time: %dms] - [%s#%s:%s] - %s", - this.code, elapsedTime, ste[1].getClassName(), ste[1].getMethodName(), ste[1].getLineNumber(), - this.message); - } - - private void doWriteLog(String msgFormat, Object... params) { + protected void doWriteLog(String msgFormat, Object... params) { String logInfo = String.format(msgFormat, params); switch (this.severity) { case INFO: diff --git a/src/main/java/io/personium/core/PersoniumMeasurmentLog.java b/src/main/java/io/personium/core/PersoniumMeasurmentLog.java new file mode 100644 index 000000000..b2b7ea60e --- /dev/null +++ b/src/main/java/io/personium/core/PersoniumMeasurmentLog.java @@ -0,0 +1,113 @@ +/** + * personium.io + * 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. + * 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.core; + +import java.text.MessageFormat; + +/** + * Log message with measurement creation class. + */ +public final class PersoniumMeasurmentLog extends PersoniumCoreLog { + + /** + * WebDAV related. + */ + public static class Dav { + /** + * Write file. + * {0}: File path + * {1}: File size + */ + public static final PersoniumMeasurmentLog FILE_OPERATION_END = create("PL-DV-0006"); + } + + /** + * Service collection. + */ + public static class ServiceCollection { + /** + * Personium-Engine reley ends. + */ + public static final PersoniumMeasurmentLog SC_ENGINE_RELAY_END = create("PL-SC-0002"); + } + + private long startTime = 0L; + + PersoniumMeasurmentLog(PersoniumCoreLog coreLog) { + super(coreLog.code, coreLog.severity, coreLog.message); + } + + /** + * Force load inner class. + * Add an inner class of error classification here if it is added. + */ + public static void loadConfig() { + new Dav(); + new ServiceCollection(); + } + + /** + * It creates and returns a message with a parameter substitution, and the expression of {1} {2} etc. on the error message is a keyword for parameter substitution. + * @param params Additional message + * @return PersoniumMeasurmentLog + */ + public PersoniumMeasurmentLog params(final Object... params) { + return new PersoniumMeasurmentLog(super.params(params)); + } + + /** + * It set a message with a parameter substitution, and the expression of {1} {2} etc. on the error message is a keyword for parameter substitution. + * @param params Additional message + */ + public void setParams(final Object... params) { + String messageFormat = PersoniumCoreMessageUtils.getMessage(code); + this.message = MessageFormat.format(messageFormat, params); + } + + /** + * Factory method. + * @param code log code + * @return PersoniumMeasurmentLog + */ + public static PersoniumMeasurmentLog create(String code) { + return new PersoniumMeasurmentLog(PersoniumCoreLog.create(code)); + } + + /** + * Set start time. + */ + public void setStartTime() { + this.startTime = System.currentTimeMillis(); + } + + /** + * Log output with time measurement.. + * When outputting the log, display the class name, method name, number of lines, and measurement time of the log output source. + * Output example) + * 2019-07-31 15:18:00.558 [main] [INFO ] PersoniumCoreLog [PL-SC-0002] - [io.personium.core.PersoniumMeasurementLogTest#ログ出力正常系のテスト:67] - [EngineRelay] End. (1000ms) + */ + public void writeLog() { + if (this.startTime != 0L) { + long elapsedTime = System.currentTimeMillis() - this.startTime; + this.message = this.message.replaceFirst("%time", String.format("%d", elapsedTime)); + } + StackTraceElement[] ste = new Throwable().getStackTrace(); + doWriteLog("[%s] - [%s#%s:%s] - %s", + this.code, ste[1].getClassName(), ste[1].getMethodName(), ste[1].getLineNumber(), this.message); + } + +} diff --git a/src/main/java/io/personium/core/PersoniumUnitConfig.java b/src/main/java/io/personium/core/PersoniumUnitConfig.java index 3fbf799b4..7c8138b14 100644 --- a/src/main/java/io/personium/core/PersoniumUnitConfig.java +++ b/src/main/java/io/personium/core/PersoniumUnitConfig.java @@ -477,6 +477,7 @@ public static final class Introspect { static { //Forcibly load various message output classes PersoniumCoreLog.loadConfig(); + PersoniumMeasurmentLog.loadConfig(); PersoniumCoreException.loadConfig(); PersoniumCoreAuthnException.loadConfig(); } diff --git a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java index 5bf8bbaad..4e440d3bc 100644 --- a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java +++ b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java @@ -33,6 +33,7 @@ import org.slf4j.LoggerFactory; import io.personium.core.PersoniumCoreLog; +import io.personium.core.PersoniumMeasurmentLog; import io.personium.core.PersoniumUnitConfig; /** @@ -42,8 +43,6 @@ public class StreamingOutputForDavFile implements StreamingOutput { private static Logger logger = LoggerFactory.getLogger(StreamingOutputForDavFile.class); private static final int KILO_BYTES = 1000; - private String fileFullPath; - private PersoniumCoreLog fileOperationLog = PersoniumCoreLog.Dav.FILE_OPERATION.create(); /** * Maximum number of retries at the time of reading / writing Dav file, hard link creation / file name modification. @@ -77,7 +76,6 @@ public StreamingOutputForDavFile(String fileFullPath, String cellId, String encr if (!Files.exists(Paths.get(fileFullPath))) { throw new BinaryDataNotFoundException(fileFullPath); } - this.fileFullPath = fileFullPath; //Generate a unique name to create a read-only hard link. String hardLinkName = UniqueNameComposer.compose(fileFullPath); @@ -118,8 +116,10 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti if (null == hardLinkInput) { throw new WebApplicationException(new BinaryDataNotFoundException(hardLinkPath.toString())); } - this.fileOperationLog.setParams(fileFullPath, 0); - this.fileOperationLog.writeStartLog(); + // write start log + PersoniumCoreLog.Dav.FILE_OPERATION_START.params("-").writeLog(); + PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + endLog.setStartTime(); int writtenBytes = 0; try { @@ -129,8 +129,9 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti //Cleanup. Delete the reading hard link for yourself. Files.delete(hardLinkPath); } - this.fileOperationLog.setParams(fileFullPath, writtenBytes / KILO_BYTES); - this.fileOperationLog.writeEndLog(); + // write end log + endLog.setParams(writtenBytes / KILO_BYTES); + endLog.writeLog(); } } diff --git a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java index a1b0c1e47..11cd84fbd 100644 --- a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java +++ b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java @@ -27,6 +27,7 @@ import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; +import io.personium.core.PersoniumMeasurmentLog; import io.personium.core.http.header.ByteRangeSpec; import io.personium.core.http.header.RangeHeaderHandler; @@ -37,8 +38,6 @@ public class StreamingOutputForDavFileWithRange extends StreamingOutputForDavFil private RangeHeaderHandler range = null; private long fileSize = 0; - private String fileFullPath; - private PersoniumCoreLog fileOperationLog = PersoniumCoreLog.Dav.FILE_OPERATION.create(); private static final int KILO_BYTES = 1000; @@ -59,13 +58,15 @@ public StreamingOutputForDavFileWithRange(final String fileFullPath, super(fileFullPath, cellId, encryptionType); this.range = range; this.fileSize = fileSize; - this.fileFullPath = fileFullPath; } @Override public void write(OutputStream output) throws IOException, WebApplicationException { - this.fileOperationLog.setParams(fileFullPath, 0); - this.fileOperationLog.writeStartLog(); + // write start log + PersoniumCoreLog.Dav.FILE_OPERATION_START.params("-").writeLog(); + PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + endLog.setStartTime(); + try { //Because it does not correspond to MultiPart, it processes only the first byte-renge-set. int rangeIndex = 0; @@ -91,12 +92,15 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti } output.write((char) chr); } - this.fileOperationLog.setParams(fileFullPath, fileSize / KILO_BYTES); - this.fileOperationLog.writeEndLog(); + + // write end log + endLog.setParams(last / KILO_BYTES); + endLog.writeLog(); } finally { IOUtils.closeQuietly(hardLinkInput); Files.delete(hardLinkPath); } + } } 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 1dd72effa..01a951fc8 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 @@ -67,6 +67,7 @@ import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; +import io.personium.core.PersoniumMeasurmentLog; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; import io.personium.core.auth.BoxPrivilege; @@ -118,7 +119,6 @@ public class DavCmpFsImpl implements DavCmp { DavCmpFsImpl parent; List ownerRepresentativeAccounts = new ArrayList(); boolean isPhantom = false; - private final PersoniumCoreLog fileOperationLog = PersoniumCoreLog.Dav.FILE_OPERATION.create(); /** * Fixed File Name for storing file. @@ -583,8 +583,11 @@ protected ResponseBuilder doPutForCreate(final String contentType, final InputSt DataCryptor cryptor = new DataCryptor(getCellId()); input = cryptor.encode(inputStream, PersoniumUnitConfig.isDavEncryptEnabled()); - this.fileOperationLog.setParams(getContentFilePath(), 0); - this.fileOperationLog.writeStartLog(); + // write start log + PersoniumCoreLog.Dav.FILE_OPERATION_START.params(getContentFilePath()).writeLog(); + PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + endLog.setStartTime(); + BufferedInputStream bufferedInput = new BufferedInputStream(input); try { // create new directory. @@ -601,8 +604,9 @@ protected ResponseBuilder doPutForCreate(final String contentType, final InputSt if (PersoniumUnitConfig.getFsyncEnabled()) { sync(newFile); } - this.fileOperationLog.setParams(getContentFilePath(), writtenBytes / KILO_BYTES); - this.fileOperationLog.writeEndLog(); + // write end log + endLog.setParams(writtenBytes / KILO_BYTES); + endLog.writeLog(); // create new metadata file. this.metaFile = DavMetadataFile.prepareNewFile(this, DavCmp.TYPE_DAV_FILE); @@ -642,8 +646,10 @@ protected ResponseBuilder doPutForUpdate(final String contentType, final InputSt throw PersoniumCoreException.Dav.ETAG_NOT_MATCH; } - this.fileOperationLog.setParams(getContentFilePath(), 0); - this.fileOperationLog.writeStartLog(); + // Write start log + PersoniumCoreLog.Dav.FILE_OPERATION_START.params(getContentFilePath()).writeLog(); + PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + endLog.setStartTime(); try { // Update Content InputStream input = inputStream; @@ -666,8 +672,9 @@ protected ResponseBuilder doPutForUpdate(final String contentType, final InputSt writtenBytes = ((CipherInputStream) input).getReadLengthBeforEncryption(); encryptionType = DataCryptor.ENCRYPTION_TYPE_AES; } - this.fileOperationLog.setParams(getContentFilePath(), writtenBytes / KILO_BYTES); - this.fileOperationLog.writeEndLog(); + // Write end log + endLog.setParams(writtenBytes / KILO_BYTES); + endLog.writeLog(); // Update Metadata this.metaFile.setUpdated(now); @@ -699,8 +706,10 @@ public final ResponseBuilder get(final String rangeHeaderField) { //Range header analysis processing final RangeHeaderHandler range = RangeHeaderHandler.parse(rangeHeaderField, fileSize); - this.fileOperationLog.setParams(fileFullPath, fileSize / KILO_BYTES); - this.fileOperationLog.writeStartLog(); + // write start log + PersoniumCoreLog.Dav.FILE_OPERATION_START.params(fileFullPath).writeLog(); + PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + endLog.setStartTime(); try { //Differentiate between processing with Range header specification if (!range.isValid()) { @@ -725,7 +734,10 @@ public final ResponseBuilder get(final String rangeHeaderField) { res = davFileResponseForRange(sout, contentType, range); } } - this.fileOperationLog.writeEndLog(); + // write end log + endLog.setParams(fileSize); + endLog.writeLog(); + return res.header(HttpHeaders.ETAG, getEtag()).header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, RangeHeaderHandler.BYTES_UNIT); @@ -1008,8 +1020,10 @@ public ResponseBuilder delete(final String ifMatch, boolean recursive) { * Exec delete. */ protected void doDelete() { - this.fileOperationLog.setParams(getContentFilePath(), getContentLength() / KILO_BYTES); - this.fileOperationLog.writeStartLog(); + // write start log + PersoniumCoreLog.Dav.FILE_OPERATION_START.params(getContentFilePath()).writeLog(); + PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + endLog.setStartTime(); try { FileUtils.deleteDirectory(this.fsDir); @@ -1017,7 +1031,9 @@ protected void doDelete() { throw PersoniumCoreException.Dav.FS_INCONSISTENCY_FOUND.reason(e); } - this.fileOperationLog.writeEndLog(); + // write end log + endLog.setParams("-"); + endLog.writeLog(); } /** diff --git a/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java b/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java index d0da0340f..e23ef6ab7 100644 --- a/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java +++ b/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java @@ -34,6 +34,7 @@ import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.core.PersoniumCoreLog; +import io.personium.core.PersoniumMeasurmentLog; /** * a class for handling internal fs file storing Dav metadata. @@ -54,7 +55,6 @@ public class DavMetadataFile { File file; JSONObject json = new JSONObject(); - private final PersoniumCoreLog fileOperationLog = PersoniumCoreLog.Dav.FILE_OPERATION.create(); /** JSON Key for ID. */ private static final String KEY_ID = "i"; @@ -213,8 +213,10 @@ public void save() { this.incrementVersion(); String jsonStr = JSONObject.toJSONString(this.getJSON()); - this.fileOperationLog.setParams(this.file.toPath(), jsonStr.getBytes(Charsets.UTF_8).length / KILO_BYTES); - this.fileOperationLog.writeStartLog(); + // write start log + PersoniumCoreLog.Dav.FILE_OPERATION_START.params(this.file.toPath()).writeLog(); + PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + endLog.setStartTime(); try { if (PersoniumUnitConfig.getFsyncEnabled()) { @@ -226,7 +228,10 @@ public void save() { } catch (IOException e) { throw new RuntimeException(e); } - this.fileOperationLog.writeEndLog(); + + // write end log + endLog.setParams(jsonStr.getBytes(Charsets.UTF_8).length / KILO_BYTES); + endLog.writeLog(); } private void incrementVersion() { diff --git a/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java index 04acdfb3c..3c9bb4a57 100644 --- a/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java @@ -62,6 +62,7 @@ import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; +import io.personium.core.PersoniumMeasurmentLog; import io.personium.core.PersoniumUnitConfig; import io.personium.core.annotations.ACL; import io.personium.core.annotations.MOVE; @@ -91,7 +92,6 @@ public class PersoniumEngineSvcCollectionResource { DavCmp davCmp = null; DavCollectionResource dcr = null; DavRsCmp davRsCmp; - PersoniumCoreLog relayLog = null; /** * constructor. @@ -490,9 +490,11 @@ private Response relaycommon( // CHECKSTYLE IGNORE - Necessary processing EventBus eventBus = this.davRsCmp.getAccessContext().getCell().getEventBus(); // write relay log - setRelayLog(req); - this.relayLog.writeStartLog(); + PersoniumCoreLog.ServiceCollection.SC_ENGINE_RELAY_START + .params(req.getMethod(), req.getURI()).writeLog(); debugRelayHeader(req); + PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.ServiceCollection.SC_ENGINE_RELAY_END.params(); + endLog.setStartTime(); //Throw a request to the Engine HttpResponse objResponse = null; @@ -511,7 +513,7 @@ private Response relaycommon( // CHECKSTYLE IGNORE - Necessary processing closeHttpClient(client, objResponse); throw PersoniumCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(ioe); } - this.relayLog.writeEndLog(); + endLog.writeLog(); // post event to EventBus String info = Integer.toString(objResponse.getStatusLine().getStatusCode()); @@ -596,10 +598,6 @@ private String getRequestKey(DavRsCmp rsCmp) { return getRequestKey(rsCmp.getParent()); } - private void setRelayLog(HttpUriRequest req) { - this.relayLog = PersoniumCoreLog.ServiceCollection.SC_ENGINE_RELAY.params(req.getMethod(), req.getURI()); - } - private void debugRelayHeader(HttpUriRequest req) { if (log.isDebugEnabled()) { Header[] reqHeaders = req.getAllHeaders(); diff --git a/src/main/resources/personium-log-level.properties b/src/main/resources/personium-log-level.properties index 7c6eb486f..a30e2d5f3 100644 --- a/src/main/resources/personium-log-level.properties +++ b/src/main/resources/personium-log-level.properties @@ -45,6 +45,7 @@ io.personium.core.loglevel.PL-SV-0020=error io.personium.core.loglevel.PL-DV-0001=info io.personium.core.loglevel.PL-DV-0002=info io.personium.core.loglevel.PL-DV-0005=debug +io.personium.core.loglevel.PL-DV-0006=debug io.personium.core.loglevel.PR503-DV-0001=info # Auth @@ -67,6 +68,7 @@ io.personium.core.loglevel.PL-OI-0004=info # ServiceCollection io.personium.core.loglevel.PL-SC-0001=info +io.personium.core.loglevel.PL-SC-0002=info # Elastic Search io.personium.core.loglevel.PL-ES-0001=info diff --git a/src/main/resources/personium-messages.properties b/src/main/resources/personium-messages.properties index 8cb3f8275..3cb52c5a0 100644 --- a/src/main/resources/personium-messages.properties +++ b/src/main/resources/personium-messages.properties @@ -391,7 +391,8 @@ io.personium.core.msg.PL-DV-0001=Role not found at [{0}]. io.personium.core.msg.PL-DV-0002=Requested range not satisfiable at [{0}]. io.personium.core.msg.PL-DV-0003=Dav file too short at [{0}.size={1},range={2}]. io.personium.core.msg.PL-DV-0004=Failed to delete binary data. id={0} -io.personium.core.msg.PL-DV-0005=Operated a file. [path={0},size={1}KB] +io.personium.core.msg.PL-DV-0005=Start file operation. [path={0}] +io.personium.core.msg.PL-DV-0006=End file operation. [time=%timems, size={0}KB] ## Server io.personium.core.msg.PL-SV-0001=Authentic Data Store Entity Create Fail. Message={0} @@ -439,7 +440,8 @@ io.personium.core.msg.PL-OI-0004=Issuer={0} not Google authorized. io.personium.core.msg.PL-OI-0005=Account is deactivated. [{0}] [{1}] [{2}] ## ServiceCollection -io.personium.core.msg.PL-SC-0001=[EngineRelay] method={0} Url={1} +io.personium.core.msg.PL-SC-0001=[EngineRelay] Start. Method={0} Url={1} +io.personium.core.msg.PL-SC-0002=[EngineRelay] End. (%timems) ## Elastic Search io.personium.core.msg.PL-ES-0001=Connected to {0} From e8db9e5e04f8b918ec9af2d8ae1c73c24b11c0d7 Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Wed, 31 Jul 2019 18:40:41 +0900 Subject: [PATCH 20/69] Improve log format --- src/main/java/io/personium/core/PersoniumCoreLog.java | 6 +++--- src/main/java/io/personium/core/PersoniumMeasurmentLog.java | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/personium/core/PersoniumCoreLog.java b/src/main/java/io/personium/core/PersoniumCoreLog.java index 6c9000e8e..5378cbbf3 100644 --- a/src/main/java/io/personium/core/PersoniumCoreLog.java +++ b/src/main/java/io/personium/core/PersoniumCoreLog.java @@ -467,12 +467,12 @@ public PersoniumCoreLog reason(final Throwable t) { * Log output. * When outputting the log, display the class name, method name, and the number of lines of the log output source. * Output example) - * 2012-09-09 11:23:47.029 [main] [INFO ] CoreLog [io.personium.core.CoreLogTest#test:22] - JSON Parse Error. + * 2019-07-31 18:27:05.834 [thread] [INFO ] PersoniumCoreLog [PL-ES-0002] - ESReq index=u0_unitadmin - [io.personium.core.model.impl.es.EsModel$2#handleEvent:57] */ public void writeLog() { StackTraceElement[] ste = new Throwable().getStackTrace(); - doWriteLog("[%s] - [%s#%s:%s] - %s", - this.code, ste[1].getClassName(), ste[1].getMethodName(), ste[1].getLineNumber(), this.message); + doWriteLog("[%s] - %s - [%s#%s:%s]", + this.code, this.message, ste[1].getClassName(), ste[1].getMethodName(), ste[1].getLineNumber()); } /** diff --git a/src/main/java/io/personium/core/PersoniumMeasurmentLog.java b/src/main/java/io/personium/core/PersoniumMeasurmentLog.java index b2b7ea60e..b9a36b9c8 100644 --- a/src/main/java/io/personium/core/PersoniumMeasurmentLog.java +++ b/src/main/java/io/personium/core/PersoniumMeasurmentLog.java @@ -98,7 +98,7 @@ public void setStartTime() { * Log output with time measurement.. * When outputting the log, display the class name, method name, number of lines, and measurement time of the log output source. * Output example) - * 2019-07-31 15:18:00.558 [main] [INFO ] PersoniumCoreLog [PL-SC-0002] - [io.personium.core.PersoniumMeasurementLogTest#ログ出力正常系のテスト:67] - [EngineRelay] End. (1000ms) + * 2019-07-31 15:18:00.558 [main] [INFO ] PersoniumCoreLog [PL-SC-0002] - [EngineRelay] End. (1000ms) - [io.personium.core.PersoniumMeasurementLogTest#testMethod:67] */ public void writeLog() { if (this.startTime != 0L) { @@ -106,8 +106,8 @@ public void writeLog() { this.message = this.message.replaceFirst("%time", String.format("%d", elapsedTime)); } StackTraceElement[] ste = new Throwable().getStackTrace(); - doWriteLog("[%s] - [%s#%s:%s] - %s", - this.code, ste[1].getClassName(), ste[1].getMethodName(), ste[1].getLineNumber(), this.message); + doWriteLog("[%s] - %s - [%s#%s:%s]", + this.code, this.message, ste[1].getClassName(), ste[1].getMethodName(), ste[1].getLineNumber()); } } From f8ad7c0bdd523865a4b960d6e7999628ae76443b Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Wed, 31 Jul 2019 19:56:44 +0900 Subject: [PATCH 21/69] Add RequestKey logging --- .../java/io/personium/core/PersoniumCoreLog.java | 6 ++++++ .../java/io/personium/core/rs/FacadeResource.java | 13 +++++++++---- src/main/resources/personium-log-level.properties | 1 + src/main/resources/personium-messages.properties | 1 + 4 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/personium/core/PersoniumCoreLog.java b/src/main/java/io/personium/core/PersoniumCoreLog.java index 5378cbbf3..cdf28fb44 100644 --- a/src/main/java/io/personium/core/PersoniumCoreLog.java +++ b/src/main/java/io/personium/core/PersoniumCoreLog.java @@ -310,6 +310,12 @@ public static class Server { * {0}: log information */ public static final PersoniumCoreLog WRITE_ADS_FAILURE_LOG_INFO = create("PL-SV-0021"); + /** + * Information of RequestKey. + * {0}: received or generated + * {1}: RequestKey + */ + public static final PersoniumCoreLog REQUEST_KEY = create("PL-SV-0022"); } /** * Service collection. diff --git a/src/main/java/io/personium/core/rs/FacadeResource.java b/src/main/java/io/personium/core/rs/FacadeResource.java index 680df2660..33d80b8ae 100644 --- a/src/main/java/io/personium/core/rs/FacadeResource.java +++ b/src/main/java/io/personium/core/rs/FacadeResource.java @@ -30,6 +30,7 @@ import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreException; +import io.personium.core.PersoniumCoreLog; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; import io.personium.core.model.Cell; @@ -95,6 +96,13 @@ public Object facade( log.debug(" X-Personium-Via: " + headerPersoniumVia); } + String requestKey = ResourceUtils.validateXPersoniumRequestKey(headerPersoniumRequestKey); + if (headerPersoniumRequestKey == null) { + PersoniumCoreLog.Server.REQUEST_KEY.params("generated", requestKey).writeLog(); + } else { + PersoniumCoreLog.Server.REQUEST_KEY.params("received", headerPersoniumRequestKey).writeLog(); + } + if (PersoniumUnitConfig.isPathBasedCellUrlEnabled()) { return new UnitResource(cookieAuthValue, cookiePeer, headerAuthz, headerHost, headerPersoniumUnitUser, uriInfo); @@ -122,10 +130,7 @@ public Object facade( CellLockManager.incrementReferenceCount(cell.getId()); httpServletRequest.setAttribute("cellId", cell.getId()); - String requestKey = ResourceUtils.validateXPersoniumRequestKey(headerPersoniumRequestKey); - if (headerPersoniumRequestKey == null) { - log.debug(" Create RequestKey: " + requestKey); - } + return new CellResource(ac, requestKey, headerPersoniumEventId, headerPersoniumRuleChain, headerPersoniumVia, httpServletRequest); } diff --git a/src/main/resources/personium-log-level.properties b/src/main/resources/personium-log-level.properties index a30e2d5f3..b5daac350 100644 --- a/src/main/resources/personium-log-level.properties +++ b/src/main/resources/personium-log-level.properties @@ -40,6 +40,7 @@ io.personium.core.loglevel.PL-SV-0016=info io.personium.core.loglevel.PL-SV-0018=info io.personium.core.loglevel.PL-SV-0019=error io.personium.core.loglevel.PL-SV-0020=error +io.personium.core.loglevel.PL-SV-0022=info # Dav io.personium.core.loglevel.PL-DV-0001=info diff --git a/src/main/resources/personium-messages.properties b/src/main/resources/personium-messages.properties index 3cb52c5a0..12dde289e 100644 --- a/src/main/resources/personium-messages.properties +++ b/src/main/resources/personium-messages.properties @@ -416,6 +416,7 @@ io.personium.core.msg.PL-SV-0018=JDBC Req db={0} table={1} id={2} type={3} celli io.personium.core.msg.PL-SV-0019=Set reference only lock. unit=[{0}] io.personium.core.msg.PL-SV-0020=Failed to write failure log for ads error. io.personium.core.msg.PL-SV-0021=Log info for ads error. [{0}] +io.personium.core.msg.PL-SV-0022=RequestKey {0}: [{1}] # Auth io.personium.core.msg.PL-AU-0001=Token parse error. Reason={0} From 2b720ec66ff17f2bea2cb807f1b02f85e000c611 Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Wed, 31 Jul 2019 19:58:28 +0900 Subject: [PATCH 22/69] Rename PersoniumMeasurmentLog to ElapsedTimeLog --- ...iumMeasurmentLog.java => ElapsedTimeLog.java} | 16 ++++++++-------- .../io/personium/core/PersoniumUnitConfig.java | 2 +- .../model/file/StreamingOutputForDavFile.java | 4 ++-- .../file/StreamingOutputForDavFileWithRange.java | 4 ++-- .../core/model/impl/fs/DavCmpFsImpl.java | 10 +++++----- .../core/model/impl/fs/DavMetadataFile.java | 4 ++-- .../PersoniumEngineSvcCollectionResource.java | 4 ++-- 7 files changed, 22 insertions(+), 22 deletions(-) rename src/main/java/io/personium/core/{PersoniumMeasurmentLog.java => ElapsedTimeLog.java} (84%) diff --git a/src/main/java/io/personium/core/PersoniumMeasurmentLog.java b/src/main/java/io/personium/core/ElapsedTimeLog.java similarity index 84% rename from src/main/java/io/personium/core/PersoniumMeasurmentLog.java rename to src/main/java/io/personium/core/ElapsedTimeLog.java index b9a36b9c8..0262eed61 100644 --- a/src/main/java/io/personium/core/PersoniumMeasurmentLog.java +++ b/src/main/java/io/personium/core/ElapsedTimeLog.java @@ -21,7 +21,7 @@ /** * Log message with measurement creation class. */ -public final class PersoniumMeasurmentLog extends PersoniumCoreLog { +public final class ElapsedTimeLog extends PersoniumCoreLog { /** * WebDAV related. @@ -32,7 +32,7 @@ public static class Dav { * {0}: File path * {1}: File size */ - public static final PersoniumMeasurmentLog FILE_OPERATION_END = create("PL-DV-0006"); + public static final ElapsedTimeLog FILE_OPERATION_END = create("PL-DV-0006"); } /** @@ -42,12 +42,12 @@ public static class ServiceCollection { /** * Personium-Engine reley ends. */ - public static final PersoniumMeasurmentLog SC_ENGINE_RELAY_END = create("PL-SC-0002"); + public static final ElapsedTimeLog SC_ENGINE_RELAY_END = create("PL-SC-0002"); } private long startTime = 0L; - PersoniumMeasurmentLog(PersoniumCoreLog coreLog) { + ElapsedTimeLog(PersoniumCoreLog coreLog) { super(coreLog.code, coreLog.severity, coreLog.message); } @@ -65,8 +65,8 @@ public static void loadConfig() { * @param params Additional message * @return PersoniumMeasurmentLog */ - public PersoniumMeasurmentLog params(final Object... params) { - return new PersoniumMeasurmentLog(super.params(params)); + public ElapsedTimeLog params(final Object... params) { + return new ElapsedTimeLog(super.params(params)); } /** @@ -83,8 +83,8 @@ public void setParams(final Object... params) { * @param code log code * @return PersoniumMeasurmentLog */ - public static PersoniumMeasurmentLog create(String code) { - return new PersoniumMeasurmentLog(PersoniumCoreLog.create(code)); + public static ElapsedTimeLog create(String code) { + return new ElapsedTimeLog(PersoniumCoreLog.create(code)); } /** diff --git a/src/main/java/io/personium/core/PersoniumUnitConfig.java b/src/main/java/io/personium/core/PersoniumUnitConfig.java index 7c8138b14..222edb85f 100644 --- a/src/main/java/io/personium/core/PersoniumUnitConfig.java +++ b/src/main/java/io/personium/core/PersoniumUnitConfig.java @@ -477,7 +477,7 @@ public static final class Introspect { static { //Forcibly load various message output classes PersoniumCoreLog.loadConfig(); - PersoniumMeasurmentLog.loadConfig(); + ElapsedTimeLog.loadConfig(); PersoniumCoreException.loadConfig(); PersoniumCoreAuthnException.loadConfig(); } diff --git a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java index 4e440d3bc..0892626d1 100644 --- a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java +++ b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFile.java @@ -33,7 +33,7 @@ import org.slf4j.LoggerFactory; import io.personium.core.PersoniumCoreLog; -import io.personium.core.PersoniumMeasurmentLog; +import io.personium.core.ElapsedTimeLog; import io.personium.core.PersoniumUnitConfig; /** @@ -118,7 +118,7 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti } // write start log PersoniumCoreLog.Dav.FILE_OPERATION_START.params("-").writeLog(); - PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + ElapsedTimeLog endLog = ElapsedTimeLog.Dav.FILE_OPERATION_END.params(); endLog.setStartTime(); int writtenBytes = 0; diff --git a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java index 11cd84fbd..1f4113dfe 100644 --- a/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java +++ b/src/main/java/io/personium/core/model/file/StreamingOutputForDavFileWithRange.java @@ -27,7 +27,7 @@ import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; -import io.personium.core.PersoniumMeasurmentLog; +import io.personium.core.ElapsedTimeLog; import io.personium.core.http.header.ByteRangeSpec; import io.personium.core.http.header.RangeHeaderHandler; @@ -64,7 +64,7 @@ public StreamingOutputForDavFileWithRange(final String fileFullPath, public void write(OutputStream output) throws IOException, WebApplicationException { // write start log PersoniumCoreLog.Dav.FILE_OPERATION_START.params("-").writeLog(); - PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + ElapsedTimeLog endLog = ElapsedTimeLog.Dav.FILE_OPERATION_END.params(); endLog.setStartTime(); try { 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 01a951fc8..4927831a7 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 @@ -67,7 +67,7 @@ import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; -import io.personium.core.PersoniumMeasurmentLog; +import io.personium.core.ElapsedTimeLog; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; import io.personium.core.auth.BoxPrivilege; @@ -585,7 +585,7 @@ protected ResponseBuilder doPutForCreate(final String contentType, final InputSt // write start log PersoniumCoreLog.Dav.FILE_OPERATION_START.params(getContentFilePath()).writeLog(); - PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + ElapsedTimeLog endLog = ElapsedTimeLog.Dav.FILE_OPERATION_END.params(); endLog.setStartTime(); BufferedInputStream bufferedInput = new BufferedInputStream(input); @@ -648,7 +648,7 @@ protected ResponseBuilder doPutForUpdate(final String contentType, final InputSt // Write start log PersoniumCoreLog.Dav.FILE_OPERATION_START.params(getContentFilePath()).writeLog(); - PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + ElapsedTimeLog endLog = ElapsedTimeLog.Dav.FILE_OPERATION_END.params(); endLog.setStartTime(); try { // Update Content @@ -708,7 +708,7 @@ public final ResponseBuilder get(final String rangeHeaderField) { // write start log PersoniumCoreLog.Dav.FILE_OPERATION_START.params(fileFullPath).writeLog(); - PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + ElapsedTimeLog endLog = ElapsedTimeLog.Dav.FILE_OPERATION_END.params(); endLog.setStartTime(); try { //Differentiate between processing with Range header specification @@ -1022,7 +1022,7 @@ public ResponseBuilder delete(final String ifMatch, boolean recursive) { protected void doDelete() { // write start log PersoniumCoreLog.Dav.FILE_OPERATION_START.params(getContentFilePath()).writeLog(); - PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + ElapsedTimeLog endLog = ElapsedTimeLog.Dav.FILE_OPERATION_END.params(); endLog.setStartTime(); try { diff --git a/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java b/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java index e23ef6ab7..c7d913718 100644 --- a/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java +++ b/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java @@ -34,7 +34,7 @@ import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumUnitConfig; import io.personium.core.PersoniumCoreLog; -import io.personium.core.PersoniumMeasurmentLog; +import io.personium.core.ElapsedTimeLog; /** * a class for handling internal fs file storing Dav metadata. @@ -215,7 +215,7 @@ public void save() { // write start log PersoniumCoreLog.Dav.FILE_OPERATION_START.params(this.file.toPath()).writeLog(); - PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.Dav.FILE_OPERATION_END.params(); + ElapsedTimeLog endLog = ElapsedTimeLog.Dav.FILE_OPERATION_END.params(); endLog.setStartTime(); try { diff --git a/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java index 3c9bb4a57..5b2b4effa 100644 --- a/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java @@ -62,7 +62,7 @@ import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; -import io.personium.core.PersoniumMeasurmentLog; +import io.personium.core.ElapsedTimeLog; import io.personium.core.PersoniumUnitConfig; import io.personium.core.annotations.ACL; import io.personium.core.annotations.MOVE; @@ -493,7 +493,7 @@ private Response relaycommon( // CHECKSTYLE IGNORE - Necessary processing PersoniumCoreLog.ServiceCollection.SC_ENGINE_RELAY_START .params(req.getMethod(), req.getURI()).writeLog(); debugRelayHeader(req); - PersoniumMeasurmentLog endLog = PersoniumMeasurmentLog.ServiceCollection.SC_ENGINE_RELAY_END.params(); + ElapsedTimeLog endLog = ElapsedTimeLog.ServiceCollection.SC_ENGINE_RELAY_END.params(); endLog.setStartTime(); //Throw a request to the Engine From 152dc4206680e0163782464c423eb47c9e89737e Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Wed, 31 Jul 2019 20:07:18 +0900 Subject: [PATCH 23/69] Modify CoreLog comments --- src/main/java/io/personium/core/ElapsedTimeLog.java | 3 +-- src/main/java/io/personium/core/PersoniumCoreLog.java | 3 ++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/personium/core/ElapsedTimeLog.java b/src/main/java/io/personium/core/ElapsedTimeLog.java index 0262eed61..4fade8b55 100644 --- a/src/main/java/io/personium/core/ElapsedTimeLog.java +++ b/src/main/java/io/personium/core/ElapsedTimeLog.java @@ -29,8 +29,7 @@ public final class ElapsedTimeLog extends PersoniumCoreLog { public static class Dav { /** * Write file. - * {0}: File path - * {1}: File size + * {0}: File size */ public static final ElapsedTimeLog FILE_OPERATION_END = create("PL-DV-0006"); } diff --git a/src/main/java/io/personium/core/PersoniumCoreLog.java b/src/main/java/io/personium/core/PersoniumCoreLog.java index cdf28fb44..08f4529c1 100644 --- a/src/main/java/io/personium/core/PersoniumCoreLog.java +++ b/src/main/java/io/personium/core/PersoniumCoreLog.java @@ -75,7 +75,6 @@ public static class Dav { /** * Write file. * {0}: File path - * {1}: File size */ public static final PersoniumCoreLog FILE_OPERATION_START = create("PL-DV-0005"); } @@ -324,6 +323,8 @@ public static class Server { public static class ServiceCollection { /** * Personium-Engine reley starts. + * {0}: HTTP Method + * {1}: Engine URL */ public static final PersoniumCoreLog SC_ENGINE_RELAY_START = create("PL-SC-0001"); } From 2aec067e2231c033888172d9a303d11216c637a8 Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Thu, 1 Aug 2019 09:57:35 +0900 Subject: [PATCH 24/69] Fix file size unit --- src/main/java/io/personium/core/model/impl/fs/DavCmpFsImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 4927831a7..60097994d 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 @@ -735,7 +735,7 @@ public final ResponseBuilder get(final String rangeHeaderField) { } } // write end log - endLog.setParams(fileSize); + endLog.setParams(fileSize / KILO_BYTES); endLog.writeLog(); return res.header(HttpHeaders.ETAG, getEtag()).header(PersoniumCoreUtils.HttpHeaders.ACCEPT_RANGES, From 1a08989a950cb94f3e4d018ecb10acbe139febff Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Fri, 2 Aug 2019 11:46:11 +0900 Subject: [PATCH 25/69] Add logging to reading a meta file --- .../io/personium/core/model/impl/fs/DavMetadataFile.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java b/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java index c7d913718..4747ddd3d 100644 --- a/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java +++ b/src/main/java/io/personium/core/model/impl/fs/DavMetadataFile.java @@ -197,9 +197,18 @@ public void load() { * load from the file. */ private void doLoad() throws PersoniumCoreException { + // write start log + PersoniumCoreLog.Dav.FILE_OPERATION_START.params(file.toPath()).writeLog(); + ElapsedTimeLog endLog = ElapsedTimeLog.Dav.FILE_OPERATION_END.params(); + endLog.setStartTime(); + try (Reader reader = Files.newBufferedReader(file.toPath(), Charsets.UTF_8)) { JSONParser parser = new JSONParser(); this.json = (JSONObject) parser.parse(reader); + // write end log + int jsonSize = this.json.toJSONString().getBytes(Charsets.UTF_8).length; + endLog.setParams(jsonSize / KILO_BYTES); + endLog.writeLog(); } catch (IOException | ParseException e) { // IO failure or JSON is broken throw PersoniumCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e); From 56b80ec5a15fb9c77c9b988c123a2c73dd0b089d Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Fri, 9 Aug 2019 14:42:07 +0900 Subject: [PATCH 26/69] Release v1.7.17 --- CHANGELOG.md | 4 ++++ pom.xml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35e39590a..57ad9fa0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 1.7.17 +IMPROVEMENTS: +* Add IO logging with IO time. ([#446](https://github.com/personium/personium-core/issues/446)) + ## 1.7.16 BUG FIXES: * Even if Depth:1 is specified in "Retrieve cell snapshot file setting" API, it is ignored. ([#439](https://github.com/personium/personium-core/issues/439)) diff --git a/pom.xml b/pom.xml index 1c9170c09..90dad118f 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ io.personium personium-core war - 1.7.17_es6.6.1-SNAPSHOT + 1.7.17_es6.6.1 personium-core Maven Webapp http://maven.apache.org From bbaa9893be3c694216c6dd2a99b14f03e3ba2b42 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sat, 10 Aug 2019 13:13:16 +0900 Subject: [PATCH 27/69] store localunit based URL for Acl base. --- .../io/personium/core/model/jaxb/Acl.java | 5 +- .../personium/test/jersey/cell/AclTest.java | 55 +++++++++++++++++-- 2 files changed, 54 insertions(+), 6 deletions(-) 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..f268f93cd 100644 --- a/src/main/java/io/personium/core/model/jaxb/Acl.java +++ b/src/main/java/io/personium/core/model/jaxb/Acl.java @@ -43,6 +43,7 @@ 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. @@ -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); } /** 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 4ca398c88..00c3a1921 100644 --- a/src/test/java/io/personium/test/jersey/cell/AclTest.java +++ b/src/test/java/io/personium/test/jersey/cell/AclTest.java @@ -27,8 +27,12 @@ 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; @@ -36,11 +40,16 @@ 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()); @@ -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にアクセスできることを確認テスト. @@ -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); } } @@ -2111,6 +2155,9 @@ private void logListAclTest(List account) { } } + + + private void deleteBox(String boxName, String location) { if (location == null) { From 970985e4d2fe433bf394b22b3918a9a0dca59b74 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 11 Aug 2019 01:14:39 +0900 Subject: [PATCH 28/69] accept client_id with localunit scheme, and add tests --- .../core/rs/cell/TokenEndPointResource.java | 4 + .../io/personium/core/model/jaxb/AclTest.java | 52 ++++++ .../cell/auth/token/TokenIssuanceTest.java | 169 ++++++++++++++++++ .../jersey/cell/auth/token/TokenTest.java | 4 +- 4 files changed, 227 insertions(+), 2 deletions(-) create mode 100644 src/test/java/io/personium/core/model/jaxb/AclTest.java create mode 100644 src/test/java/io/personium/test/jersey/cell/auth/token/TokenIssuanceTest.java 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 92fb37a2e..08841c527 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -150,6 +150,7 @@ public final Response token(@Context final UriInfo uriInfo, // relsolve personium-localunit scheme url. String target = UriUtils.convertSchemeFromLocalUnitToHttp(pTarget); + //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) { @@ -370,6 +371,9 @@ public static String clientAuth(final String clientId, final String clientSecret } } + // relsolve personium-localunit scheme url. + targetClientId = UriUtils.resolveLocalUnit(targetClientId); + //Check pw //· Since PW is a SAML token, it is parsed. TransCellAccessToken tcToken = null; 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/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..8eefae969 --- /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.AccountAccessToken; +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); + + AccountAccessToken aat = AccountAccessToken.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..684aefb76 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 @@ -47,7 +47,7 @@ import io.personium.test.utils.ResourceUtils; /** - * トークンのテスト. + * Access Token Acceptance test. */ @RunWith(PersoniumIntegTestRunner.class) @Category({Unit.class, Integration.class, Regression.class }) @@ -62,7 +62,7 @@ public class TokenTest extends PersoniumTest { static final int MILLISECS_IN_AN_MINITE = 60 * 1000; /** - * コンストラクタ. + * Constructor. */ public TokenTest() { super(new PersoniumCoreApplication()); From 1b7edbbb5955efc76fffed465581300b9c183e4e Mon Sep 17 00:00:00 2001 From: "Tochiori, Yasufumi" Date: Sun, 11 Aug 2019 00:30:23 +0900 Subject: [PATCH 29/69] For v1.7.18 --- pom.xml | 2 +- src/main/resources/personium-unit-config-default.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 90dad118f..d0807de3c 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-SNAPSHOT personium-core Maven Webapp http://maven.apache.org diff --git a/src/main/resources/personium-unit-config-default.properties b/src/main/resources/personium-unit-config-default.properties index 970c9034a..0635d956b 100644 --- a/src/main/resources/personium-unit-config-default.properties +++ b/src/main/resources/personium-unit-config-default.properties @@ -23,7 +23,7 @@ ################################################# # 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 From 484a18be96eac9b88205294273cfee57f10612d2 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 11 Aug 2019 13:37:11 +0900 Subject: [PATCH 30/69] Creating tests --- .../test/jersey/cell/auth/AuthTest.java | 9 +- .../cell/auth/token/TokenAcceptanceTest.java | 190 ++++++++++++++++++ 2 files changed, 194 insertions(+), 5 deletions(-) create mode 100644 src/test/java/io/personium/test/jersey/cell/auth/token/TokenAcceptanceTest.java 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 7bc674bf1..1d69fda31 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 @@ -1410,12 +1410,11 @@ private TResponse resetAcl(String cellName, String boxName, String token, String } /** - * 17.スキーマ付き自セルリフレッシュートランスセルトークン. */ @Test public void スキーマ付き自セルリフレッシュートランスセルトークン() { try { - // Authenticate to user cell + // Authenticate at TEST_CELL1 without app auth TResponse res = Http.request("authn/password-cl-c0.txt") .with("remoteCell", TEST_CELL1) @@ -1434,7 +1433,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String fail(); } - // Authenticate to app cell + // App Auth Token for TEST_CELL1 TResponse res2 = Http.request("authn/password-tc-c0.txt") .with("remoteCell", TEST_APP_CELL1) @@ -1447,7 +1446,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String 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) @@ -1470,7 +1469,7 @@ 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( UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); 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..e5fd08a6e --- /dev/null +++ b/src/test/java/io/personium/test/jersey/cell/auth/token/TokenAcceptanceTest.java @@ -0,0 +1,190 @@ +/** + * 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.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.CellLocalRefreshToken; +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_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 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 + CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl); + + // Generate AppAuth Token + List roleList = new ArrayList(); + TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl, appCellUrl + "#account1", usrCellUrl, roleList ,null); + + // Refresh Token + JsonObject res = this.refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl, appCellUrl, appAuthToken.toTokenString()); + log.info(res.toString()); + + // Should be error + + } + + + /** + * 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 + CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl); + + // Generate AppAuth Token + List roleList = new ArrayList(); + TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl, appCellUrl + "#account1", usrCellUrl, roleList ,null); + + // Refresh Token + JsonObject res = this.refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl, appCellUrl, appAuthToken.toTokenString()); + String at = res.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 JsonObject refreshToken(String cellUrl, String refreshToken, String pTarget) + throws ClientProtocolException, IOException { + return refreshToken(cellUrl, refreshToken, pTarget, null, null); + } + + private JsonObject 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); + HttpResponse res = client.execute(post); + + try (InputStream is = res.getEntity().getContent()){ + return Json.createReader(is).readObject(); + } + } + + + +} + From fd442946265ada5f200e06790f0df4b131636263 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 11 Aug 2019 15:56:41 +0900 Subject: [PATCH 31/69] fix #463 --- .../core/PersoniumCoreAuthnException.java | 15 +- .../core/rs/cell/TokenEndPointResource.java | 54 ++++--- .../resources/personium-messages.properties | 3 + .../cell/auth/token/TokenAcceptanceTest.java | 137 +++++++++++++++--- 4 files changed, 166 insertions(+), 43 deletions(-) diff --git a/src/main/java/io/personium/core/PersoniumCoreAuthnException.java b/src/main/java/io/personium/core/PersoniumCoreAuthnException.java index 9ee17607b..cdc225fa4 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 { @@ -135,6 +132,18 @@ public final class PersoniumCoreAuthnException extends PersoniumCoreException { public static final PersoniumCoreAuthnException PASSWORD_CHANGE_REQUIRED = create("PR401-AN-0001", Error.UNAUTHORIZED_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); + + /** * NetWork related error. */ 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 08841c527..79ba813ac 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -22,6 +22,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.UUID; import javax.ws.rs.HeaderParam; @@ -633,6 +634,15 @@ 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(); @@ -655,30 +665,32 @@ private Response receiveRefresh(final String target, String owner, String schema 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 CellLocalRefreshToken) { + String subject = rToken.getSubject(); + List roleList = cell.getRoleListForAccount(subject); + aToken = rToken.refreshAccessToken(issuedAt, expiresIn, target, getIssuerUrl(), roleList, schema); } 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, schema); + } - 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, diff --git a/src/main/resources/personium-messages.properties b/src/main/resources/personium-messages.properties index 5a3ac3849..f42ec28e2 100644 --- a/src/main/resources/personium-messages.properties +++ b/src/main/resources/personium-messages.properties @@ -228,6 +228,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.PR401-AN-0001=The password should be changed. 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 index e5fd08a6e..5b6f57d31 100644 --- 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 @@ -16,6 +16,7 @@ */ 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; @@ -77,7 +78,7 @@ public TokenAcceptanceTest() { } /** - * Should_FailRefreshingToken_When_ClientIdNotMatchesSchemaInRefreshToken. + * Should_FailRefreshingToken_When_NewClientSpecifiedForTokenWithoutSchema. * @throws IOException * @throws ClientProtocolException * @throws TokenRootCrtException @@ -85,26 +86,59 @@ public TokenAcceptanceTest() { * @throws TokenParseException */ @Test - public final void Should_FailRefreshingToken_When_ClientIdNotMatchesSchemaInRefreshToken() + 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 - CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl); + // Generate Refresh Token without schema (schema null) + CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", null); // Generate AppAuth Token List roleList = new ArrayList(); TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl, appCellUrl + "#account1", usrCellUrl, roleList ,null); // Refresh Token - JsonObject res = this.refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl, appCellUrl, appAuthToken.toTokenString()); - log.info(res.toString()); - + 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 + CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl2); + + // Generate AppAuth Token + List roleList = new ArrayList(); + TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl1, appCellUrl1 + "#account1", usrCellUrl, roleList ,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()); } @@ -132,8 +166,11 @@ public final void Should_SuccessRefrehingToken__When_ClientIdMatchesSchemaInRefr TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl, appCellUrl + "#account1", usrCellUrl, roleList ,null); // Refresh Token - JsonObject res = this.refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl, appCellUrl, appAuthToken.toTokenString()); - String at = res.getString(OAuth2Helper.Key.ACCESS_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); @@ -144,12 +181,81 @@ public final void Should_SuccessRefrehingToken__When_ClientIdMatchesSchemaInRefr assertTrue(aud.startsWith("http")); } - private JsonObject refreshToken(String cellUrl, String refreshToken, String pTarget) + /** + * 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 + CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl); + + // 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 + CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", null); + + // 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 JsonObject refreshToken(String cellUrl, String refreshToken, String pTarget, String clientId, String clientSecret) + private static HttpResponse refreshToken(String cellUrl, String refreshToken, String pTarget, String clientId, String clientSecret) throws ClientProtocolException, IOException { HttpClient client = HttpClientFactory.create(HttpClientFactory.TYPE_DEFAULT); @@ -177,14 +283,7 @@ private JsonObject refreshToken(String cellUrl, String refreshToken, String pTar 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(); - } + return client.execute(post); } - - - } From f2b31ab11061d8c91faa99f32be1358245e6fca6 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Mon, 12 Aug 2019 01:10:01 +0900 Subject: [PATCH 32/69] modify existig tests to fit with new spec --- .../rs/cell/TokenEndPointResourceTest.java | 2 + .../test/jersey/cell/auth/AuthTest.java | 342 +++++++++--------- 2 files changed, 182 insertions(+), 162 deletions(-) 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 087297cca..d779bee0c 100644 --- a/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java +++ b/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java @@ -100,6 +100,7 @@ public void receiveRefresh_Normal_cell_local_token() throws Exception { "parse", refreshToken, cellUrl, host).thenReturn(mockOldRToken); PowerMockito.doReturn(false).when(mockOldRToken).isRefreshExpired(); + PowerMockito.doReturn(schema).when(mockOldRToken).getSchema(); CellLocalRefreshToken mockNewRToken = PowerMockito.mock(CellLocalRefreshToken.class); doReturn(mockNewRToken).when(mockOldRToken).refreshRefreshToken(anyLong(), anyLong()); @@ -172,6 +173,7 @@ public void receiveRefresh_Normal_trans_cell_access_token() throws Exception { "parse", refreshToken, cellUrl, host).thenReturn(mockOldRToken); PowerMockito.doReturn(false).when(mockOldRToken).isRefreshExpired(); + PowerMockito.doReturn(schema).when(mockOldRToken).getSchema(); TransCellRefreshToken mockNewRToken = PowerMockito.mock(TransCellRefreshToken.class); doReturn(mockNewRToken).when(mockOldRToken).refreshRefreshToken(anyLong(), anyLong()); 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 1d69fda31..67a73c53a 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,7 +37,6 @@ 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.Role; @@ -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") @@ -265,7 +264,7 @@ public AuthTest() { * 1.スキーマ付きーパスワード認証ートランセルトークン取得. */ @Test - public final void スキーマ付きーパスワード認証ートランセルトークン取得() { + public final void C01_スキーマ付きーパスワード認証ートランセルトークン取得() { // アプリセルに対して認証 TResponse res = Http.request("authn/password-tc-c0.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) @@ -665,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トークン セルローカルでアクセス @@ -685,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) @@ -712,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) @@ -764,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) @@ -819,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トークンでデータアクセス @@ -838,7 +837,7 @@ 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); @@ -881,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 // パスワード認証 リフレッシュ セルローカルでデータアクセス @@ -901,7 +900,7 @@ 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); @@ -944,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) @@ -958,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") @@ -979,11 +978,13 @@ 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); @@ -1008,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 = @@ -1046,9 +1047,11 @@ 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); @@ -1072,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 リフレッシュ セルローカルでデータアクセス @@ -1105,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) @@ -1172,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トークン リフレッシュ セルローカルでデータアクセス @@ -1196,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) @@ -1255,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) @@ -1270,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) @@ -1283,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) @@ -1305,10 +1308,12 @@ 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); @@ -1334,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) @@ -1349,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) @@ -1362,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) @@ -1384,9 +1389,11 @@ 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); @@ -1412,14 +1419,28 @@ private TResponse resetAcl(String cellName, String boxName, String token, String /** */ @Test - public void スキーマ付き自セルリフレッシュートランスセルトークン() { + public void C17_スキーマ付き自セルリフレッシュートランスセルトークン() { try { - // Authenticate at TEST_CELL1 without app auth + // 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,17 +1454,6 @@ private TResponse resetAcl(String cellName, String boxName, String token, String fail(); } - // 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); // ------------------------------ // refresh at TEST_CELL1 adding app auth (body) @@ -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 = PersoniumCoreUtils.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,7 +1669,7 @@ 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( UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); @@ -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) @@ -1756,7 +1774,7 @@ 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( UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); From 212c91188630f7147a949c78966cf61f70e627ce Mon Sep 17 00:00:00 2001 From: akioshimono Date: Mon, 12 Aug 2019 10:37:46 +0900 Subject: [PATCH 33/69] modify existig tests to fit with new spec --- .../test/jersey/cell/auth/SchemaAuthTest.java | 228 ++++++++---------- .../personium/test/utils/ResourceUtils.java | 15 -- 2 files changed, 107 insertions(+), 136 deletions(-) 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 6917fea59..f45c0eef1 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 @@ -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); @@ -100,7 +101,7 @@ public SchemaAuthTest() { // 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"); @@ -321,7 +322,7 @@ private void setAclSchema(String box, String path, String roleBaseUrl, String le // 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)); diff --git a/src/test/java/io/personium/test/utils/ResourceUtils.java b/src/test/java/io/personium/test/utils/ResourceUtils.java index 757db4ef1..47c153dd7 100644 --- a/src/test/java/io/personium/test/utils/ResourceUtils.java +++ b/src/test/java/io/personium/test/utils/ResourceUtils.java @@ -22,7 +22,6 @@ import javax.ws.rs.core.MediaType; -import org.apache.http.HttpStatus; import org.json.simple.JSONObject; import io.personium.common.utils.PersoniumCoreUtils; @@ -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). From 23f6702f25d73f87f318ed40e1b5242b5efa937d Mon Sep 17 00:00:00 2001 From: akioshimono Date: Wed, 14 Aug 2019 22:19:17 +0900 Subject: [PATCH 34/69] Change the common-lib version to 1.5.0 --- pom.xml | 4 +-- .../io/personium/core/auth/AccessContext.java | 34 ++++++------------ .../core/model/impl/es/CellEsImpl.java | 2 +- .../core/rs/PersoniumCoreApplication.java | 4 +-- .../core/rs/cell/AuthzEndPointResource.java | 30 +++++++--------- .../cell/IntrospectionEndPointResource.java | 4 +-- .../core/rs/cell/TokenEndPointResource.java | 31 ++++++++-------- .../core/rule/action/TokenBuilder.java | 12 ++++++- .../core/auth/AccessContextTest.java | 35 +++++++------------ .../rs/cell/TokenEndPointResourceTest.java | 12 +++---- .../test/jersey/cell/auth/AuthTest.java | 18 +++++----- .../cell/auth/token/TokenAcceptanceTest.java | 10 +++--- .../jersey/cell/auth/token/TokenTest.java | 16 +++++---- 13 files changed, 97 insertions(+), 115 deletions(-) diff --git a/pom.xml b/pom.xml index d0807de3c..bf571031c 100644 --- a/pom.xml +++ b/pom.xml @@ -28,11 +28,11 @@ 1.1.1 - + io.personium personium-lib-common - 1.4.20 + 1.5.0-SNAPSHOT io.personium diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index b799d0251..bbe928490 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -27,6 +27,7 @@ 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; @@ -34,12 +35,11 @@ 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.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.auth.token.VisitorRefreshToken; import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreAuthzException; import io.personium.core.PersoniumCoreException; @@ -184,31 +184,17 @@ 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); } @@ -736,7 +722,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); } 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 04eea6f4b..2a0ab5558 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 @@ -761,7 +761,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("#")) { diff --git a/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java b/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java index 899b3662c..46727b8f6 100644 --- a/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java +++ b/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java @@ -21,7 +21,7 @@ import javax.ws.rs.core.Application; -import io.personium.common.auth.token.LocalToken; +import io.personium.common.auth.token.AbstractLocalToken; import io.personium.common.auth.token.TransCellAccessToken; import io.personium.common.utils.PersoniumThread; import io.personium.core.PersoniumCoreLog; @@ -47,7 +47,7 @@ public static void start() { try { TransCellAccessToken.configureX509(PersoniumUnitConfig.getX509PrivateKey(), PersoniumUnitConfig.getX509Certificate(), PersoniumUnitConfig.getX509RootCertificate()); - LocalToken.setKeyString(PersoniumUnitConfig.getTokenSecretKey()); + AbstractLocalToken.setKeyString(PersoniumUnitConfig.getTokenSecretKey()); DataCryptor.setKeyString(PersoniumUnitConfig.getTokenSecretKey()); PersoniumThread.start(PersoniumUnitConfig.getThreadPoolNumForCellIO(), PersoniumUnitConfig.getThreadPoolNumForBoxIO(), 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 9daca390e..7dfb40e75 100644 --- a/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java @@ -57,18 +57,17 @@ 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.Role; -import io.personium.common.auth.token.UnitLocalUnitUserToken; import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; @@ -566,15 +565,15 @@ private Response handlePassword(String responseType, String clientId, String red //Returning cell local token if (OAuth2Helper.ResponseType.TOKEN.equals(responseType)) { AccountAccessToken aToken = new AccountAccessToken(issuedAt, expiresIn, - getIssuerUrl(), username, schema); + getIssuerUrl(), username, schema, "ROPC"); 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(); @@ -634,13 +633,10 @@ private Response handlePCookie(boolean isPost, String responseType, String clien //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()); @@ -684,15 +680,15 @@ private Response handlePCookie(boolean isPost, String responseType, String clien if (OAuth2Helper.ResponseType.TOKEN.equals(responseType)) { AccountAccessToken aToken = new AccountAccessToken(issuedAt, expiresIn, - getIssuerUrl(), username, clientId); + getIssuerUrl(), username, clientId, "ROPC"); 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(); 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..709e79d21 100644 --- a/src/main/java/io/personium/core/rs/cell/IntrospectionEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/IntrospectionEndPointResource.java @@ -39,7 +39,7 @@ import io.personium.common.auth.token.CellLocalRefreshToken; import io.personium.common.auth.token.IAccessToken; import io.personium.common.auth.token.TransCellAccessToken; -import io.personium.common.auth.token.TransCellRefreshToken; +import io.personium.common.auth.token.VisitorRefreshToken; import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreAuthzException; import io.personium.core.PersoniumCoreException; @@ -159,7 +159,7 @@ public final Response introspect(@Context final UriInfo uriInfo, tk.getRoles().stream().map(role -> role.createUrl()).collect(Collectors.toList())); } } else if (tk instanceof CellLocalAccessToken - || tk instanceof TransCellRefreshToken + || tk instanceof VisitorRefreshToken || tk instanceof TransCellAccessToken) { IAccessToken iat = (IAccessToken) tk; String audience = iat.getTarget(); 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 79ba813ac..91dac1c0c 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -52,16 +52,16 @@ 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.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.auth.token.VisitorRefreshToken; import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreAuthnException; import io.personium.core.PersoniumCoreException; @@ -314,7 +314,7 @@ private Response callAuthPlugins(String grantType, MultivaluedMap roleList = cell.getRoleListForAccount(subject); - aToken = rToken.refreshAccessToken(issuedAt, expiresIn, target, getIssuerUrl(), roleList, schema); + aToken = rToken.refreshAccessToken(issuedAt, expiresIn, target, getIssuerUrl(), roleList); } 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); + getIssuerUrl(), rolesHere); } if (aToken instanceof TransCellAccessToken) { @@ -719,14 +719,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(); @@ -880,7 +877,7 @@ private Response handlePassword(final String target, final String owner, } } - return issueToken(target, owner, schema, username, expiresIn, rTokenExpiresIn); + return issueToken(target, owner, schema, username, expiresIn, rTokenExpiresIn, "ROPC"); } /** @@ -910,7 +907,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 scope) { long issuedAt = new Date().getTime(); if (Key.TRUE_STR.equals(owner)) { @@ -931,12 +928,12 @@ private Response issueToken(final String target, final String owner, } CellLocalRefreshToken rToken = new CellLocalRefreshToken(issuedAt, rTokenExpiresIn, - getIssuerUrl(), username, schema); + getIssuerUrl(), username, schema, scope); //Create a response. if (target == null) { AccountAccessToken localToken = new AccountAccessToken(issuedAt, expiresIn, - getIssuerUrl(), username, schema); + getIssuerUrl(), username, schema, scope); return this.responseAuthSuccess(localToken, rToken, issuedAt); } else { //Check that TODO SCHEMA is URL 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..0a1f3afab 100644 --- a/src/main/java/io/personium/core/rule/action/TokenBuilder.java +++ b/src/main/java/io/personium/core/rule/action/TokenBuilder.java @@ -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. @@ -119,7 +129,7 @@ public Optional build() { new AccountAccessToken(new Date().getTime(), cellUrl, subject, - schema); + schema, scope); accessToken = token.toTokenString(); } else { // CellLocalAccessToken diff --git a/src/test/java/io/personium/core/auth/AccessContextTest.java b/src/test/java/io/personium/core/auth/AccessContextTest.java index ee88f35df..77f574d72 100644 --- a/src/test/java/io/personium/core/auth/AccessContextTest.java +++ b/src/test/java/io/personium/core/auth/AccessContextTest.java @@ -40,7 +40,6 @@ 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.core.PersoniumUnitConfig; @@ -252,13 +251,11 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { System.currentTimeMillis(), UnitLocalUnitUserToken.ACCESS_TOKEN_EXPIRES_HOUR * MILLISECS_IN_AN_HOUR, 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, @@ -284,13 +281,11 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { UrlUtils.getBaseUrl() + "/cellowner", cell.getOwnerNormalized(), null, UrlUtils.getBaseUrl() + "/cellowner"); - 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, @@ -314,19 +309,17 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { System.currentTimeMillis(), UnitLocalUnitUserToken.ACCESS_TOKEN_EXPIRES_HOUR * MILLISECS_IN_AN_HOUR, 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()); // 第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()); } @@ -348,18 +341,16 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { System.currentTimeMillis(), UnitLocalUnitUserToken.ACCESS_TOKEN_EXPIRES_HOUR * MILLISECS_IN_AN_HOUR, 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/rs/cell/TokenEndPointResourceTest.java b/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java index d779bee0c..879910900 100644 --- a/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java +++ b/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java @@ -44,7 +44,7 @@ import io.personium.common.auth.token.CellLocalAccessToken; import io.personium.common.auth.token.CellLocalRefreshToken; import io.personium.common.auth.token.Role; -import io.personium.common.auth.token.TransCellRefreshToken; +import io.personium.common.auth.token.VisitorRefreshToken; import io.personium.core.model.Cell; import io.personium.test.categories.Unit; @@ -52,7 +52,7 @@ * TokenEndPointResource unit test classs. */ @RunWith(PowerMockRunner.class) -@PrepareForTest({ TokenEndPointResource.class, CellLocalRefreshToken.class, TransCellRefreshToken.class, +@PrepareForTest({ TokenEndPointResource.class, CellLocalRefreshToken.class, VisitorRefreshToken.class, AbstractOAuth2Token.class }) @Category({ Unit.class }) public class TokenEndPointResourceTest { @@ -112,7 +112,7 @@ public void receiveRefresh_Normal_cell_local_token() throws Exception { CellLocalAccessToken mockNewAToken = mock(CellLocalAccessToken.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", @@ -167,7 +167,7 @@ public void receiveRefresh_Normal_trans_cell_access_token() throws Exception { // -------------------- 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); @@ -175,7 +175,7 @@ public void receiveRefresh_Normal_trans_cell_access_token() throws Exception { 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(); @@ -183,7 +183,7 @@ public void receiveRefresh_Normal_trans_cell_access_token() throws Exception { CellLocalAccessToken mockNewAToken = mock(CellLocalAccessToken.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", 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 67a73c53a..1050db1b8 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 @@ -41,7 +41,7 @@ import io.personium.common.auth.token.CellLocalRefreshToken; 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.VisitorRefreshToken; import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.auth.OAuth2Helper; import io.personium.core.model.ctl.Relation; @@ -1134,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秒停止 @@ -1154,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)); // リフレッシュトークンが更新されている事をチェック @@ -1225,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 @@ -1237,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)); // リフレッシュトークンが更新されている事をチェック @@ -1296,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秒停止 @@ -1317,7 +1317,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .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)); // リフレッシュトークンが更新されている事をチェック @@ -1377,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秒停止 @@ -1397,7 +1397,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .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)); // リフレッシュトークンが更新されている事をチェック 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 index 5b6f57d31..3ffb926f2 100644 --- 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 @@ -94,7 +94,7 @@ public final void Should_FailRefreshingToken_When_NewClientSpecifiedForTokenWith String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token without schema (schema null) - CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", null); + CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", null, null); // Generate AppAuth Token List roleList = new ArrayList(); @@ -127,7 +127,7 @@ public final void Should_FailRefreshingToken_When_ClientIdNotMatchesSchemaInRefr String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token without schema - CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl2); + CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl2, "ROPC"); // Generate AppAuth Token List roleList = new ArrayList(); @@ -159,7 +159,7 @@ public final void Should_SuccessRefrehingToken__When_ClientIdMatchesSchemaInRefr String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token - CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl); + CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl, "ROPC"); // Generate AppAuth Token List roleList = new ArrayList(); @@ -198,7 +198,7 @@ public final void Should_FailRefrehingToken__When_RefreshTokenHasSchemaButNoAppA String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token - CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl); + CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl, "ROPC"); // Refresh Token HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), null); @@ -223,7 +223,7 @@ public final void Should_SuccessRefrehingToken__When_ClientIdNullAndRefreshToken String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token - CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", null); + CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", null, "ROPC"); // Refresh Token HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl); 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 684aefb76..19b518cb9 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 @@ -34,7 +34,7 @@ import io.personium.common.auth.token.PasswordChangeAccessToken; 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.VisitorRefreshToken; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.test.categories.Integration; import io.personium.test.categories.Regression; @@ -116,7 +116,7 @@ public TokenTest() { // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) CellLocalRefreshToken validToken = new CellLocalRefreshToken( issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 + MILLISECS_IN_AN_MINITE, - issuer, subject, schema); + issuer, subject, schema, "ROPC"); // アプリセルに対して認証 Http.request("authn/refresh-cl.txt") @@ -127,7 +127,8 @@ public TokenTest() { // 期限切れのトークンを生成する(IT環境の通信時間を考慮して1分余裕を持たせる) CellLocalRefreshToken invalidToken = new CellLocalRefreshToken( - issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 - MILLISECS_IN_AN_MINITE, issuer, subject, schema); + issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 - MILLISECS_IN_AN_MINITE, issuer, subject, + schema, "ROPC"); // アプリセルに対して認証 Http.request("authn/refresh-cl.txt") .with("remoteCell", TEST_CELL1) @@ -150,7 +151,7 @@ public TokenTest() { String schema = ""; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - TransCellRefreshToken validToken = new TransCellRefreshToken( + VisitorRefreshToken validToken = new VisitorRefreshToken( id, issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 + MILLISECS_IN_AN_MINITE, issuer, subject, origIssuer, origRoleList, schema); // Refresh @@ -161,7 +162,7 @@ public TokenTest() { .statusCode(HttpStatus.SC_OK); // 期限切れのトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - TransCellRefreshToken invalidToken = new TransCellRefreshToken( + VisitorRefreshToken invalidToken = new VisitorRefreshToken( id, issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 - MILLISECS_IN_AN_MINITE, issuer, subject, origIssuer, origRoleList, schema); // Refresh @@ -225,11 +226,12 @@ public TokenTest() { String issuer = UrlUtils.cellRoot(TEST_CELL1); String subject = "account2"; String schema = ""; + String scope = "ROPC"; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) AccountAccessToken validToken = new AccountAccessToken( 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); @@ -237,7 +239,7 @@ public TokenTest() { // 期限切れのトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) AccountAccessToken invalidToken = new AccountAccessToken( 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); From 5099d46737386bef09c88b49075204443d74b17b Mon Sep 17 00:00:00 2001 From: akioshimono Date: Thu, 15 Aug 2019 00:28:33 +0900 Subject: [PATCH 35/69] update CHANGELOG --- CHANGELOG.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57ad9fa0c..57286b508 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ +## 1.7.18 +IMPROVEMENTS: +* Limit Cell Level API Access to tokens issued via ROPC process. ([#445](https://github.com/personium/personium-core/issues/445)) +* URL scheme "personium-localunit" is extended and supports a syntax using two colons. ([#284](https://github.com/personium/personium-core/issues/284)) +* Token refreshing between apps 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 +15,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: From e88eac0515ca5d30ba1614d31deed5dbe133334e Mon Sep 17 00:00:00 2001 From: akioshimono Date: Thu, 15 Aug 2019 04:26:54 +0900 Subject: [PATCH 36/69] bug fix --- .../java/io/personium/core/rs/cell/TokenEndPointResource.java | 4 ++-- .../io/personium/test/jersey/cell/auth/AuthExpiresInTest.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) 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 91dac1c0c..549fb9955 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -455,9 +455,9 @@ private Response receiveCode(final String target, String owner, String schema, throw PersoniumCoreAuthnException.TOKEN_PARSE_ERROR.realm(this.cell.getUrl()); } - CellLocalAccessToken token; + GrantCode token; try { - token = (CellLocalAccessToken) AbstractOAuth2Token.parse(code, getIssuerUrl(), cell.getUnitUrl()); + token = (GrantCode) AbstractOAuth2Token.parse(code, getIssuerUrl(), cell.getUnitUrl()); } catch (TokenParseException e) { //Because I failed in Perth PersoniumCoreLog.Auth.TOKEN_PARSE_ERROR.params(e.getMessage()).writeLog(); 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"; From 2057477fc73def59f06fd26c6f1b8fe8a7db887b Mon Sep 17 00:00:00 2001 From: akioshimono Date: Fri, 16 Aug 2019 13:58:26 +0900 Subject: [PATCH 37/69] change neccessary for upgrading common-lib to 1.5.0 --- .../io/personium/core/auth/AccessContext.java | 10 ++++---- .../core/rs/cell/AuthzEndPointResource.java | 10 ++++---- .../cell/IntrospectionEndPointResource.java | 12 ++++----- .../core/rs/cell/TokenEndPointResource.java | 25 ++++++++++--------- .../core/rule/action/TokenBuilder.java | 12 ++++----- .../core/auth/AccessContextTest.java | 4 +-- .../rs/cell/TokenEndPointResourceTest.java | 14 +++++------ .../test/jersey/cell/auth/AuthCheckTest.java | 6 ++--- .../test/jersey/cell/auth/AuthTest.java | 24 +++++++++--------- .../cell/auth/AuthzValidIntervalTest.java | 4 +-- .../jersey/cell/auth/ImplicitFlowTest.java | 6 ++--- .../test/jersey/cell/auth/MyPasswordTest.java | 4 +-- .../test/jersey/cell/auth/SchemaAuthTest.java | 18 ++++++------- .../cell/auth/token/TokenAcceptanceTest.java | 12 ++++----- .../cell/auth/token/TokenIssuanceTest.java | 4 +-- .../jersey/cell/auth/token/TokenTest.java | 20 +++++++-------- 16 files changed, 93 insertions(+), 92 deletions(-) diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index bbe928490..39842a915 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -32,8 +32,8 @@ 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.ResidentLocalAccessToken; +import io.personium.common.auth.token.VisitorLocalAccessToken; import io.personium.common.auth.token.IAccessToken; import io.personium.common.auth.token.PasswordChangeAccessToken; import io.personium.common.auth.token.Role; @@ -733,7 +733,7 @@ private static AccessContext createBearerAuthz(String authzHeaderValue, Cell cel } AccessContext ret = new AccessContext(null, cell, baseUri, uriInfo); - if (tk instanceof AccountAccessToken) { + if (tk instanceof ResidentLocalAccessToken) { ret.accessType = TYPE_ACCOUNT; //Retrieve role information. String acct = tk.getSubject(); @@ -749,8 +749,8 @@ 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; + } else if (tk instanceof VisitorLocalAccessToken) { + VisitorLocalAccessToken clat = (VisitorLocalAccessToken) tk; ret.accessType = TYPE_LOCAL; //Acquire roll information and pack it. ret.roles = clat.getRoles(); 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 7dfb40e75..3d097fa95 100644 --- a/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java @@ -62,11 +62,11 @@ 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.GrantCode; import io.personium.common.auth.token.IAccessToken; import io.personium.common.auth.token.IdToken; 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.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreException; @@ -564,8 +564,8 @@ 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, "ROPC"); + 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())); @@ -679,8 +679,8 @@ 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, "ROPC"); + 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())); 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 709e79d21..0903ddea6 100644 --- a/src/main/java/io/personium/core/rs/cell/IntrospectionEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/IntrospectionEndPointResource.java @@ -34,9 +34,9 @@ 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.ResidentLocalAccessToken; +import io.personium.common.auth.token.VisitorLocalAccessToken; +import io.personium.common.auth.token.ResidentRefreshToken; import io.personium.common.auth.token.IAccessToken; import io.personium.common.auth.token.TransCellAccessToken; import io.personium.common.auth.token.VisitorRefreshToken; @@ -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,7 +158,7 @@ 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 + } else if (tk instanceof VisitorLocalAccessToken || tk instanceof VisitorRefreshToken || tk instanceof TransCellAccessToken) { IAccessToken iat = (IAccessToken) tk; 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 549fb9955..0f80f056c 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -49,18 +49,18 @@ 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.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.UnitLocalUnitUserToken; +import io.personium.common.auth.token.VisitorLocalAccessToken; import io.personium.common.auth.token.VisitorRefreshToken; import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumCoreAuthnException; @@ -314,7 +314,8 @@ private Response callAuthPlugins(String grantType, MultivaluedMap roleList = cell.getRoleListForAccount(token.getSubject()); @@ -583,7 +584,7 @@ issuedAt, rTokenExpiresIn, getIssuerUrl(), tcToken.getSubject(), //The target can be freely decided. IAccessToken aToken = null; if (target == null) { - aToken = new CellLocalAccessToken(issuedAt, expiresIn, getIssuerUrl(), + aToken = new VisitorLocalAccessToken(issuedAt, expiresIn, getIssuerUrl(), tcToken.getSubject(), rolesHere, schemaVerified); } else { aToken = new TransCellAccessToken(issuedAt, expiresIn, getIssuerUrl(), @@ -648,7 +649,7 @@ private Response receiveRefresh(final String target, String owner, String schema 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 @@ -674,7 +675,7 @@ private Response receiveRefresh(final String target, String owner, String schema rToken = rToken.refreshRefreshToken(issuedAt, rTokenExpiresIn); IAccessToken aToken = null; - if (rToken instanceof CellLocalRefreshToken) { + if (rToken instanceof ResidentRefreshToken) { String subject = rToken.getSubject(); List roleList = cell.getRoleListForAccount(subject); aToken = rToken.refreshAccessToken(issuedAt, expiresIn, target, getIssuerUrl(), roleList); @@ -877,7 +878,7 @@ private Response handlePassword(final String target, final String owner, } } - return issueToken(target, owner, schema, username, expiresIn, rTokenExpiresIn, "ROPC"); + return issueToken(target, owner, schema, username, expiresIn, rTokenExpiresIn, AbstractOAuth2Token.Scope.ROPC); } /** @@ -927,12 +928,12 @@ private Response issueToken(final String target, final String owner, return this.responseAuthSuccess(uluut, null, issuedAt); } - CellLocalRefreshToken rToken = new CellLocalRefreshToken(issuedAt, rTokenExpiresIn, + ResidentRefreshToken rToken = new ResidentRefreshToken(issuedAt, rTokenExpiresIn, getIssuerUrl(), username, schema, scope); //Create a response. if (target == null) { - AccountAccessToken localToken = new AccountAccessToken(issuedAt, expiresIn, + ResidentLocalAccessToken localToken = new ResidentLocalAccessToken(issuedAt, expiresIn, getIssuerUrl(), username, schema, scope); return this.responseAuthSuccess(localToken, rToken, issuedAt); } else { 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 0a1f3afab..3065da87a 100644 --- a/src/main/java/io/personium/core/rule/action/TokenBuilder.java +++ b/src/main/java/io/personium/core/rule/action/TokenBuilder.java @@ -22,8 +22,8 @@ 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.VisitorLocalAccessToken; import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; @@ -125,16 +125,16 @@ public Optional build() { subject = null; } // AccountAccessToken - AccountAccessToken token = - new AccountAccessToken(new Date().getTime(), + ResidentLocalAccessToken token = + new ResidentLocalAccessToken(new Date().getTime(), cellUrl, subject, schema, scope); accessToken = token.toTokenString(); } else { // CellLocalAccessToken - CellLocalAccessToken token = - new CellLocalAccessToken(new Date().getTime(), + VisitorLocalAccessToken token = + new VisitorLocalAccessToken(new Date().getTime(), cellUrl, subject, roleList, diff --git a/src/test/java/io/personium/core/auth/AccessContextTest.java b/src/test/java/io/personium/core/auth/AccessContextTest.java index 77f574d72..81a9b7f0b 100644 --- a/src/test/java/io/personium/core/auth/AccessContextTest.java +++ b/src/test/java/io/personium/core/auth/AccessContextTest.java @@ -39,7 +39,7 @@ import org.junit.runner.RunWith; import org.mockito.Matchers; -import io.personium.common.auth.token.CellLocalAccessToken; +import io.personium.common.auth.token.VisitorLocalAccessToken; import io.personium.common.auth.token.UnitLocalUnitUserToken; import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.PersoniumUnitConfig; @@ -277,7 +277,7 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { when(cell.getUnitUrl()).thenReturn(UrlUtils.getBaseUrl()); // Token発行処理 - CellLocalAccessToken token = new CellLocalAccessToken( + VisitorLocalAccessToken token = new VisitorLocalAccessToken( UrlUtils.getBaseUrl() + "/cellowner", cell.getOwnerNormalized(), null, UrlUtils.getBaseUrl() + "/cellowner"); 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 879910900..7bdfd5149 100644 --- a/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java +++ b/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java @@ -41,8 +41,8 @@ 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.VisitorLocalAccessToken; +import io.personium.common.auth.token.ResidentRefreshToken; import io.personium.common.auth.token.Role; import io.personium.common.auth.token.VisitorRefreshToken; import io.personium.core.model.Cell; @@ -52,7 +52,7 @@ * TokenEndPointResource unit test classs. */ @RunWith(PowerMockRunner.class) -@PrepareForTest({ TokenEndPointResource.class, CellLocalRefreshToken.class, VisitorRefreshToken.class, +@PrepareForTest({ TokenEndPointResource.class, ResidentRefreshToken.class, VisitorRefreshToken.class, AbstractOAuth2Token.class }) @Category({ Unit.class }) public class TokenEndPointResourceTest { @@ -94,7 +94,7 @@ public void receiveRefresh_Normal_cell_local_token() throws Exception { // -------------------- 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); @@ -102,7 +102,7 @@ public void receiveRefresh_Normal_cell_local_token() throws Exception { 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(); @@ -110,7 +110,7 @@ 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()); @@ -181,7 +181,7 @@ public void receiveRefresh_Normal_trans_cell_access_token() throws Exception { 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()); 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 4bee3dde6..11b4db5a8 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,7 +36,7 @@ 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; @@ -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/AuthTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthTest.java index 1050db1b8..4f05ffca4 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,8 +37,8 @@ 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.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.VisitorRefreshToken; @@ -842,7 +842,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String // セルに対してパスワード認証 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)); // リフレッシュトークンが更新されている事をチェック @@ -905,7 +905,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String // セルに対してパスワード認証 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)); // リフレッシュトークンが更新されている事をチェック @@ -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秒停止 @@ -989,7 +989,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .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)); // リフレッシュトークンが更新されている事をチェック @@ -1035,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秒停止 @@ -1055,7 +1055,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String .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)); // リフレッシュトークンが更新されている事をチェック @@ -1763,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 @@ -1787,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/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..61f7a1020 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 @@ -32,7 +32,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.common.auth.token.PasswordChangeAccessToken; import io.personium.common.utils.PersoniumCoreUtils; import io.personium.core.auth.OAuth2Helper; @@ -134,7 +134,7 @@ 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)); } finally { AccountUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN, account, -1); } 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 f45c0eef1..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; @@ -92,10 +92,10 @@ 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のスキーマアクセス制御確認 @@ -316,7 +316,7 @@ 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のスキーマアクセス制御確認 @@ -800,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; @@ -866,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/token/TokenAcceptanceTest.java b/src/test/java/io/personium/test/jersey/cell/auth/token/TokenAcceptanceTest.java index 3ffb926f2..f6d12514f 100644 --- 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 @@ -45,7 +45,7 @@ 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.CellLocalRefreshToken; +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; @@ -94,7 +94,7 @@ public final void Should_FailRefreshingToken_When_NewClientSpecifiedForTokenWith String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token without schema (schema null) - CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", null, null); + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", null, null); // Generate AppAuth Token List roleList = new ArrayList(); @@ -127,7 +127,7 @@ public final void Should_FailRefreshingToken_When_ClientIdNotMatchesSchemaInRefr String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token without schema - CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl2, "ROPC"); + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl2, "ROPC"); // Generate AppAuth Token List roleList = new ArrayList(); @@ -159,7 +159,7 @@ public final void Should_SuccessRefrehingToken__When_ClientIdMatchesSchemaInRefr String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token - CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl, "ROPC"); + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl, "ROPC"); // Generate AppAuth Token List roleList = new ArrayList(); @@ -198,7 +198,7 @@ public final void Should_FailRefrehingToken__When_RefreshTokenHasSchemaButNoAppA String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token - CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", appCellUrl, "ROPC"); + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl, "ROPC"); // Refresh Token HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), null); @@ -223,7 +223,7 @@ public final void Should_SuccessRefrehingToken__When_ClientIdNullAndRefreshToken String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token - CellLocalRefreshToken clrt = new CellLocalRefreshToken(usrCellUrl, "account1", null, "ROPC"); + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", null, "ROPC"); // Refresh Token HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl); 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 index 8eefae969..c836124aa 100644 --- 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 @@ -42,7 +42,7 @@ 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.ResidentLocalAccessToken; import io.personium.common.auth.token.TransCellAccessToken; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.core.utils.HttpClientFactory; @@ -114,7 +114,7 @@ public final void When_ClientIdLocalunitSchemeURL_Then_StillTheAppAuthShouldWork String at = this.callROPC(usrCellUrl, "account1", "password1", null, appCellLocalUnit, clientSecret).getString("access_token"); log.info("token:" + at); - AccountAccessToken aat = AccountAccessToken.parse(at, usrCellUrl); + ResidentLocalAccessToken aat = ResidentLocalAccessToken.parse(at, usrCellUrl); String schema = aat.getSchema(); log.info(schema); 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 19b518cb9..a18bb3b1d 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,12 +28,12 @@ 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.VisitorLocalAccessToken; import io.personium.common.auth.token.VisitorRefreshToken; import io.personium.core.rs.PersoniumCoreApplication; import io.personium.test.categories.Integration; @@ -114,7 +114,7 @@ public TokenTest() { String schema = ""; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - CellLocalRefreshToken validToken = new CellLocalRefreshToken( + ResidentRefreshToken validToken = new ResidentRefreshToken( issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 + MILLISECS_IN_AN_MINITE, issuer, subject, schema, "ROPC"); @@ -126,7 +126,7 @@ public TokenTest() { .statusCode(HttpStatus.SC_OK); // 期限切れのトークンを生成する(IT環境の通信時間を考慮して1分余裕を持たせる) - CellLocalRefreshToken invalidToken = new CellLocalRefreshToken( + ResidentRefreshToken invalidToken = new ResidentRefreshToken( issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 - MILLISECS_IN_AN_MINITE, issuer, subject, schema, "ROPC"); // アプリセルに対して認証 @@ -226,10 +226,10 @@ public TokenTest() { String issuer = UrlUtils.cellRoot(TEST_CELL1); String subject = "account2"; String schema = ""; - String scope = "ROPC"; + String scope = AbstractOAuth2Token.Scope.ROPC; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - AccountAccessToken validToken = new AccountAccessToken( + ResidentLocalAccessToken validToken = new ResidentLocalAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR + MILLISECS_IN_AN_MINITE, issuer, subject, schema, scope); // データアクセス @@ -237,7 +237,7 @@ public TokenTest() { 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, scope); // データアクセス @@ -260,7 +260,7 @@ public TokenTest() { String schema = ""; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) - CellLocalAccessToken validToken = new CellLocalAccessToken( + VisitorLocalAccessToken validToken = new VisitorLocalAccessToken( issuedAt - AbstractOAuth2Token.MILLISECS_IN_AN_HOUR + MILLISECS_IN_AN_MINITE, issuer, subject, roleList, schema); // データアクセス @@ -268,7 +268,7 @@ public TokenTest() { 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); // データアクセス From 54ec6ef11bf3fc445b987d7ac88fcff70722879c Mon Sep 17 00:00:00 2001 From: akioshimono Date: Fri, 16 Aug 2019 16:01:13 +0900 Subject: [PATCH 38/69] Fix for #156 --- .../core/PersoniumReadDeleteModeManager.java | 2 +- .../personium/core/PersoniumUnitConfig.java | 4 +- .../io/personium/core/auth/AccessContext.java | 4 +- .../io/personium/core/auth/OAuth2Helper.java | 6 +- .../auth/hash/Sha256HashPasswordImpl.java | 4 +- .../java/io/personium/core/bar/BarFile.java | 4 +- .../bar/BarFileContentsInstallVisitor.java | 6 +- .../core/bar/BarFileInstallRunner.java | 10 ++-- .../personium/core/bar/BarFileReadRunner.java | 12 ++-- .../filter/PersoniumCoreContainerFilter.java | 26 ++++----- .../io/personium/core/model/DavRsCmp.java | 26 ++++----- .../io/personium/core/model/ctl/Common.java | 6 +- .../impl/es/odata/ODataProducerUtils.java | 4 +- .../core/model/impl/fs/DavCmpFsImpl.java | 8 +-- .../io/personium/core/model/jaxb/Acl.java | 4 +- .../io/personium/core/rs/FacadeResource.java | 12 ++-- .../io/personium/core/rs/box/BoxResource.java | 10 ++-- .../core/rs/box/DavCollectionResource.java | 18 +++--- .../core/rs/box/DavFileResource.java | 12 ++-- .../rs/box/ODataSvcCollectionResource.java | 16 ++--- .../box/PersoniumEngineSourceCollection.java | 6 +- .../PersoniumEngineSvcCollectionResource.java | 20 +++---- .../core/rs/box/StreamCollectionResource.java | 16 ++--- .../core/rs/box/StreamQueueResource.java | 6 +- .../core/rs/box/StreamTopicResource.java | 6 +- .../core/rs/cell/AuthzEndPointResource.java | 6 +- .../core/rs/cell/BoxUrlResource.java | 4 +- .../personium/core/rs/cell/CellResource.java | 14 ++--- .../rs/cell/CellSnapshotDavFileResource.java | 6 +- .../core/rs/cell/CellSnapshotResource.java | 6 +- .../core/rs/cell/ErrorHtmlResource.java | 4 +- .../cell/IntrospectionEndPointResource.java | 4 +- .../personium/core/rs/cell/LogResource.java | 4 +- .../core/rs/cell/MessageResource.java | 4 +- .../core/rs/cell/TokenEndPointResource.java | 4 +- .../core/rs/odata/ODataEntityResource.java | 4 +- .../core/rs/odata/ODataPropertyResource.java | 6 +- .../rs/odata/ODataSentMessageResource.java | 4 +- .../personium/core/rs/unit/UnitResource.java | 12 ++-- .../core/rule/action/HttpAction.java | 10 ++-- .../personium/core/utils/ResourceUtils.java | 2 +- .../io/personium/core/ws/StreamEndpoint.java | 14 ++--- .../PersoniumReadDeleteModeManagerTest.java | 20 +++---- .../core/PersoniumUnitConfigTest.java | 16 ++--- .../core/auth/AccessContextTest.java | 8 +-- .../core/model/impl/fs/DavCmpFsImplTest.java | 14 ++--- .../core/rs/box/BoxResourceTest.java | 8 +-- .../rs/box/DavCollectionResourceTest.java | 4 +- ...soniumEngineSvcCollectionResourceTest.java | 4 +- .../test/jersey/CrossDomainTest.java | 2 +- .../test/jersey/PersoniumRequest.java | 2 +- .../test/jersey/bar/BarInstallTest.java | 8 +-- .../test/jersey/box/CollectionTest.java | 8 +-- .../personium/test/jersey/box/Property.java | 4 +- .../test/jersey/box/dav/file/DavFileTest.java | 4 +- .../box/odatacol/AbstractUserDataTest.java | 4 +- .../personium/test/jersey/cell/AclTest.java | 30 +++++----- .../jersey/cell/CellBulkDeletionTest.java | 6 +- .../personium/test/jersey/cell/EventTest.java | 4 +- .../test/jersey/cell/LogListTest.java | 28 ++++----- .../personium/test/jersey/cell/LogTest.java | 4 +- .../test/jersey/cell/MessageApproveTest.java | 58 +++++++++---------- .../test/jersey/cell/auth/AuthCheckTest.java | 26 ++++----- .../test/jersey/cell/auth/AuthErrorTest.java | 8 +-- .../test/jersey/cell/auth/AuthTest.java | 26 ++++----- .../test/jersey/cell/auth/MyPasswordTest.java | 4 +- .../jersey/cell/ctl/AccountRoleLinkTest.java | 4 +- .../jersey/cell/ctl/BoxBulkDeletionTest.java | 6 +- .../test/jersey/cell/ctl/CellCtlUtils.java | 8 +-- .../jersey/cell/ctl/ExtCellDeleteTest.java | 10 ++-- .../test/jersey/cell/ctl/ExtCellListTest.java | 6 +- .../test/jersey/cell/ctl/ExtCellReadTest.java | 6 +- .../jersey/cell/ctl/ExtRoleDeleteTest.java | 10 ++-- .../test/jersey/cell/ctl/ExtRoleLinkTest.java | 8 +-- .../hashpassword/SCryptHashPasswordTest.java | 4 +- .../hashpassword/Sha256HashPasswordTest.java | 4 +- .../java/io/personium/test/setup/Setup.java | 10 ++-- .../PersoniumCoreContainerFilterTest.java | 12 ++-- .../io/personium/test/utils/AuthzUtils.java | 6 +- .../io/personium/test/utils/CellUtils.java | 6 +- .../io/personium/test/utils/ExtCellUtils.java | 14 ++--- .../io/personium/test/utils/ExtRoleUtils.java | 12 ++-- .../personium/test/utils/ResourceUtils.java | 8 +-- .../personium/test/utils/UserDataUtils.java | 6 +- 84 files changed, 398 insertions(+), 398 deletions(-) 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 604332eb6..35595ea1a 100644 --- a/src/main/java/io/personium/core/PersoniumUnitConfig.java +++ b/src/main/java/io/personium/core/PersoniumUnitConfig.java @@ -34,7 +34,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; @@ -871,7 +871,7 @@ public static String getPluginPath() { public static String getBaseUrl() { return UriBuilder.fromPath("/") .scheme(getUnitScheme()) - .host(PersoniumCoreUtils.getFQDN()) + .host(CommonUtils.getFQDN()) .port(getUnitPort()) .build() .toString(); diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index 39842a915..f027a6ff8 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -40,7 +40,7 @@ import io.personium.common.auth.token.TransCellAccessToken; import io.personium.common.auth.token.UnitLocalUnitUserToken; import io.personium.common.auth.token.VisitorRefreshToken; -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.PersoniumCoreLog; @@ -633,7 +633,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); } diff --git a/src/main/java/io/personium/core/auth/OAuth2Helper.java b/src/main/java/io/personium/core/auth/OAuth2Helper.java index ee0cfd01c..d7fe2bf35 100644 --- a/src/main/java/io/personium/core/auth/OAuth2Helper.java +++ b/src/main/java/io/personium/core/auth/OAuth2Helper.java @@ -18,7 +18,7 @@ import javax.xml.namespace.QName; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; /** * A utility around OAuth 2. @@ -323,12 +323,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"); } /** 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/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/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/DavRsCmp.java b/src/main/java/io/personium/core/model/DavRsCmp.java index ad6e0e70b..901897d8d 100644 --- a/src/main/java/io/personium/core/model/DavRsCmp.java +++ b/src/main/java/io/personium/core/model/DavRsCmp.java @@ -58,7 +58,7 @@ 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; @@ -421,10 +421,10 @@ public Response options() { 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(); } @@ -591,8 +591,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 +602,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 +613,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 +626,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/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/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/fs/DavCmpFsImpl.java b/src/main/java/io/personium/core/model/impl/fs/DavCmpFsImpl.java index 6862c9f73..9316bc31d 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,7 @@ 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.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; import io.personium.core.ElapsedTimeLog; @@ -424,7 +424,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 +738,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 +784,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); } 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 f268f93cd..80358ca90 100644 --- a/src/main/java/io/personium/core/model/jaxb/Acl.java +++ b/src/main/java/io/personium/core/model/jaxb/Acl.java @@ -36,7 +36,7 @@ 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; @@ -66,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.*/ diff --git a/src/main/java/io/personium/core/rs/FacadeResource.java b/src/main/java/io/personium/core/rs/FacadeResource.java index 33d80b8ae..d46b06129 100644 --- a/src/main/java/io/personium/core/rs/FacadeResource.java +++ b/src/main/java/io/personium/core/rs/FacadeResource.java @@ -28,7 +28,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.PersoniumCoreLog; import io.personium.core.PersoniumUnitConfig; @@ -76,11 +76,11 @@ public Object facade( @QueryParam(COOKIE_PEER_QUERY_KEY) final String cookiePeer, @HeaderParam(HttpHeaders.AUTHORIZATION) final String headerAuthz, @HeaderParam(HttpHeaders.HOST) final String headerHost, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_UNIT_USER) final String headerPersoniumUnitUser, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY) final String headerPersoniumRequestKey, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_EVENTID) final String headerPersoniumEventId, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RULECHAIN) final String headerPersoniumRuleChain, - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_VIA) final String headerPersoniumVia, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_UNIT_USER) final String headerPersoniumUnitUser, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY) final String headerPersoniumRequestKey, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_EVENTID) final String headerPersoniumEventId, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_RULECHAIN) final String headerPersoniumRuleChain, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_VIA) final String headerPersoniumVia, @Context final UriInfo uriInfo, @Context HttpServletRequest httpServletRequest) { diff --git a/src/main/java/io/personium/core/rs/box/BoxResource.java b/src/main/java/io/personium/core/rs/box/BoxResource.java index 9e31d6044..5748ca444 100644 --- a/src/main/java/io/personium/core/rs/box/BoxResource.java +++ b/src/main/java/io/personium/core/rs/box/BoxResource.java @@ -41,7 +41,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.annotations.ACL; import io.personium.core.annotations.MKCOL; @@ -269,11 +269,11 @@ private JSONObject createResponse(JSONObject values) { @WriteAPI @DELETE public Response recursiveDelete( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { // If the X-Personium-Recursive header is not true, it is an error if (!Boolean.TRUE.toString().equalsIgnoreCase(recursiveHeader)) { throw PersoniumCoreException.Misc.PRECONDITION_FAILED.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE); } boolean recursive = Boolean.valueOf(recursiveHeader); @@ -309,7 +309,7 @@ public Response recursiveDelete( */ @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) { // Access Control @@ -424,7 +424,7 @@ public Response acl(final Reader reader) { @WriteAPI @MKCOL public Response mkcol( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL) final String pCredHeader, + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL) final String pCredHeader, @HeaderParam(HttpHeaders.CONTENT_TYPE) final String contentType, @HeaderParam(HttpHeaders.CONTENT_LENGTH) final String contentLength, final InputStream inStream) { diff --git a/src/main/java/io/personium/core/rs/box/DavCollectionResource.java b/src/main/java/io/personium/core/rs/box/DavCollectionResource.java index 0bd3a150f..203b49580 100644 --- a/src/main/java/io/personium/core/rs/box/DavCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/DavCollectionResource.java @@ -32,7 +32,7 @@ import org.apache.http.HttpStatus; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.annotations.ACL; import io.personium.core.annotations.MKCOL; @@ -117,13 +117,13 @@ public Response proppatch(final Reader requestBodyXml) { @WriteAPI @DELETE public Response delete( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { // X-Personium-Recursive Header if (recursiveHeader != null && !Boolean.TRUE.toString().equalsIgnoreCase(recursiveHeader) && !Boolean.FALSE.toString().equalsIgnoreCase(recursiveHeader)) { throw PersoniumCoreException.Dav.INVALID_REQUEST_HEADER.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); } boolean recursive = Boolean.valueOf(recursiveHeader); // Check acl.(Parent acl check) @@ -161,7 +161,7 @@ public Response delete( */ @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) { // Access Control @@ -264,11 +264,11 @@ public Response options() { HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE, - 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.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(); } diff --git a/src/main/java/io/personium/core/rs/box/DavFileResource.java b/src/main/java/io/personium/core/rs/box/DavFileResource.java index f485253d8..96846b7bb 100644 --- a/src/main/java/io/personium/core/rs/box/DavFileResource.java +++ b/src/main/java/io/personium/core/rs/box/DavFileResource.java @@ -30,7 +30,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.ACL; import io.personium.core.annotations.MOVE; @@ -204,7 +204,7 @@ public Response proppatch(final Reader requestBodyXml) { */ @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) { // Access Control @@ -298,10 +298,10 @@ public Response options() { HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE, - 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.MOVE, + io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND, + io.personium.common.utils.CommonUtils.HttpMethod.PROPPATCH, + io.personium.common.utils.CommonUtils.HttpMethod.ACL ).build(); } } diff --git a/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java b/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java index 4203ff07a..9db203883 100644 --- a/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java @@ -27,7 +27,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.PersoniumCoreException; import io.personium.core.annotations.ACL; import io.personium.core.annotations.MOVE; @@ -80,7 +80,7 @@ public ODataSvcCollectionResource(final DavRsCmp parent, final DavCmp davCmp) { */ @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) { // Access Control @@ -184,13 +184,13 @@ public Response acl(final Reader reader) { @WriteAPI @DELETE public Response delete( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { // X-Personium-Recursive Header if (recursiveHeader != null && !Boolean.TRUE.toString().equalsIgnoreCase(recursiveHeader) && !Boolean.FALSE.toString().equalsIgnoreCase(recursiveHeader)) { throw PersoniumCoreException.Dav.INVALID_REQUEST_HEADER.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); } boolean recursive = Boolean.valueOf(recursiveHeader); // Check acl. @@ -232,10 +232,10 @@ public Response optionsRoot() { return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, HttpMethod.DELETE, - PersoniumCoreUtils.HttpMethod.MOVE, - PersoniumCoreUtils.HttpMethod.PROPFIND, - PersoniumCoreUtils.HttpMethod.PROPPATCH, - PersoniumCoreUtils.HttpMethod.ACL + CommonUtils.HttpMethod.MOVE, + CommonUtils.HttpMethod.PROPFIND, + CommonUtils.HttpMethod.PROPPATCH, + CommonUtils.HttpMethod.ACL ).build(); } diff --git a/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceCollection.java b/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceCollection.java index 83347a53c..190bbd6fb 100644 --- a/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceCollection.java +++ b/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceCollection.java @@ -27,7 +27,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.PersoniumCoreException; import io.personium.core.annotations.MOVE; import io.personium.core.annotations.PROPFIND; @@ -84,7 +84,7 @@ public Object nextPath(@PathParam("nextPath") final String nextPath, */ @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) { // Access Control @@ -123,7 +123,7 @@ public Response options() { //Access control to move source this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); 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/box/PersoniumEngineSvcCollectionResource.java b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java index 5b2b4effa..9c89f37bc 100644 --- a/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java @@ -59,7 +59,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.PersoniumCoreLog; import io.personium.core.ElapsedTimeLog; @@ -114,7 +114,7 @@ public PersoniumEngineSvcCollectionResource(final DavRsCmp parent, final DavCmp */ @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) { // Access Control @@ -159,13 +159,13 @@ public Response report() { @WriteAPI @DELETE public Response delete( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { // X-Personium-Recursive Header if (recursiveHeader != null && !Boolean.TRUE.toString().equalsIgnoreCase(recursiveHeader) && !Boolean.FALSE.toString().equalsIgnoreCase(recursiveHeader)) { throw PersoniumCoreException.Dav.INVALID_REQUEST_HEADER.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); } boolean recursive = Boolean.valueOf(recursiveHeader); // Check acl.(Parent acl check) @@ -262,10 +262,10 @@ public Response options() { this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); return ResourceUtils.responseBuilderForOptions( HttpMethod.DELETE, - 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.MOVE, + io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND, + io.personium.common.utils.CommonUtils.HttpMethod.PROPPATCH, + io.personium.common.utils.CommonUtils.HttpMethod.ACL ).build(); } @@ -478,10 +478,10 @@ private Response relaycommon( // CHECKSTYLE IGNORE - Necessary processing } // If RequestKey is not specified in the header, Take over the generated RequestKey. - if (!req.containsHeader(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY)) { + if (!req.containsHeader(CommonUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY)) { String requestKey = this.getRequestKey(this.davRsCmp); if (requestKey != null) { - req.addHeader(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY, requestKey); + req.addHeader(CommonUtils.HttpHeaders.X_PERSONIUM_REQUESTKEY, requestKey); } } diff --git a/src/main/java/io/personium/core/rs/box/StreamCollectionResource.java b/src/main/java/io/personium/core/rs/box/StreamCollectionResource.java index bb7c2a518..3797dc584 100644 --- a/src/main/java/io/personium/core/rs/box/StreamCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/StreamCollectionResource.java @@ -27,7 +27,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.PersoniumCoreException; import io.personium.core.annotations.ACL; import io.personium.core.annotations.MOVE; @@ -73,7 +73,7 @@ public StreamCollectionResource(final DavRsCmp parent, final DavCmp davCmp) { */ @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) { // Access Control @@ -118,13 +118,13 @@ public Response report() { @WriteAPI @DELETE public Response delete( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE) final String recursiveHeader) { // X-Personium-Recursive Header if (recursiveHeader != null && !Boolean.TRUE.toString().equalsIgnoreCase(recursiveHeader) && !Boolean.FALSE.toString().equalsIgnoreCase(recursiveHeader)) { throw PersoniumCoreException.Dav.INVALID_REQUEST_HEADER.params( - PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); + CommonUtils.HttpHeaders.X_PERSONIUM_RECURSIVE, recursiveHeader); } boolean recursive = Boolean.valueOf(recursiveHeader); // Check acl.(Parent acl check) @@ -235,10 +235,10 @@ public Response options() { this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); return ResourceUtils.responseBuilderForOptions( HttpMethod.DELETE, - 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.MOVE, + io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND, + io.personium.common.utils.CommonUtils.HttpMethod.PROPPATCH, + io.personium.common.utils.CommonUtils.HttpMethod.ACL ).build(); } diff --git a/src/main/java/io/personium/core/rs/box/StreamQueueResource.java b/src/main/java/io/personium/core/rs/box/StreamQueueResource.java index dbc07d366..2388b35e9 100644 --- a/src/main/java/io/personium/core/rs/box/StreamQueueResource.java +++ b/src/main/java/io/personium/core/rs/box/StreamQueueResource.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; @@ -64,7 +64,7 @@ protected List 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/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/AuthzEndPointResource.java b/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java index 3d097fa95..999d9946a 100644 --- a/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java @@ -68,7 +68,7 @@ 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.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; import io.personium.core.PersoniumCoreMessageUtils; @@ -1020,7 +1020,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; @@ -1092,7 +1092,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..51e2c2427 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; @@ -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/CellResource.java b/src/main/java/io/personium/core/rs/cell/CellResource.java index 530a68064..e2bbf58e2 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; @@ -216,11 +216,11 @@ 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 @@ -275,7 +275,7 @@ 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); } @@ -286,7 +286,7 @@ public CellCtlResource ctl( */ @Path("__mypassword") public PasswordResource mypassword( - @HeaderParam(PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL) final String pCredHeader) { + @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL) final String pCredHeader) { return new PasswordResource(this.accessContext, pCredHeader, this.cell, this.cellRsCmp); } @@ -460,7 +460,7 @@ 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 @@ -565,7 +565,7 @@ public Response options() { this.cellRsCmp.checkAccessContext(this.cellRsCmp.getAccessContext(), 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..60e494a44 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; @@ -126,7 +126,7 @@ 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 @@ -159,7 +159,7 @@ public Response options() { 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..ea1e7ff74 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,7 +75,7 @@ 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 @@ -93,7 +93,7 @@ public Response options() { // Access Control cellSnapshotCellRsCmp.checkAccessContext(cellSnapshotCellRsCmp.getAccessContext(), 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/IntrospectionEndPointResource.java b/src/main/java/io/personium/core/rs/cell/IntrospectionEndPointResource.java index 0903ddea6..02c36d2cd 100644 --- a/src/main/java/io/personium/core/rs/cell/IntrospectionEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/IntrospectionEndPointResource.java @@ -40,7 +40,7 @@ import io.personium.common.auth.token.IAccessToken; import io.personium.common.auth.token.TransCellAccessToken; import io.personium.common.auth.token.VisitorRefreshToken; -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; @@ -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(); 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 06233d875..d7119344d 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,7 +129,7 @@ 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 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..453beedde 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,7 +82,7 @@ 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 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 0f80f056c..34069ebb1 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -62,7 +62,7 @@ import io.personium.common.auth.token.UnitLocalUnitUserToken; import io.personium.common.auth.token.VisitorLocalAccessToken; import io.personium.common.auth.token.VisitorRefreshToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreAuthnException; import io.personium.core.PersoniumCoreException; import io.personium.core.PersoniumCoreLog; @@ -361,7 +361,7 @@ public static String clientAuth(final String clientId, final String clientSecret //Parsing authzHeader if (authzHeader != null) { - String[] idpw = PersoniumCoreUtils + String[] idpw = CommonUtils .parseBasicAuthzHeader(authzHeader); if (idpw != null) { //Specify authzHeader first 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..3a7254da8 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; @@ -501,7 +501,7 @@ public Response options() { 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/ODataPropertyResource.java b/src/main/java/io/personium/core/rs/odata/ODataPropertyResource.java index 9e11e2a13..aa260ce20 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataPropertyResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataPropertyResource.java @@ -52,7 +52,7 @@ 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; @@ -114,7 +114,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 +242,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) { 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..399a6f635 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; @@ -445,7 +445,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/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/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/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/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/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 423f07d80..7d14ea703 100644 --- a/src/test/java/io/personium/core/PersoniumUnitConfigTest.java +++ b/src/test/java/io/personium/core/PersoniumUnitConfigTest.java @@ -26,7 +26,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.test.categories.Unit; /** @@ -35,7 +35,7 @@ @Category({ Unit.class }) @RunWith(PowerMockRunner.class) -@PrepareForTest({ PersoniumCoreUtils.class, PersoniumUnitConfig.class }) +@PrepareForTest({ CommonUtils.class, PersoniumUnitConfig.class }) public class PersoniumUnitConfigTest { /** @@ -45,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(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 81a9b7f0b..1e8a36a2e 100644 --- a/src/test/java/io/personium/core/auth/AccessContextTest.java +++ b/src/test/java/io/personium/core/auth/AccessContextTest.java @@ -41,7 +41,7 @@ import io.personium.common.auth.token.VisitorLocalAccessToken; import io.personium.common.auth.token.UnitLocalUnitUserToken; -import io.personium.common.utils.PersoniumCoreUtils; +import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.core.model.Cell; import io.personium.core.odata.OEntityWrapper; @@ -154,7 +154,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内の暗号化されたトークン情報 @@ -170,7 +170,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内の暗号化されたトークン情報 @@ -316,7 +316,7 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { 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, pCookiePeer, encodedCookieValue, 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..7178c5dd5 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 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/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 b662f3787..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) @@ -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 aa59f3675..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())); 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/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/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 00c3a1921..dcc3bdc69 100644 --- a/src/test/java/io/personium/test/jersey/cell/AclTest.java +++ b/src/test/java/io/personium/test/jersey/cell/AclTest.java @@ -36,7 +36,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.auth.OAuth2Helper; import io.personium.core.model.Box; @@ -1000,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(); @@ -1051,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の権限が必要 @@ -1066,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の削除 @@ -1687,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")); @@ -1701,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); @@ -1770,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); @@ -2105,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, @@ -2116,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削除 @@ -2145,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, 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/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 d46380540..969c26b79 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; @@ -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); 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 11b4db5a8..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 @@ -39,7 +39,7 @@ 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; @@ -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を結びつけ @@ -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); @@ -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削除 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..4ba426a7e 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; @@ -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") @@ -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 = @@ -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) 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 4f05ffca4..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 @@ -42,7 +42,7 @@ import io.personium.common.auth.token.Role; import io.personium.common.auth.token.TransCellAccessToken; import io.personium.common.auth.token.VisitorRefreshToken; -import io.personium.common.utils.PersoniumCoreUtils; +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; @@ -248,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") @@ -289,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") @@ -416,7 +416,7 @@ public AuthTest() { // 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(); @@ -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を削除 @@ -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") @@ -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); @@ -1481,7 +1481,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String // ------------------------------ // 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") @@ -1571,7 +1571,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String // ------------------------------ // Refresh should fail when added app auth (header) at refresh time. // ------------------------------ - String schemaTransCellAccessTokenHeader = PersoniumCoreUtils.createBasicAuthzHeader( + String schemaTransCellAccessTokenHeader = CommonUtils.createBasicAuthzHeader( UrlUtils.cellRoot(TEST_APP_CELL1), schemaTransCellAccessToken); res3 = Http.request("authn/refresh-cl-ch.txt") @@ -1671,7 +1671,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String // ------------------------------ // 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") @@ -1776,7 +1776,7 @@ private TResponse resetAcl(String cellName, String boxName, String token, String // ------------------------------ // 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") 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 61f7a1020..884cbc53c 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 @@ -34,7 +34,7 @@ import io.personium.common.auth.token.AbstractOAuth2Token.TokenParseException; import io.personium.common.auth.token.ResidentLocalAccessToken; import io.personium.common.auth.token.PasswordChangeAccessToken; -import io.personium.common.utils.PersoniumCoreUtils; +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; @@ -450,7 +450,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", "", 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 130ec9a56..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; @@ -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/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 365a137a8..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; @@ -349,7 +349,7 @@ public static String createDefaultHtml(String clientId, String redirectUriStr, S 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; @@ -386,7 +386,7 @@ public static String createDefaultPasswordChangeHtml(String clientId, String red 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/ResourceUtils.java b/src/test/java/io/personium/test/utils/ResourceUtils.java index 47c153dd7..b1ab93f64 100644 --- a/src/test/java/io/personium/test/utils/ResourceUtils.java +++ b/src/test/java/io/personium/test/utils/ResourceUtils.java @@ -24,7 +24,7 @@ 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; @@ -129,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; @@ -407,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() From 006261d020d8cb7187deef528ba732d1c8b44a9e Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sat, 17 Aug 2019 22:07:24 +0900 Subject: [PATCH 39/69] make able to handle scopes --- .../io/personium/core/auth/OAuth2Helper.java | 7 +++- .../java/io/personium/core/model/Cell.java | 3 ++ .../core/model/impl/es/CellEsImpl.java | 7 ++++ .../io/personium/core/model/jaxb/Acl.java | 2 +- .../core/rs/cell/AuthzEndPointResource.java | 30 ++++++++-------- .../core/rs/cell/BoxUrlResource.java | 2 +- .../core/rs/cell/TokenEndPointResource.java | 34 +++++++++++-------- .../core/rule/action/TokenBuilder.java | 6 ++-- .../cell/auth/token/TokenAcceptanceTest.java | 8 ++--- .../jersey/cell/auth/token/TokenTest.java | 14 ++++---- 10 files changed, 67 insertions(+), 46 deletions(-) diff --git a/src/main/java/io/personium/core/auth/OAuth2Helper.java b/src/main/java/io/personium/core/auth/OAuth2Helper.java index d7fe2bf35..68a98311a 100644 --- a/src/main/java/io/personium/core/auth/OAuth2Helper.java +++ b/src/main/java/io/personium/core/auth/OAuth2Helper.java @@ -180,6 +180,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"; + } /** @@ -291,6 +292,10 @@ 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. */ @@ -354,7 +359,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/model/Cell.java b/src/main/java/io/personium/core/model/Cell.java index 1d0b79f3d..6b8b5ff48 100644 --- a/src/main/java/io/personium/core/model/Cell.java +++ b/src/main/java/io/personium/core/model/Cell.java @@ -27,6 +27,7 @@ import io.personium.common.auth.token.IExtRoleContainingToken; import io.personium.common.auth.token.Role; +import io.personium.core.auth.ScopeArbitrator; import io.personium.core.event.EventBus; import io.personium.core.model.ctl.Common; import io.personium.core.odata.OEntityWrapper; @@ -173,6 +174,8 @@ public interface Cell { */ Box getBoxForSchema(String boxSchema); + ScopeArbitrator getScopeArbitrator(String clientId, boolean isRopc); + /** * It gets the Accounts to specify the Account name. * @param username Account name 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 2a0ab5558..0b8bbc34e 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 @@ -51,6 +51,7 @@ import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; import io.personium.core.auth.AuthUtils; +import io.personium.core.auth.ScopeArbitrator; import io.personium.core.event.EventBus; import io.personium.core.eventlog.EventUtils; import io.personium.core.model.Box; @@ -993,4 +994,10 @@ private void addRole(String uuid, List roles) { roles.add(new Role(roleName, boxName, schema, this.url)); } + + @Override + public ScopeArbitrator getScopeArbitrator(String clientId, boolean isRopc) { + Box box = this.getBoxForSchema(clientId); + return new ScopeArbitrator(this, box, isRopc); + } } 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 80358ca90..88569122a 100644 --- a/src/main/java/io/personium/core/model/jaxb/Acl.java +++ b/src/main/java/io/personium/core/model/jaxb/Acl.java @@ -200,7 +200,7 @@ public boolean allows(final Privilege priv, final AccessContext ac, Map 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. @@ -312,10 +315,10 @@ private Response callAuthPlugins(String grantType, MultivaluedMap roleList; - private String scope; + private String[] scope; /** * Constructor. @@ -89,7 +89,7 @@ public TokenBuilder schema(String schema) { // CHECKSTYLE IGNORE * @param scope scope * @return TokenBuilder */ - public TokenBuilder scope(String scope) { // CHECKSTYLE IGNORE + public TokenBuilder scope(String[] scope) { // CHECKSTYLE IGNORE this.scope = scope; return this; } 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 index f6d12514f..feb4ef300 100644 --- 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 @@ -127,7 +127,7 @@ public final void Should_FailRefreshingToken_When_ClientIdNotMatchesSchemaInRefr String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token without schema - ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl2, "ROPC"); + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl2, new String [] {"scope1"}); // Generate AppAuth Token List roleList = new ArrayList(); @@ -159,7 +159,7 @@ public final void Should_SuccessRefrehingToken__When_ClientIdMatchesSchemaInRefr String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token - ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl, "ROPC"); + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl, new String[] {"scope1"}); // Generate AppAuth Token List roleList = new ArrayList(); @@ -198,7 +198,7 @@ public final void Should_FailRefrehingToken__When_RefreshTokenHasSchemaButNoAppA String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token - ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl, "ROPC"); + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", appCellUrl, new String[] {"scope1"}); // Refresh Token HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), null); @@ -223,7 +223,7 @@ public final void Should_SuccessRefrehingToken__When_ClientIdNullAndRefreshToken String usrCellUrl = UriUtils.resolveLocalUnit(usrCellLocalUnit); // Generate Refresh Token - ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", null, "ROPC"); + ResidentRefreshToken clrt = new ResidentRefreshToken(usrCellUrl, "account1", null, new String[] {"scope1", "scope2"}); // Refresh Token HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl); 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 a18bb3b1d..6334dbb12 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 @@ -115,8 +115,8 @@ public TokenTest() { // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) ResidentRefreshToken validToken = new ResidentRefreshToken( - issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 + MILLISECS_IN_AN_MINITE, - issuer, subject, schema, "ROPC"); + issuedAt - AbstractOAuth2Token.SECS_IN_A_DAY * 1000 + MILLISECS_IN_AN_MINITE, + issuer, subject, schema, new String[] {"scope1", "scope2"}); // アプリセルに対して認証 Http.request("authn/refresh-cl.txt") @@ -127,8 +127,8 @@ public TokenTest() { // 期限切れのトークンを生成する(IT環境の通信時間を考慮して1分余裕を持たせる) ResidentRefreshToken invalidToken = new ResidentRefreshToken( - issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 - MILLISECS_IN_AN_MINITE, issuer, subject, - schema, "ROPC"); + 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) @@ -152,7 +152,7 @@ public TokenTest() { // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) VisitorRefreshToken validToken = new VisitorRefreshToken( - id, issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 + MILLISECS_IN_AN_MINITE, + id, issuedAt - AbstractOAuth2Token.SECS_IN_A_DAY * 1000 + MILLISECS_IN_AN_MINITE, issuer, subject, origIssuer, origRoleList, schema); // Refresh Http.request("authn/refresh-cl.txt") @@ -163,7 +163,7 @@ public TokenTest() { // 期限切れのトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) VisitorRefreshToken invalidToken = new VisitorRefreshToken( - id, issuedAt - AbstractOAuth2Token.SECS_IN_AN_DAY * 1000 - MILLISECS_IN_AN_MINITE, + id, issuedAt - AbstractOAuth2Token.SECS_IN_A_DAY * 1000 - MILLISECS_IN_AN_MINITE, issuer, subject, origIssuer, origRoleList, schema); // Refresh Http.request("authn/refresh-cl.txt") @@ -226,7 +226,7 @@ public TokenTest() { String issuer = UrlUtils.cellRoot(TEST_CELL1); String subject = "account2"; String schema = ""; - String scope = AbstractOAuth2Token.Scope.ROPC; + String[] scope = new String[0]; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) ResidentLocalAccessToken validToken = new ResidentLocalAccessToken( From 83568a6aea38a57ebe6e9a0dbdcb488e6732c73a Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 18 Aug 2019 01:21:55 +0900 Subject: [PATCH 40/69] make able to handle scopes --- .../personium/core/auth/ScopeArbitrator.java | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/main/java/io/personium/core/auth/ScopeArbitrator.java 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..4f7da28e5 --- /dev/null +++ b/src/main/java/io/personium/core/auth/ScopeArbitrator.java @@ -0,0 +1,74 @@ +package io.personium.core.auth; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +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; + +public class ScopeArbitrator { + Cell cell; + Box box; + boolean isRopc; + String[] requestedScopes = new String[0]; + List permittedScopes = new ArrayList(); + + static final String[] VALID_NON_URL_SCOPES = new String[] { + "root", + OAuth2Helper.Scope.OPENID + }; + public ScopeArbitrator(Cell cell, Box box, boolean ropc) { + this.cell = cell; + this.box = box; + this.isRopc = ropc; + } + public void request(String requestScopes) { + this.requestedScopes = AbstractOAuth2Token.Scope.parse(requestScopes); + arbitrate(); + } + public ScopeArbitrator request(String[] requestScopes) { + if (requestScopes != null) { + this.requestedScopes = requestScopes; + } + arbitrate(); + return this; + } + private void arbitrate() { + for (int i = 0 ; i < this.requestedScopes.length ; i++) { + if (this.check(requestedScopes[i])) { + this.permittedScopes.add(this.requestedScopes[i]); + } + } + } + public String[] getResults() { + return this.permittedScopes.toArray(new String[0]); + } + private boolean check(String scope) { + String resolvedScope = UriUtils.resolveLocalUnit(scope); + if (resolvedScope.startsWith("http://") || resolvedScope.startsWith("https://")) { + if (isRole(resolvedScope)) { + return true; + } + return false; + + } + // Exclude invalid non-URL values; + if (Arrays.binarySearch(VALID_NON_URL_SCOPES, scope) < 0) { + return false; + } + // if ROPC then allow any valid scopes. + if (this.isRopc) { + return true; + } + + return false; + } + private boolean isRole(String scope) { + String id = this.box.getCell().roleResourceUrlToId(scope, PersoniumUnitConfig.getBaseUrl()); + return (id != null); + } +} From 8afc7882f6e1b8f9ba050c8b08f4a367dbdc16d4 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sun, 18 Aug 2019 16:30:00 +0900 Subject: [PATCH 41/69] make able to handle scopes --- .../personium/core/auth/ScopeArbitrator.java | 32 ++++++++++--------- .../core/rs/cell/AuthzEndPointResource.java | 2 +- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/src/main/java/io/personium/core/auth/ScopeArbitrator.java b/src/main/java/io/personium/core/auth/ScopeArbitrator.java index 4f7da28e5..6b02d8b9b 100644 --- a/src/main/java/io/personium/core/auth/ScopeArbitrator.java +++ b/src/main/java/io/personium/core/auth/ScopeArbitrator.java @@ -2,7 +2,9 @@ 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; @@ -14,33 +16,33 @@ public class ScopeArbitrator { Cell cell; Box box; boolean isRopc; - String[] requestedScopes = new String[0]; + Set requestedScopes = new HashSet<>(); List permittedScopes = new ArrayList(); - static final String[] VALID_NON_URL_SCOPES = new String[] { - "root", - OAuth2Helper.Scope.OPENID - }; + static final Set VALID_NON_URL_SCOPES = new HashSet<>(Arrays.asList(new String[] { + CellPrivilege.ROOT.getName(), + CellPrivilege.MESSAGE.getName(), + OAuth2Helper.Scope.OPENID + })); public ScopeArbitrator(Cell cell, Box box, boolean ropc) { this.cell = cell; this.box = box; this.isRopc = ropc; } - public void request(String requestScopes) { - this.requestedScopes = AbstractOAuth2Token.Scope.parse(requestScopes); - arbitrate(); + public ScopeArbitrator request(String requestScopes) { + return this.request(AbstractOAuth2Token.Scope.parse(requestScopes)); } public ScopeArbitrator request(String[] requestScopes) { if (requestScopes != null) { - this.requestedScopes = requestScopes; + this.requestedScopes = new HashSet<>(Arrays.asList(requestScopes)); } - arbitrate(); + this.arbitrate(); return this; } private void arbitrate() { - for (int i = 0 ; i < this.requestedScopes.length ; i++) { - if (this.check(requestedScopes[i])) { - this.permittedScopes.add(this.requestedScopes[i]); + for (String scope : this.requestedScopes) { + if (this.check(scope)) { + this.permittedScopes.add(scope); } } } @@ -57,7 +59,7 @@ private boolean check(String scope) { } // Exclude invalid non-URL values; - if (Arrays.binarySearch(VALID_NON_URL_SCOPES, scope) < 0) { + if (!VALID_NON_URL_SCOPES.contains(scope)) { return false; } // if ROPC then allow any valid scopes. @@ -68,7 +70,7 @@ private boolean check(String scope) { return false; } private boolean isRole(String scope) { - String id = this.box.getCell().roleResourceUrlToId(scope, PersoniumUnitConfig.getBaseUrl()); + String id = this.cell.roleResourceUrlToId(scope, PersoniumUnitConfig.getBaseUrl()); return (id != null); } } 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 b22d49642..245aecf36 100644 --- a/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java @@ -180,7 +180,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 = scopeStr.split(" "); + String[] scope = AbstractOAuth2Token.Scope.parse(scopeStr); return auth(false, responseType, clientId, redirectUri, null, null, pCookie, state, scope, keepLogin, isCancel, expiresInStr, uriInfo, xForwardedFor, accessTokenStr, passwordChangeRequiredStr); } From c53a67d570ed198b135fad1a1bd9275f8dd320e4 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Mon, 19 Aug 2019 08:01:23 +0900 Subject: [PATCH 42/69] make able to handle scopes --- .../personium/core/auth/ScopeArbitrator.java | 17 ++ .../java/io/personium/core/model/Cell.java | 271 +++++++++++++++--- .../io/personium/core/model/CellRsCmp.java | 17 ++ .../core/model/impl/es/CellEsImpl.java | 237 +-------------- .../core/rs/PersoniumCoreApplication.java | 13 +- .../core/rs/cell/AuthResourceUtils.java | 21 -- .../core/rs/cell/AuthzEndPointResource.java | 2 +- .../core/rs/cell/TokenEndPointResource.java | 15 +- .../core/auth/ScopeArbitratorTest.java | 53 ++++ .../rs/cell/TokenEndPointResourceTest.java | 165 ++++++++++- 10 files changed, 483 insertions(+), 328 deletions(-) create mode 100644 src/test/java/io/personium/core/auth/ScopeArbitratorTest.java diff --git a/src/main/java/io/personium/core/auth/ScopeArbitrator.java b/src/main/java/io/personium/core/auth/ScopeArbitrator.java index 6b02d8b9b..56d91d955 100644 --- a/src/main/java/io/personium/core/auth/ScopeArbitrator.java +++ b/src/main/java/io/personium/core/auth/ScopeArbitrator.java @@ -22,6 +22,23 @@ public class ScopeArbitrator { static final Set VALID_NON_URL_SCOPES = new HashSet<>(Arrays.asList(new String[] { CellPrivilege.ROOT.getName(), CellPrivilege.MESSAGE.getName(), + CellPrivilege.MESSAGE_READ.getName(), + CellPrivilege.EVENT.getName(), + CellPrivilege.EVENT_READ.getName(), + CellPrivilege.ACL.getName(), + CellPrivilege.ACL_READ.getName(), + CellPrivilege.AUTH.getName(), + CellPrivilege.AUTH_READ.getName(), + CellPrivilege.SOCIAL.getName(), + CellPrivilege.SOCIAL_READ.getName(), + CellPrivilege.BOX.getName(), + CellPrivilege.BOX_BAR_INSTALL.getName(), + CellPrivilege.BOX_READ.getName(), + CellPrivilege.LOG.getName(), + CellPrivilege.LOG_READ.getName(), + CellPrivilege.PROPFIND.getName(), + CellPrivilege.RULE.getName(), + CellPrivilege.RULE_READ.getName(), OAuth2Helper.Scope.OPENID })); public ScopeArbitrator(Cell cell, Box box, boolean ropc) { diff --git a/src/main/java/io/personium/core/model/Cell.java b/src/main/java/io/personium/core/model/Cell.java index 6b8b5ff48..6ea29615d 100644 --- a/src/main/java/io/personium/core/model/Cell.java +++ b/src/main/java/io/personium/core/model/Cell.java @@ -16,199 +16,376 @@ */ 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.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. */ - String getOwnerNormalized(); + public String getOwnerNormalized() { + return UriUtils.convertSchemeFromLocalUnitToHttp(this.owner); + } /** * Returns the raw URI of the owner Unit User of this Cell. * @return raw owner url. */ - String getOwnerRaw(); + 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); - - ScopeArbitrator getScopeArbitrator(String clientId, boolean isRopc); - + 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, boolean isRopc) { + Box box = this.getBoxForSchema(clientId); + return new ScopeArbitrator(this, box, isRopc); + } /** * 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. @@ -216,7 +393,7 @@ 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); } diff --git a/src/main/java/io/personium/core/model/CellRsCmp.java b/src/main/java/io/personium/core/model/CellRsCmp.java index baa951c0e..0030687a1 100644 --- a/src/main/java/io/personium/core/model/CellRsCmp.java +++ b/src/main/java/io/personium/core/model/CellRsCmp.java @@ -355,6 +355,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/impl/es/CellEsImpl.java b/src/main/java/io/personium/core/model/impl/es/CellEsImpl.java index 0b8bbc34e..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,12 +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.auth.ScopeArbitrator; -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; @@ -64,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; @@ -87,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; /** @@ -204,95 +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.reason(e); - } - } - - /** - * {@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 getOwnerNormalized() { - return UriUtils.convertSchemeFromLocalUnitToHttp(this.owner); - } - @Override - public String getOwnerRaw() { - return this.owner; - } - - @Override public String getDataBundleNameWithOutPrefix() { String unitUserName; @@ -310,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.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; - } - /** * {@inheritDoc} */ @@ -433,81 +279,6 @@ public void run() { } }); thread.start(); - - } - - @Override - 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; - } - } - } - - @Override - 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; - } - - @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") @@ -995,9 +766,5 @@ private void addRole(String uuid, List roles) { roles.add(new Role(roleName, boxName, schema, this.url)); } - @Override - public ScopeArbitrator getScopeArbitrator(String clientId, boolean isRopc) { - Box box = this.getBoxForSchema(clientId); - return new ScopeArbitrator(this, box, isRopc); - } + } diff --git a/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java b/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java index 46727b8f6..510679afa 100644 --- a/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java +++ b/src/main/java/io/personium/core/rs/PersoniumCoreApplication.java @@ -45,10 +45,9 @@ public class PersoniumCoreApplication extends Application { */ public static void start() { try { + loadConfig(); TransCellAccessToken.configureX509(PersoniumUnitConfig.getX509PrivateKey(), PersoniumUnitConfig.getX509Certificate(), PersoniumUnitConfig.getX509RootCertificate()); - AbstractLocalToken.setKeyString(PersoniumUnitConfig.getTokenSecretKey()); - DataCryptor.setKeyString(PersoniumUnitConfig.getTokenSecretKey()); PersoniumThread.start(PersoniumUnitConfig.getThreadPoolNumForCellIO(), PersoniumUnitConfig.getThreadPoolNumForBoxIO(), PersoniumUnitConfig.getThreadPoolNumForMisc()); @@ -67,12 +66,20 @@ public static void start() { String.valueOf(mergeSchedulerMaxThreadCount)); } - pm = new PluginManager(); + loadPlugins(); } catch (Exception e) { PersoniumCoreLog.Server.FAILED_TO_START_SERVER.reason(e).writeLog(); throw new RuntimeException(e); } } + public static void loadConfig() { + AbstractLocalToken.setKeyString(PersoniumUnitConfig.getTokenSecretKey()); + DataCryptor.setKeyString(PersoniumUnitConfig.getTokenSecretKey()); + } + + public static void loadPlugins() { + pm = new PluginManager(); + } /** * Stop Application. 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 245aecf36..075ae50ad 100644 --- a/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java @@ -467,7 +467,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) { 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 e72d2e4a6..6f0ecef20 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. @@ -72,11 +72,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; @@ -97,7 +97,7 @@ public class TokenEndPointResource { 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. @@ -110,7 +110,7 @@ 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; } @@ -812,7 +812,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) { @@ -880,7 +880,8 @@ private Response handlePassword(final String target, final String owner, throw PersoniumCoreAuthnException.AUTHN_FAILED.realm(this.cell.getUrl()); } } - String[] scopes = this.cell.getScopeArbitrator(schema, true).request(scope).getResults(); + ScopeArbitrator sa = this.cell.getScopeArbitrator(schema, true); + String[] scopes = sa.request(scope).getResults(); return issueToken(target, owner, schema, username, expiresIn, rTokenExpiresIn, scopes); } 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..8799ecbd1 --- /dev/null +++ b/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java @@ -0,0 +1,53 @@ +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.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); + + @Before + public void setUp() throws Exception { + doReturn("https://personium.example/").when(mockCell).getUnitUrl(); + + } + + @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, true); + sa.request("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 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, false); + sa.request("root message-read"); + String[] res = sa.getResults(); + assertEquals(0, res.length); + } +} 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 7bdfd5149..fe2c93b85 100644 --- a/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java +++ b/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java @@ -18,34 +18,61 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; 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.VisitorLocalAccessToken; import io.personium.common.auth.token.ResidentRefreshToken; import io.personium.common.auth.token.Role; +import io.personium.common.auth.token.VisitorLocalAccessToken; import io.personium.common.auth.token.VisitorRefreshToken; 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; /** @@ -55,17 +82,114 @@ @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; + + @BeforeClass + public static void beforeClass() { + PersoniumCoreApplication.loadConfig(); + PersoniumCoreApplication.loadPlugins(); + + } + @AfterClass + public static void afterClass() { + + } + /** * Before. + * @throws Exception */ @Before - public void before() { - 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)); } /** @@ -76,9 +200,6 @@ public void before() { @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,8 +213,6 @@ public void receiveRefresh_Normal_cell_local_token() throws Exception { // -------------------- // Mock settings // -------------------- - PowerMockito.doReturn(cellUrl).when(tokenEndPointResource, "getIssuerUrl"); - doReturn(host).when(mockCell).getUnitUrl(); ResidentRefreshToken mockOldRToken = PowerMockito.mock(ResidentRefreshToken.class); PowerMockito.mockStatic(AbstractOAuth2Token.class); PowerMockito.when(AbstractOAuth2Token.class, @@ -149,9 +268,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 // -------------------- @@ -165,8 +281,6 @@ public void receiveRefresh_Normal_trans_cell_access_token() throws Exception { // -------------------- // Mock settings // -------------------- - PowerMockito.doReturn(cellUrl).when(tokenEndPointResource, "getIssuerUrl"); - doReturn(host).when(mockCell).getUnitUrl(); VisitorRefreshToken mockOldRToken = PowerMockito.mock(VisitorRefreshToken.class); PowerMockito.mockStatic(AbstractOAuth2Token.class); PowerMockito.when(AbstractOAuth2Token.class, @@ -211,4 +325,27 @@ public void receiveRefresh_Normal_trans_cell_access_token() throws Exception { // -------------------- assertThat(actual.getStatus(), is(expected.getStatus())); } + + @Test + public void testToken() throws Exception { + String cellUrl = "https://personium/testcell/"; + 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/"); + + UriInfo uriInfo = mock(UriInfo.class); + doReturn(new URI(cellUrl)).when(uriInfo).getBaseUri(); + + Response res = tokenEndPointResource.token(uriInfo, null, formParams, xForwadedFor); + JsonObject j = Json.createReader(new ByteArrayInputStream(res.getEntity().toString().getBytes(Charsets.UTF8_CHARSET))).readObject(); + System.out.println(j.getString("access_token")); + assertEquals(200, res.getStatus()); + + + } } From 37be17d9e4d41ed8910f5cc1bc346a88b6e69fc8 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Mon, 19 Aug 2019 08:23:38 +0900 Subject: [PATCH 43/69] make able to handle scopes ( Fix for oidc related degrade) --- .../io/personium/core/rs/cell/TokenEndPointResource.java | 6 +++++- .../personium/core/rs/cell/TokenEndPointResourceTest.java | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) 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 6f0ecef20..7ebdfd76b 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -18,11 +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; @@ -502,7 +505,8 @@ private Response receiveCode(final String target, String owner, String schema, // 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(); 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 fe2c93b85..a3af8c681 100644 --- a/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java +++ b/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java @@ -327,7 +327,7 @@ public void receiveRefresh_Normal_trans_cell_access_token() throws Exception { } @Test - public void testToken() throws Exception { + public void testToken_password() throws Exception { String cellUrl = "https://personium/testcell/"; String xForwadedFor = "1.2.3.4"; @@ -345,7 +345,7 @@ public void testToken() throws Exception { JsonObject j = Json.createReader(new ByteArrayInputStream(res.getEntity().toString().getBytes(Charsets.UTF8_CHARSET))).readObject(); System.out.println(j.getString("access_token")); assertEquals(200, res.getStatus()); + } - } } From 7f162928e0e92fc9706a0f5169e64555e840669d Mon Sep 17 00:00:00 2001 From: akioshimono Date: Mon, 19 Aug 2019 21:42:42 +0900 Subject: [PATCH 44/69] let token endpoint return scope actually granted to the app --- src/main/java/io/personium/core/rs/cell/CellCtlResource.java | 3 +-- .../java/io/personium/core/rs/cell/TokenEndPointResource.java | 3 +++ .../io/personium/core/rs/cell/TokenEndPointResourceTest.java | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) 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 19d98e5a2..18ae7edd7 100644 --- a/src/main/java/io/personium/core/rs/cell/CellCtlResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellCtlResource.java @@ -58,7 +58,6 @@ * JAX-RS Resource handling DC Cell Level Api. */ public final class CellCtlResource extends ODataResource { - String pCredHeader; DavRsCmp davRsCmp; @@ -82,7 +81,7 @@ public void checkAccessContext(final AccessContext ac, Privilege 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() { 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 7ebdfd76b..389d2b3ff 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -712,6 +712,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.getScopes() != null && accessToken.getScopes().length > 0) { + resp.put(OAuth2Helper.Key.SCOPE, AbstractOAuth2Token.Scope.toConcatValue(accessToken.getScopes())); + } if (refreshToken != null) { resp.put(OAuth2Helper.Key.REFRESH_TOKEN, refreshToken.toTokenString()); resp.put(OAuth2Helper.Key.REFRESH_TOKEN_EXPIRES_IN, refreshToken.refreshExpiresIn()); 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 a3af8c681..990b6f04d 100644 --- a/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java +++ b/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java @@ -343,8 +343,8 @@ public void testToken_password() throws Exception { Response res = tokenEndPointResource.token(uriInfo, null, formParams, xForwadedFor); JsonObject j = Json.createReader(new ByteArrayInputStream(res.getEntity().toString().getBytes(Charsets.UTF8_CHARSET))).readObject(); - System.out.println(j.getString("access_token")); assertEquals(200, res.getStatus()); + assertEquals("root", j.getString("scope")); } From 2323cca47cacdd7e06cc1a302852038fdd4b422a Mon Sep 17 00:00:00 2001 From: akioshimono Date: Mon, 19 Aug 2019 22:09:31 +0900 Subject: [PATCH 45/69] some refactoring for the preparation for implementing scope based access control --- .../io/personium/core/auth/AccessContext.java | 60 +++++++++++++------ .../core/rs/cell/PasswordResource.java | 5 +- .../core/auth/AccessContextTest.java | 6 +- 3 files changed, 46 insertions(+), 25 deletions(-) diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index f027a6ff8..48519c1c5 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; @@ -32,13 +37,13 @@ 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.VisitorLocalAccessToken; import io.personium.common.auth.token.IAccessToken; 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.UnitLocalUnitUserToken; +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; @@ -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 scopeRole = new HashSet<>(); + /** confidentialLevel. */ private String confidentialLevel; /** Roles associated with access account. */ @@ -186,7 +198,6 @@ public static AccessContext create(String authzHeaderValue, } String nonPortHost = headerHost.split(":")[0]; - // Cookie related processing requires no port number. String authToken = null; try { @@ -200,10 +211,8 @@ public static AccessContext create(String authzHeaderValue, } } - //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 - + // 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 if (authzHeaderValue.startsWith(OAuth2Helper.Scheme.BASIC)) { //Basic authentication return createBasicAuthz(authzHeaderValue, cell, baseUri, requestURIInfo); @@ -378,8 +387,7 @@ 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().getOwnerNormalized())) { @@ -389,6 +397,7 @@ && getSubject().equals(getCell().getOwnerNormalized())) { return false; } + /** * Perform access control (only master token, unit user token, unit local unit user token accessible). * @param resourcePrivilege Required authority @@ -455,7 +464,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 checkMyLocalOrPasswordChangeToken(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())) { @@ -475,7 +484,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; } @@ -551,7 +561,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; } @@ -777,8 +787,23 @@ 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.scopeRole.add(new Role(new URL(scope))); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } else { + ret.scopePrivileges.add(CellPrivilege.get(CellPrivilege.class, scope)); + } + } + } return ret; } @@ -929,5 +954,4 @@ private static AccessContext createAccessContext(Cell cell, String requestURIHos return ret; } } - } diff --git a/src/main/java/io/personium/core/rs/cell/PasswordResource.java b/src/main/java/io/personium/core/rs/cell/PasswordResource.java index 4e65734af..a29d5b2a3 100644 --- a/src/main/java/io/personium/core/rs/cell/PasswordResource.java +++ b/src/main/java/io/personium/core/rs/cell/PasswordResource.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; @@ -75,7 +73,7 @@ public PasswordResource(final AccessContext accessContext, @PUT public Response mypass() { //Access control - this.accessContext.checkMyLocalOrPasswordChangeToken(cell, this.davRsCmp.getAcceptableAuthScheme()); + this.accessContext.checkMyLocalOrPasswordChangeToken(this.davRsCmp.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/test/java/io/personium/core/auth/AccessContextTest.java b/src/test/java/io/personium/core/auth/AccessContextTest.java index 1e8a36a2e..8cf987a0f 100644 --- a/src/test/java/io/personium/core/auth/AccessContextTest.java +++ b/src/test/java/io/personium/core/auth/AccessContextTest.java @@ -39,8 +39,8 @@ import org.junit.runner.RunWith; import org.mockito.Matchers; -import io.personium.common.auth.token.VisitorLocalAccessToken; import io.personium.common.auth.token.UnitLocalUnitUserToken; +import io.personium.common.auth.token.VisitorLocalAccessToken; import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumUnitConfig; import io.personium.core.model.Cell; @@ -50,14 +50,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(); From 5168064e65e9a88259c489a688ac9ffd33a3f476 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Mon, 19 Aug 2019 23:21:41 +0900 Subject: [PATCH 46/69] update pom.xml to use personium-lib-common 1.5.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index bf571031c..e58e51faf 100644 --- a/pom.xml +++ b/pom.xml @@ -32,7 +32,7 @@ io.personium personium-lib-common - 1.5.0-SNAPSHOT + 1.5.0 io.personium From f68b2e33990d7ff3c1262183d8255bce7f7cbcfd Mon Sep 17 00:00:00 2001 From: akioshimono Date: Tue, 20 Aug 2019 00:56:32 +0900 Subject: [PATCH 47/69] some refactoring for the preparation for implementing scope based access control --- .../io/personium/core/auth/AccessContext.java | 30 +++++++++++++++---- .../java/io/personium/core/model/Cell.java | 8 +++++ .../io/personium/core/model/CellRsCmp.java | 2 +- .../io/personium/core/model/DavRsCmp.java | 2 +- .../rs/box/ODataSvcCollectionResource.java | 5 ++-- 5 files changed, 37 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index 48519c1c5..902ccbbc8 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -175,6 +175,7 @@ private AccessContext(String type, Cell cell, String baseUri, UriInfo uriInfo, I this.baseUri = baseUri; this.uriInfo = uriInfo; this.invalidReason = invalidReason; + } /** @@ -211,7 +212,6 @@ public static AccessContext create(String authzHeaderValue, } } - // 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 if (authzHeaderValue.startsWith(OAuth2Helper.Scheme.BASIC)) { //Basic authentication @@ -322,12 +322,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 requirePrivilege(Acl acl, Privilege resourcePrivilege) { //No access if ACL is not set if (acl == null || acl.getAceList() == null) { return false; @@ -366,7 +365,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; @@ -954,4 +953,25 @@ private static AccessContext createAccessContext(Cell cell, String requestURIHos return ret; } } + + /** + * Check if this access context has the cell level privilege. + * @param cellPriv + * @return + */ + public boolean hasPrivilege(CellPrivilege cellPriv) { + return hasPrivilegeInScope(cellPriv) && hasPrivilegeInSubject(cellPriv); + } + private boolean hasPrivilegeInScope(CellPrivilege cellPriv) { + for (CellPrivilege scopePriv : this.scopePrivileges) { + if (scopePriv.includes(cellPriv)) { + return true; + } + } + // TODO scope role check + return false; + } + private boolean hasPrivilegeInSubject(CellPrivilege cellPriv) { + return this.requirePrivilege(this.cell.getAcl(), cellPriv); + } } diff --git a/src/main/java/io/personium/core/model/Cell.java b/src/main/java/io/personium/core/model/Cell.java index 6ea29615d..0cbd262a0 100644 --- a/src/main/java/io/personium/core/model/Cell.java +++ b/src/main/java/io/personium/core/model/Cell.java @@ -56,6 +56,7 @@ 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; @@ -395,5 +396,12 @@ public boolean authenticateAccount(final OEntityWrapper oew, final String passwo */ 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 0030687a1..9155e7b52 100644 --- a/src/main/java/io/personium/core/model/CellRsCmp.java +++ b/src/main/java/io/personium/core/model/CellRsCmp.java @@ -142,7 +142,7 @@ public boolean hasPrivilege(AccessContext ac, Privilege privilege) { //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().requirePrivilege(this.davCmp.getAcl(), privilege)) { return true; } return false; diff --git a/src/main/java/io/personium/core/model/DavRsCmp.java b/src/main/java/io/personium/core/model/DavRsCmp.java index 901897d8d..32f18f685 100644 --- a/src/main/java/io/personium/core/model/DavRsCmp.java +++ b/src/main/java/io/personium/core/model/DavRsCmp.java @@ -396,7 +396,7 @@ public boolean hasPrivilege(AccessContext ac, Privilege privilege, Privilege par // 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().requirePrivilege(this.davCmp.getAcl(), privilege)) { return true; } diff --git a/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java b/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java index 9db203883..abc4bd0b2 100644 --- a/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java @@ -275,11 +275,10 @@ public AcceptableAuthScheme getAcceptableAuthScheme() { @Override public boolean hasPrivilegeForBatch(AccessContext ac) { Acl acl = this.davRsCmp.getDavCmp().getAcl(); - String url = this.davRsCmp.getCell().getUrl(); - if (ac.requirePrivilege(acl, BoxPrivilege.READ, url)) { + if (ac.requirePrivilege(acl, BoxPrivilege.READ)) { return true; } - if (ac.requirePrivilege(acl, BoxPrivilege.WRITE, url)) { + if (ac.requirePrivilege(acl, BoxPrivilege.WRITE)) { return true; } return false; From 193dbff8a0c1dd5cd0858d1156397e00de7cbc9d Mon Sep 17 00:00:00 2001 From: akioshimono Date: Tue, 20 Aug 2019 01:19:30 +0900 Subject: [PATCH 48/69] minor refactoring --- .../core/rs/cell/CellCtlResource.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) 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 18ae7edd7..eeaf1f3ee 100644 --- a/src/main/java/io/personium/core/rs/cell/CellCtlResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellCtlResource.java @@ -38,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; @@ -59,24 +59,24 @@ */ 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); + this.cellRsCmp.checkAccessContext(ac, privilege); } /** @@ -85,12 +85,12 @@ public void checkAccessContext(final AccessContext ac, Privilege privilege) { */ @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); + return this.cellRsCmp.hasPrivilege(ac, privilege); } @Override @@ -476,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); From d3063e6c232286d165a3ccd9dd45b48e9ded08f4 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Tue, 20 Aug 2019 22:35:35 +0900 Subject: [PATCH 49/69] If ROPC then default scope will be root. --- .../personium/core/auth/ScopeArbitrator.java | 34 +++++++++++++++++-- .../core/auth/ScopeArbitratorTest.java | 11 ++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/personium/core/auth/ScopeArbitrator.java b/src/main/java/io/personium/core/auth/ScopeArbitrator.java index 56d91d955..7887822ff 100644 --- a/src/main/java/io/personium/core/auth/ScopeArbitrator.java +++ b/src/main/java/io/personium/core/auth/ScopeArbitrator.java @@ -12,6 +12,23 @@ 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 a flag whether the token + * authentication is done via ROPC or not. + * + * 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; @@ -53,6 +70,12 @@ public ScopeArbitrator request(String[] requestScopes) { if (requestScopes != null) { this.requestedScopes = new HashSet<>(Arrays.asList(requestScopes)); } + // remove empty entry + this.requestedScopes.remove(""); + if (this.requestedScopes.size() == 0 && this.isRopc) { + // if ROPC and no scope requested then root will be granted. + this.requestedScopes.add("root"); + } this.arbitrate(); return this; } @@ -68,22 +91,27 @@ public String[] getResults() { } private boolean check(String scope) { 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; - } - // Exclude invalid non-URL values; + // If not, it should probably be Cell Privilege. + // make sure. if (!VALID_NON_URL_SCOPES.contains(scope)) { return false; } + // Now Cell Level privilege can come here. // if ROPC then allow any valid scopes. if (this.isRopc) { return true; } - + // if not the reject all .. (Tentatively) + // TODO implement Box configuration to allow Cell Level privilege, and refer to that + // setting. return false; } private boolean isRole(String scope) { diff --git a/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java b/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java index 8799ecbd1..8c943734a 100644 --- a/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java +++ b/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java @@ -40,6 +40,17 @@ public void When_ROPC_Then_CellLevelPrivileges_CanBeAllowed () { 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, true); + sa.request(""); + String[] res = sa.getResults(); + assertEquals("root", res[0]); + } + /** * When constructed with non-ROPC option, then any Cell level priviledge can not be allowed. */ From 4e05cb7f0cc8f724ed3ee2611b5e94523fc60440 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Wed, 21 Aug 2019 09:03:33 +0900 Subject: [PATCH 50/69] password change requires auth scope --- .../core/PersoniumCoreException.java | 5 + .../io/personium/core/auth/AccessContext.java | 10 +- .../personium/core/auth/ScopeArbitrator.java | 2 +- .../io/personium/core/model/DavRsCmp.java | 3 +- .../personium/core/rs/cell/CellResource.java | 6 +- ...dResource.java => MyPasswordResource.java} | 20 +-- .../resources/personium-messages.properties | 1 + .../core/auth/ScopeArbitratorTest.java | 6 +- .../test/jersey/cell/auth/MyPasswordTest.java | 131 ++++++++++++++++-- 9 files changed, 149 insertions(+), 35 deletions(-) rename src/main/java/io/personium/core/rs/cell/{PasswordResource.java => MyPasswordResource.java} (86%) diff --git a/src/main/java/io/personium/core/PersoniumCoreException.java b/src/main/java/io/personium/core/PersoniumCoreException.java index e2f54ce3a..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. */ diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index 902ccbbc8..88769c46b 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -474,6 +474,11 @@ public void checkMyLocalOrPasswordChangeToken(AcceptableAuthScheme acceptableAut } else if (!TYPE_ACCOUNT.equals(this.getType()) && !TYPE_PASSWORD_CHANGE.equals(this.getType())) { throw PersoniumCoreException.Auth.NECESSARY_PRIVILEGE_LACKING; } + + // Check if cope lacking + if (TYPE_ACCOUNT.equals(this.getType()) &&!this.hasPrivilegeInScope(CellPrivilege.AUTH)) { + throw PersoniumCoreException.Auth.INSUFFICIENT_SCOPE.params(CellPrivilege.AUTH.getName()); + } } /** @@ -799,7 +804,10 @@ private static AccessContext createBearerAuthz(String authzHeaderValue, Cell cel throw new RuntimeException(e); } } else { - ret.scopePrivileges.add(CellPrivilege.get(CellPrivilege.class, scope)); + CellPrivilege prv = CellPrivilege.get(CellPrivilege.class, scope); + if (prv != null) { + ret.scopePrivileges.add(prv); + } } } } diff --git a/src/main/java/io/personium/core/auth/ScopeArbitrator.java b/src/main/java/io/personium/core/auth/ScopeArbitrator.java index 7887822ff..ed0857d5e 100644 --- a/src/main/java/io/personium/core/auth/ScopeArbitrator.java +++ b/src/main/java/io/personium/core/auth/ScopeArbitrator.java @@ -63,7 +63,7 @@ public ScopeArbitrator(Cell cell, Box box, boolean ropc) { this.box = box; this.isRopc = ropc; } - public ScopeArbitrator request(String requestScopes) { + public ScopeArbitrator requestString(String requestScopes) { return this.request(AbstractOAuth2Token.Scope.parse(requestScopes)); } public ScopeArbitrator request(String[] requestScopes) { diff --git a/src/main/java/io/personium/core/model/DavRsCmp.java b/src/main/java/io/personium/core/model/DavRsCmp.java index 32f18f685..4d6f6e664 100644 --- a/src/main/java/io/personium/core/model/DavRsCmp.java +++ b/src/main/java/io/personium/core/model/DavRsCmp.java @@ -57,7 +57,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; -import io.personium.common.auth.token.Role; import io.personium.common.utils.CommonUtils; import io.personium.core.PersoniumCoreAuthzException; import io.personium.core.PersoniumCoreException; @@ -488,7 +487,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; 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 e2bbf58e2..47d08fb17 100644 --- a/src/main/java/io/personium/core/rs/cell/CellResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellResource.java @@ -280,14 +280,14 @@ public CellCtlResource ctl( } /** - * Endpoint of password change API. + * Endpoint of my password change API. * @param pCredHeader pCredHeader * @return Response */ @Path("__mypassword") - public PasswordResource mypassword( + public MyPasswordResource mypassword( @HeaderParam(CommonUtils.HttpHeaders.X_PERSONIUM_CREDENTIAL) final String pCredHeader) { - return new PasswordResource(this.accessContext, pCredHeader, this.cell, this.cellRsCmp); + return new MyPasswordResource(this.accessContext, pCredHeader, this.cell, this.cellRsCmp); } /** 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 86% 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 a29d5b2a3..30b8892fe 100644 --- a/src/main/java/io/personium/core/rs/cell/PasswordResource.java +++ b/src/main/java/io/personium/core/rs/cell/MyPasswordResource.java @@ -28,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; @@ -36,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; } /** @@ -71,9 +71,9 @@ public PasswordResource(final AccessContext accessContext, */ @WriteAPI @PUT - public Response mypass() { + public Response put() { //Access control - this.accessContext.checkMyLocalOrPasswordChangeToken(this.davRsCmp.getAcceptableAuthScheme()); + this.accessContext.checkMyLocalOrPasswordChangeToken(this.cellRsCmp.getAcceptableAuthScheme()); //Get the Account name to change password from cell local token this.key = this.accessContext.getSubject(); String[] keyName; diff --git a/src/main/resources/personium-messages.properties b/src/main/resources/personium-messages.properties index f42ec28e2..1e6234b84 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 diff --git a/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java b/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java index 8c943734a..5174463df 100644 --- a/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java +++ b/src/test/java/io/personium/core/auth/ScopeArbitratorTest.java @@ -34,7 +34,7 @@ public void tearDown() throws Exception { @Test public void When_ROPC_Then_CellLevelPrivileges_CanBeAllowed () { ScopeArbitrator sa = new ScopeArbitrator(this.mockCell, this.mockBox, true); - sa.request("openid root root message foo https://personium.example/__role/__/someRole"); + 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, " ")); @@ -46,7 +46,7 @@ public void When_ROPC_Then_CellLevelPrivileges_CanBeAllowed () { @Test public void When_ROPC_noScopeRequest_Then_RootGranted () { ScopeArbitrator sa = new ScopeArbitrator(this.mockCell, this.mockBox, true); - sa.request(""); + sa.requestString(null); String[] res = sa.getResults(); assertEquals("root", res[0]); } @@ -57,7 +57,7 @@ public void When_ROPC_noScopeRequest_Then_RootGranted () { @Test public void When_NotROPC_Then_CellLevelPrivileges_CanNotBeAllowed () { ScopeArbitrator sa = new ScopeArbitrator(this.mockCell, this.mockBox, false); - sa.request("root message-read"); + sa.requestString("root message-read"); String[] res = sa.getResults(); assertEquals(0, res.length); } 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 884cbc53c..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.ResidentLocalAccessToken; import io.personium.common.auth.token.PasswordChangeAccessToken; +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. @@ -135,6 +199,8 @@ public final void test_my_password_change_token() throws TokenParseException { resBody = ResourceUtils.getLocalTokenByPassAuth(Setup.TEST_CELL1, account, "newPassword", -1); tokenStr = (String) resBody.get(OAuth2Helper.Key.ACCESS_TOKEN); assertTrue(tokenStr.startsWith(ResidentLocalAccessToken.PREFIX_ACCESS)); + } catch (Exception e) { + e.printStackTrace(); } finally { AccountUtils.delete(Setup.TEST_CELL1, MASTER_TOKEN, account, -1); } @@ -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); + } } From 0ee295448f2bceb2d0236db4cb26a74126fe9391 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Wed, 21 Aug 2019 17:24:56 +0900 Subject: [PATCH 51/69] refactoring: DavRsCmp has an AccessContest. so use it instead of hand it via parameter. --- .../io/personium/core/auth/AccessContext.java | 16 ++++++------ .../io/personium/core/model/BoxUrlRsCmp.java | 6 +++-- .../io/personium/core/model/CellRsCmp.java | 15 ++++++----- .../io/personium/core/model/DavRsCmp.java | 24 +++++++++-------- .../impl/es/odata/MessageODataProducer.java | 6 ++--- .../core/model/impl/fs/DavCmpFsImpl.java | 10 +++---- .../io/personium/core/rs/box/BoxResource.java | 16 ++++++------ .../core/rs/box/DavCollectionResource.java | 16 ++++++------ .../core/rs/box/DavFileResource.java | 16 ++++++------ .../personium/core/rs/box/NullResource.java | 25 +++++++++--------- .../rs/box/ODataSvcCollectionResource.java | 14 +++++----- .../core/rs/box/ODataSvcSchemaResource.java | 4 +-- .../box/PersoniumEngineSourceCollection.java | 7 +++-- .../PersoniumEngineSourceFileResource.java | 2 +- .../PersoniumEngineSourceNullResource.java | 2 +- .../PersoniumEngineSvcCollectionResource.java | 22 ++++++++-------- .../core/rs/box/StreamCollectionResource.java | 12 ++++----- .../personium/core/rs/box/StreamResource.java | 8 +++--- .../core/rs/cell/BoxUrlResource.java | 2 +- .../core/rs/cell/CellCtlResource.java | 2 +- .../core/rs/cell/CellExportResource.java | 2 +- .../personium/core/rs/cell/CellResource.java | 2 +- .../rs/cell/CellSnapshotDavFileResource.java | 10 +++---- .../personium/core/rs/cell/EventResource.java | 2 +- .../cell/IntrospectionEndPointResource.java | 6 ++--- .../personium/core/rs/cell/LogResource.java | 6 ++--- .../core/rs/cell/MessageResource.java | 4 +-- .../core/rs/cell/MyPasswordResource.java | 2 +- .../personium/core/rs/cell/RoleResource.java | 6 ++--- .../personium/core/model/BoxUrlRsCmpTest.java | 26 +++++++++---------- .../core/model/impl/fs/DavCmpFsImplTest.java | 2 +- 31 files changed, 150 insertions(+), 143 deletions(-) diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index 88769c46b..e39515019 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -326,7 +326,7 @@ public String getUnitUserRole() { * @param resourcePrivilege Privilege required to access the resource * @return boolean */ - public boolean requirePrivilege(Acl acl, Privilege resourcePrivilege) { + public boolean hasSubjectPrivilegeForAcl(Acl acl, Privilege resourcePrivilege) { //No access if ACL is not set if (acl == null || acl.getAceList() == null) { return false; @@ -463,7 +463,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(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())) { @@ -476,7 +476,7 @@ public void checkMyLocalOrPasswordChangeToken(AcceptableAuthScheme acceptableAut } // Check if cope lacking - if (TYPE_ACCOUNT.equals(this.getType()) &&!this.hasPrivilegeInScope(CellPrivilege.AUTH)) { + if (TYPE_ACCOUNT.equals(this.getType()) &&!this.hasScopeCellPrivilege(CellPrivilege.AUTH)) { throw PersoniumCoreException.Auth.INSUFFICIENT_SCOPE.params(CellPrivilege.AUTH.getName()); } } @@ -967,10 +967,10 @@ private static AccessContext createAccessContext(Cell cell, String requestURIHos * @param cellPriv * @return */ - public boolean hasPrivilege(CellPrivilege cellPriv) { - return hasPrivilegeInScope(cellPriv) && hasPrivilegeInSubject(cellPriv); + public boolean hasCellPrivilege(CellPrivilege cellPriv) { + return hasScopeCellPrivilege(cellPriv) && hasSubjectCellPrivilege(cellPriv); } - private boolean hasPrivilegeInScope(CellPrivilege cellPriv) { + private boolean hasScopeCellPrivilege(CellPrivilege cellPriv) { for (CellPrivilege scopePriv : this.scopePrivileges) { if (scopePriv.includes(cellPriv)) { return true; @@ -979,7 +979,7 @@ private boolean hasPrivilegeInScope(CellPrivilege cellPriv) { // TODO scope role check return false; } - private boolean hasPrivilegeInSubject(CellPrivilege cellPriv) { - return this.requirePrivilege(this.cell.getAcl(), cellPriv); + private boolean hasSubjectCellPrivilege(CellPrivilege cellPriv) { + return this.hasSubjectPrivilegeForAcl(this.cell.getAcl(), cellPriv); } } 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/CellRsCmp.java b/src/main/java/io/personium/core/model/CellRsCmp.java index 9155e7b52..3b8048c9d 100644 --- a/src/main/java/io/personium/core/model/CellRsCmp.java +++ b/src/main/java/io/personium/core/model/CellRsCmp.java @@ -138,11 +138,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.getAccessContext().hasSubjectPrivilegeForAcl(this.davCmp.getAcl(), privilege)) { return true; } return false; @@ -154,7 +156,7 @@ public boolean hasPrivilege(AccessContext ac, Privilege privilege) { * @param privilege Required privilege */ public void checkAccessContext(AccessContext ac, Privilege privilege) { - // Check UnitUser token. + // If UnitUser token, then OK. if (ac.isUnitUserToken(privilege)) { return; } @@ -163,9 +165,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())) { diff --git a/src/main/java/io/personium/core/model/DavRsCmp.java b/src/main/java/io/personium/core/model/DavRsCmp.java index 4d6f6e664..30db420b8 100644 --- a/src/main/java/io/personium/core/model/DavRsCmp.java +++ b/src/main/java/io/personium/core/model/DavRsCmp.java @@ -234,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; } @@ -380,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); } /** @@ -391,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.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; } @@ -414,7 +415,7 @@ 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, @@ -433,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); } /** @@ -444,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; @@ -465,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 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 3c71e6b1a..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()); 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 9316bc31d..1d0f95568 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 @@ -65,9 +65,9 @@ import io.personium.common.es.response.PersoniumGetResponse; import io.personium.common.es.util.IndexNameEncoder; 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; import io.personium.core.PersoniumUnitConfig; import io.personium.core.auth.AccessContext; import io.personium.core.auth.BoxPrivilege; @@ -924,7 +924,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 +932,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); diff --git a/src/main/java/io/personium/core/rs/box/BoxResource.java b/src/main/java/io/personium/core/rs/box/BoxResource.java index 5748ca444..1e2e59cc4 100644 --- a/src/main/java/io/personium/core/rs/box/BoxResource.java +++ b/src/main/java/io/personium/core/rs/box/BoxResource.java @@ -181,8 +181,8 @@ public Response get(@Context HttpHeaders httpHeaders) { */ private Response getBarFile() { // Access control. - boxRsCmp.checkAccessContext(boxRsCmp.getAccessContext(), BoxPrivilege.READ); - boxRsCmp.checkAccessContext(boxRsCmp.getAccessContext(), BoxPrivilege.READ_ACL); + boxRsCmp.checkAccessContext(BoxPrivilege.READ); + boxRsCmp.checkAccessContext(BoxPrivilege.READ_ACL); BarFileExporter exporter = new BarFileExporter(boxRsCmp); // Execute export. @@ -195,7 +195,7 @@ private Response getBarFile() { */ private Response getMetadata() { // Access control. - this.boxRsCmp.checkAccessContext(this.boxRsCmp.getAccessContext(), BoxPrivilege.READ); + this.boxRsCmp.checkAccessContext(BoxPrivilege.READ); //Get asynchronous processing status of box installation from cache. //In this case, if null is returned, box installation has not been executed, @@ -278,7 +278,7 @@ public Response recursiveDelete( boolean recursive = Boolean.valueOf(recursiveHeader); // Check acl. - boxRsCmp.checkAccessContext(boxRsCmp.getAccessContext(), CellPrivilege.BOX); + boxRsCmp.checkAccessContext(CellPrivilege.BOX); Response response = boxRsCmp.getDavCmp().delete(null, recursive).build(); @@ -313,7 +313,7 @@ public Response propfind(final Reader requestBodyXml, @HeaderParam(HttpHeaders.CONTENT_LENGTH) final Long contentLength, @HeaderParam("Transfer-Encoding") final String transferEncoding) { // Access Control - this.boxRsCmp.checkAccessContext(this.getAccessContext(), BoxPrivilege.READ_PROPERTIES); + this.boxRsCmp.checkAccessContext(BoxPrivilege.READ_PROPERTIES); Response response = this.boxRsCmp.doPropfind(requestBodyXml, depth, contentLength, @@ -346,7 +346,7 @@ public Response propfind(final Reader requestBodyXml, @PROPPATCH public Response proppatch(final Reader requestBodyXml) { //Access control - this.boxRsCmp.checkAccessContext(this.getAccessContext(), BoxPrivilege.WRITE_PROPERTIES); + this.boxRsCmp.checkAccessContext(BoxPrivilege.WRITE_PROPERTIES); Response response = this.boxRsCmp.doProppatch(requestBodyXml); // post event to EventBus @@ -393,7 +393,7 @@ public Response options() { @ACL public Response acl(final Reader reader) { //Access control - this.boxRsCmp.checkAccessContext(this.boxRsCmp.getAccessContext(), BoxPrivilege.WRITE_ACL); + this.boxRsCmp.checkAccessContext(BoxPrivilege.WRITE_ACL); Response response = this.boxRsCmp.doAcl(reader); // post event to EventBus @@ -495,7 +495,7 @@ public Response move( @Context HttpHeaders headers) { //MOVE method for Box resource is disabled - this.boxRsCmp.checkAccessContext(this.boxRsCmp.getAccessContext(), BoxPrivilege.WRITE); + this.boxRsCmp.checkAccessContext(BoxPrivilege.WRITE); throw PersoniumCoreException.Dav.RESOURCE_PROHIBITED_TO_MOVE_BOX; } } diff --git a/src/main/java/io/personium/core/rs/box/DavCollectionResource.java b/src/main/java/io/personium/core/rs/box/DavCollectionResource.java index 203b49580..6552351b1 100644 --- a/src/main/java/io/personium/core/rs/box/DavCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/DavCollectionResource.java @@ -74,7 +74,7 @@ public DavCollectionResource(final DavRsCmp parent, final DavCmp davCmp) { @GET public Response get() { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ); StringBuilder sb = new StringBuilder(); sb.append("URL : " + this.davRsCmp.getUrl() + "\n"); @@ -89,7 +89,7 @@ public Response get() { @PROPPATCH public Response proppatch(final Reader requestBodyXml) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_PROPERTIES); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE_PROPERTIES); Response response = this.davRsCmp.doProppatch(requestBodyXml); // post event to EventBus @@ -128,7 +128,7 @@ public Response delete( boolean recursive = Boolean.valueOf(recursiveHeader); // Check acl.(Parent acl check) // Since DavCollectionResource always has a parent, result of this.davRsCmp.getParent() will never be null. - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); if (!recursive && !this.davRsCmp.getDavCmp().isEmpty()) { throw PersoniumCoreException.Dav.HAS_CHILDREN; @@ -165,7 +165,7 @@ public Response propfind(final Reader requestBodyXml, @HeaderParam(HttpHeaders.CONTENT_LENGTH) final Long contentLength, @HeaderParam("Transfer-Encoding") final String transferEncoding) { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ_PROPERTIES); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ_PROPERTIES); Response response = this.davRsCmp.doPropfind(requestBodyXml, depth, contentLength, @@ -217,7 +217,7 @@ public Object nextPath(@PathParam("nextPath") final String nextPath, @MKCOL public Response mkcol() { //Access control - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.BIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.BIND); throw PersoniumCoreException.Dav.METHOD_NOT_ALLOWED; } @@ -231,7 +231,7 @@ public Response mkcol() { @ACL public Response acl(final Reader reader) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_ACL); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE_ACL); Response response = this.davRsCmp.doAcl(reader); // post event to EventBus @@ -258,7 +258,7 @@ public Response acl(final Reader reader) { @OPTIONS public Response options() { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, @@ -283,7 +283,7 @@ public Response move( @Context HttpHeaders headers) { //Access control to move source (check parent's authority) //Since DavCollectionResource always has a parent (the top is a Box), the result of this.davRsCmp.getParent () will never be null - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); return new DavMoveResource(this.davRsCmp.getParent(), this.davRsCmp.getDavCmp(), headers).doMove(); } } diff --git a/src/main/java/io/personium/core/rs/box/DavFileResource.java b/src/main/java/io/personium/core/rs/box/DavFileResource.java index 96846b7bb..025a34f63 100644 --- a/src/main/java/io/personium/core/rs/box/DavFileResource.java +++ b/src/main/java/io/personium/core/rs/box/DavFileResource.java @@ -77,7 +77,7 @@ public Response put(@HeaderParam(HttpHeaders.CONTENT_TYPE) final String contentT @HeaderParam(HttpHeaders.IF_MATCH) final String ifMatch, final InputStream inputStream) { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_CONTENT); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE_CONTENT); ResponseBuilder rb = this.davRsCmp.getDavCmp().putForUpdate(contentType, inputStream, ifMatch); Response res = rb.build(); @@ -111,7 +111,7 @@ public Response get( @HeaderParam("Range") final String rangeHeaderField) { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ); ResponseBuilder rb = this.davRsCmp.get(ifNoneMatch, rangeHeaderField); Response res = rb.build(); @@ -143,7 +143,7 @@ public Response get( public Response delete(@HeaderParam(HttpHeaders.IF_MATCH) final String ifMatch) { // Access Control //The result of this.davRsCmp.getParent () is never null since DavFileResource always has a parent (the top is Box) - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); ResponseBuilder rb = this.davRsCmp.getDavCmp().delete(ifMatch, false); Response res = rb.build(); @@ -174,7 +174,7 @@ public Response delete(@HeaderParam(HttpHeaders.IF_MATCH) final String ifMatch) @PROPPATCH public Response proppatch(final Reader requestBodyXml) { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_PROPERTIES); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE_PROPERTIES); Response response = this.davRsCmp.doProppatch(requestBodyXml); // post event to EventBus @@ -208,7 +208,7 @@ public Response propfind(final Reader requestBodyXml, @HeaderParam(HttpHeaders.CONTENT_LENGTH) final Long contentLength, @HeaderParam("Transfer-Encoding") final String transferEncoding) { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ_PROPERTIES); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ_PROPERTIES); Response response = this.davRsCmp.doPropfind(requestBodyXml, depth, contentLength, @@ -250,7 +250,7 @@ public Response report() { @ACL public Response acl(final Reader reader) { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_ACL); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE_ACL); Response response = this.davRsCmp.doAcl(reader); // post event to EventBus @@ -281,7 +281,7 @@ public Response move( @Context HttpHeaders headers) { // Access Control against the move source //The result of this.davRsCmp.getParent () is never null since DavFileResource always has a parent (the top is Box) - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); return new DavMoveResource(this.davRsCmp.getParent(), this.davRsCmp.getDavCmp(), headers).doMove(); } @@ -293,7 +293,7 @@ public Response move( @OPTIONS public Response options() { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, HttpMethod.PUT, diff --git a/src/main/java/io/personium/core/rs/box/NullResource.java b/src/main/java/io/personium/core/rs/box/NullResource.java index 6789187ff..99bb08295 100644 --- a/src/main/java/io/personium/core/rs/box/NullResource.java +++ b/src/main/java/io/personium/core/rs/box/NullResource.java @@ -94,7 +94,7 @@ public NullResource(final DavRsCmp parent, final DavCmp davCmp, final boolean is public final Response get() { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ); throw PersoniumCoreException.Dav.RESOURCE_NOT_FOUND.params(this.davRsCmp.getUrl()); } @@ -113,7 +113,7 @@ public final Response put( //Access control if (!this.isParentNull) { - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.BIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.BIND); } //If there is no intermediate path 409 error @@ -191,7 +191,7 @@ public Response mkcol(@HeaderParam(HttpHeaders.CONTENT_TYPE) final String conten //Access control if (!this.isParentNull) { - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.BIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.BIND); } //If there is no intermediate path 409 error @@ -284,7 +284,7 @@ public Object nextPath(@PathParam("nextPath") final String nextPath, public final Response delete() { //Access control if (!this.isParentNull) { - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); } throw PersoniumCoreException.Dav.RESOURCE_NOT_FOUND.params(this.davRsCmp.getUrl()); @@ -297,7 +297,7 @@ public final Response delete() { @POST public final Response post() { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE); throw PersoniumCoreException.Dav.RESOURCE_NOT_FOUND.params(this.davRsCmp.getUrl()); } @@ -309,7 +309,7 @@ public final Response post() { @REPORT public final Response report() { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ); throw PersoniumCoreException.Dav.RESOURCE_NOT_FOUND.params(this.davRsCmp.getUrl()); } @@ -321,7 +321,7 @@ public final Response report() { @PROPFIND public final Response propfind() { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ_PROPERTIES); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ_PROPERTIES); throw PersoniumCoreException.Dav.RESOURCE_NOT_FOUND.params(this.davRsCmp.getUrl()); } @@ -333,7 +333,7 @@ public final Response propfind() { @PROPPATCH public final Response proppatch() { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_PROPERTIES); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE_PROPERTIES); throw PersoniumCoreException.Dav.RESOURCE_NOT_FOUND.params(this.davRsCmp.getUrl()); } @@ -344,9 +344,10 @@ public final Response proppatch() { */ @ACL public final Response acl() { - //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_ACL); - + //Check Access control first. + // and throw access control related exception if the request is not authorized. + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE_ACL); + // If the parent resource is accessible then return not found. throw PersoniumCoreException.Dav.RESOURCE_NOT_FOUND.params(this.davRsCmp.getUrl()); } @@ -358,7 +359,7 @@ public final Response acl() { public final Response move() { //Access control if (!this.isParentNull) { - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); } throw PersoniumCoreException.Dav.RESOURCE_NOT_FOUND.params(this.davRsCmp.getUrl()); diff --git a/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java b/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java index abc4bd0b2..84e5c916a 100644 --- a/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java @@ -84,7 +84,7 @@ public Response propfind(final Reader requestBodyXml, @HeaderParam(HttpHeaders.CONTENT_LENGTH) final Long contentLength, @HeaderParam("Transfer-Encoding") final String transferEncoding) { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ_PROPERTIES); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ_PROPERTIES); Response response = this.davRsCmp.doPropfind(requestBodyXml, depth, contentLength, @@ -195,7 +195,7 @@ public Response delete( boolean recursive = Boolean.valueOf(recursiveHeader); // Check acl. // Since ODataSvcCollectionResource always has a parent, result of this.davRsCmp.getParent() will never be null. - this.davRsCmp.getParent().checkAccessContext(this.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); // If OData schema/data already exists, an error if (!recursive && !this.davRsCmp.getDavCmp().isEmpty()) { @@ -249,13 +249,13 @@ public Response optionsRoot() { public Response move( @Context HttpHeaders headers) { //Access control to move source (check parent's authority) - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); return new DavMoveResource(this.davRsCmp.getParent(), this.davRsCmp.getDavCmp(), headers).doMove(); } @Override public void checkAccessContext(AccessContext ac, Privilege privilege) { - this.davRsCmp.checkAccessContext(ac, privilege); + this.davRsCmp.checkAccessContext(privilege); } /** @@ -275,10 +275,10 @@ public AcceptableAuthScheme getAcceptableAuthScheme() { @Override public boolean hasPrivilegeForBatch(AccessContext ac) { Acl acl = this.davRsCmp.getDavCmp().getAcl(); - if (ac.requirePrivilege(acl, BoxPrivilege.READ)) { + if (ac.hasSubjectPrivilegeForAcl(acl, BoxPrivilege.READ)) { return true; } - if (ac.requirePrivilege(acl, BoxPrivilege.WRITE)) { + if (ac.hasSubjectPrivilegeForAcl(acl, BoxPrivilege.WRITE)) { return true; } return false; @@ -286,7 +286,7 @@ public boolean hasPrivilegeForBatch(AccessContext ac) { @Override public boolean hasPrivilege(AccessContext ac, Privilege privilege) { - return this.davRsCmp.hasPrivilege(ac, privilege); + return this.davRsCmp.hasSubjectPrivilege(privilege); } @Override diff --git a/src/main/java/io/personium/core/rs/box/ODataSvcSchemaResource.java b/src/main/java/io/personium/core/rs/box/ODataSvcSchemaResource.java index 7242e3e2b..6eb906fe0 100644 --- a/src/main/java/io/personium/core/rs/box/ODataSvcSchemaResource.java +++ b/src/main/java/io/personium/core/rs/box/ODataSvcSchemaResource.java @@ -90,7 +90,7 @@ public final class ODataSvcSchemaResource extends ODataResource { @Override public void checkAccessContext(AccessContext ac, Privilege privilege) { - this.davRsCmp.checkAccessContext(ac, privilege); + this.davRsCmp.checkAccessContext(privilege); } /** @@ -104,7 +104,7 @@ public AcceptableAuthScheme getAcceptableAuthScheme() { @Override public boolean hasPrivilege(AccessContext ac, Privilege privilege) { - return this.davRsCmp.hasPrivilege(ac, privilege); + return this.davRsCmp.hasSubjectPrivilege(privilege); } @Override diff --git a/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceCollection.java b/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceCollection.java index 190bbd6fb..e83cac93b 100644 --- a/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceCollection.java +++ b/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceCollection.java @@ -88,7 +88,7 @@ public Response propfind(final Reader requestBodyXml, @HeaderParam(HttpHeaders.CONTENT_LENGTH) final Long contentLength, @HeaderParam("Transfer-Encoding") final String transferEncoding) { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ_PROPERTIES); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ_PROPERTIES); return this.davRsCmp.doPropfind(requestBodyXml, depth, contentLength, transferEncoding, BoxPrivilege.READ_ACL); } @@ -109,8 +109,7 @@ public Response report() { @MOVE public void move() { //Access control - this.davRsCmp.checkAccessContext( - this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE); throw PersoniumCoreException.Dav.SERVICE_SOURCE_COLLECTION_PROHIBITED_TO_MOVE; } @@ -121,7 +120,7 @@ public void move() { @OPTIONS public Response options() { //Access control to move source - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ); return ResourceUtils.responseBuilderForOptions( io.personium.common.utils.CommonUtils.HttpMethod.PROPFIND ).build(); diff --git a/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceFileResource.java b/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceFileResource.java index 73379ec2f..7f946c4ab 100644 --- a/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceFileResource.java +++ b/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceFileResource.java @@ -50,7 +50,7 @@ public PersoniumEngineSourceFileResource(final DavRsCmp parent, final DavCmp dav @ACL public Response acl(final Reader reader) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_ACL); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE_ACL); throw PersoniumCoreException.Dav.METHOD_NOT_ALLOWED; } } diff --git a/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceNullResource.java b/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceNullResource.java index f501d9023..5b3a05b15 100644 --- a/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceNullResource.java +++ b/src/main/java/io/personium/core/rs/box/PersoniumEngineSourceNullResource.java @@ -57,7 +57,7 @@ public Response mkcol(@HeaderParam(HttpHeaders.CONTENT_TYPE) final String conten @HeaderParam("Transfer-Encoding") final String transferEncoding, final InputStream inputStream) { //Access control - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.BIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.BIND); throw PersoniumCoreException.Dav.METHOD_NOT_ALLOWED; } diff --git a/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java index 9c89f37bc..daf7aae3b 100644 --- a/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/PersoniumEngineSvcCollectionResource.java @@ -60,9 +60,9 @@ import org.slf4j.LoggerFactory; 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; import io.personium.core.PersoniumUnitConfig; import io.personium.core.annotations.ACL; import io.personium.core.annotations.MOVE; @@ -118,7 +118,7 @@ public Response propfind(final Reader requestBodyXml, @HeaderParam(HttpHeaders.CONTENT_LENGTH) final Long contentLength, @HeaderParam("Transfer-Encoding") final String transferEncoding) { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ_PROPERTIES); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ_PROPERTIES); Response response = this.davRsCmp.doPropfind(requestBodyXml, depth, contentLength, @@ -170,7 +170,7 @@ public Response delete( boolean recursive = Boolean.valueOf(recursiveHeader); // Check acl.(Parent acl check) // Since DavCollectionResource always has a parent, result of this.davRsCmp.getParent() will never be null. - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); if (!recursive && !this.davRsCmp.getDavCmp().isEmpty()) { throw PersoniumCoreException.Dav.HAS_CHILDREN; @@ -203,7 +203,7 @@ public Response delete( @PROPPATCH public Response proppatch(final Reader requestBodyXml) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_PROPERTIES); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE_PROPERTIES); Response response = this.davRsCmp.doProppatch(requestBodyXml); // post event to EventBus @@ -232,7 +232,7 @@ public Response proppatch(final Reader requestBodyXml) { @ACL public Response acl(final Reader reader) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_ACL); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE_ACL); Response response = this.davCmp.acl(reader).build(); // post event to EventBus @@ -259,7 +259,7 @@ public Response acl(final Reader reader) { @OPTIONS public Response options() { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ); return ResourceUtils.responseBuilderForOptions( HttpMethod.DELETE, io.personium.common.utils.CommonUtils.HttpMethod.MOVE, @@ -297,7 +297,7 @@ public Response relayget(@PathParam("path") String path, @Context final UriInfo uriInfo, @Context HttpHeaders headers) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.EXEC); + this.davRsCmp.checkAccessContext(BoxPrivilege.EXEC); return relaycommon(HttpMethod.GET, uriInfo, path, headers, null); } @@ -317,7 +317,7 @@ public Response relaypost(@PathParam("path") String path, @Context HttpHeaders headers, final InputStream is) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.EXEC); + this.davRsCmp.checkAccessContext(BoxPrivilege.EXEC); return relaycommon(HttpMethod.POST, uriInfo, path, headers, is); } @@ -337,7 +337,7 @@ public Response relayput(@PathParam("path") String path, @Context HttpHeaders headers, final InputStream is) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.EXEC); + this.davRsCmp.checkAccessContext(BoxPrivilege.EXEC); return relaycommon(HttpMethod.PUT, uriInfo, path, headers, is); } @@ -355,7 +355,7 @@ public Response relaydelete(@PathParam("path") String path, @Context final UriInfo uriInfo, @Context HttpHeaders headers) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.EXEC); + this.davRsCmp.checkAccessContext(BoxPrivilege.EXEC); return relaycommon(HttpMethod.DELETE, uriInfo, path, headers, null); } @@ -617,7 +617,7 @@ private void debugRelayHeader(HttpUriRequest req) { public Response move( @Context HttpHeaders headers) { //Access control to move source (check parent's authority) - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); return new DavMoveResource(this.davRsCmp.getParent(), this.davRsCmp.getDavCmp(), headers).doMove(); } } diff --git a/src/main/java/io/personium/core/rs/box/StreamCollectionResource.java b/src/main/java/io/personium/core/rs/box/StreamCollectionResource.java index 3797dc584..76cd02a94 100644 --- a/src/main/java/io/personium/core/rs/box/StreamCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/StreamCollectionResource.java @@ -77,7 +77,7 @@ public Response propfind(final Reader requestBodyXml, @HeaderParam(HttpHeaders.CONTENT_LENGTH) final Long contentLength, @HeaderParam("Transfer-Encoding") final String transferEncoding) { // Access Control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ_PROPERTIES); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ_PROPERTIES); Response response = this.davRsCmp.doPropfind(requestBodyXml, depth, contentLength, @@ -129,7 +129,7 @@ public Response delete( boolean recursive = Boolean.valueOf(recursiveHeader); // Check acl.(Parent acl check) // Since DavCollectionResource always has a parent, result of this.davRsCmp.getParent() will never be null. - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); if (!recursive && !this.davRsCmp.getDavCmp().isEmpty()) { throw PersoniumCoreException.Dav.HAS_CHILDREN; @@ -162,7 +162,7 @@ public Response delete( @PROPPATCH public Response proppatch(final Reader requestBodyXml) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_PROPERTIES); + this.davRsCmp.checkAccessContext( BoxPrivilege.WRITE_PROPERTIES); Response response = this.davRsCmp.doProppatch(requestBodyXml); // post event to EventBus @@ -191,7 +191,7 @@ public Response proppatch(final Reader requestBodyXml) { @ACL public Response acl(final Reader reader) { //Access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_ACL); + this.davRsCmp.checkAccessContext(BoxPrivilege.WRITE_ACL); Response response = this.davCmp.acl(reader).build(); // post event to EventBus @@ -221,7 +221,7 @@ public Response acl(final Reader reader) { public Response move( @Context HttpHeaders headers) { //Access control to move source (check parent's authority) - this.davRsCmp.getParent().checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.UNBIND); + this.davRsCmp.getParent().checkAccessContext(BoxPrivilege.UNBIND); return new DavMoveResource(this.davRsCmp.getParent(), this.davRsCmp.getDavCmp(), headers).doMove(); } @@ -232,7 +232,7 @@ public Response move( @OPTIONS public Response options() { // access control - this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.READ); + this.davRsCmp.checkAccessContext(BoxPrivilege.READ); return ResourceUtils.responseBuilderForOptions( HttpMethod.DELETE, io.personium.common.utils.CommonUtils.HttpMethod.MOVE, 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 25699bd98..53c4c10ef 100644 --- a/src/main/java/io/personium/core/rs/box/StreamResource.java +++ b/src/main/java/io/personium/core/rs/box/StreamResource.java @@ -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"); @@ -216,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); @@ -235,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/cell/BoxUrlResource.java b/src/main/java/io/personium/core/rs/cell/BoxUrlResource.java index cdb6f05d1..64dd7d043 100644 --- a/src/main/java/io/personium/core/rs/cell/BoxUrlResource.java +++ b/src/main/java/io/personium/core/rs/cell/BoxUrlResource.java @@ -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(); 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 eeaf1f3ee..67c83ee39 100644 --- a/src/main/java/io/personium/core/rs/cell/CellCtlResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellCtlResource.java @@ -90,7 +90,7 @@ public AcceptableAuthScheme getAcceptableAuthScheme() { @Override public boolean hasPrivilege(AccessContext ac, Privilege privilege) { - return this.cellRsCmp.hasPrivilege(ac, privilege); + return this.cellRsCmp.hasSubjectPrivilege(privilege); } @Override 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..d8ea86993 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(cellRsCmp.getAccessContext(), CellPrivilege.ROOT); // Get processing status from cache. // If it returns null, it is regarded as ready state. 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 47d08fb17..6cac29cc0 100644 --- a/src/main/java/io/personium/core/rs/cell/CellResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellResource.java @@ -379,7 +379,7 @@ public RuleResource rule() { } /** - * Access to the default box. + * Access to the main box. * @param jaxRsRequest HTTP request for JAX-RS * @return BoxResource Object */ 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 60e494a44..27f2adce4 100644 --- a/src/main/java/io/personium/core/rs/cell/CellSnapshotDavFileResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellSnapshotDavFileResource.java @@ -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(); } @@ -132,7 +132,7 @@ public Response propfind(final Reader requestBodyXml, // 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,7 +154,7 @@ 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, 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 02c36d2cd..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,11 +34,11 @@ import org.slf4j.LoggerFactory; import io.personium.common.auth.token.AbstractOAuth2Token; +import io.personium.common.auth.token.IAccessToken; 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.IAccessToken; import io.personium.common.auth.token.TransCellAccessToken; +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; @@ -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 d7119344d..e80d4a42f 100644 --- a/src/main/java/io/personium/core/rs/cell/LogResource.java +++ b/src/main/java/io/personium/core/rs/cell/LogResource.java @@ -133,7 +133,7 @@ public final Response archivePropfind(final Reader requestBodyXml, ) { //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)) { @@ -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)) { 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 453beedde..74a25038c 100644 --- a/src/main/java/io/personium/core/rs/cell/MessageResource.java +++ b/src/main/java/io/personium/core/rs/cell/MessageResource.java @@ -86,7 +86,7 @@ public Response messages( @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/MyPasswordResource.java b/src/main/java/io/personium/core/rs/cell/MyPasswordResource.java index 30b8892fe..9713a2def 100644 --- a/src/main/java/io/personium/core/rs/cell/MyPasswordResource.java +++ b/src/main/java/io/personium/core/rs/cell/MyPasswordResource.java @@ -73,7 +73,7 @@ public MyPasswordResource(final AccessContext accessContext, @PUT public Response put() { //Access control - this.accessContext.checkMyLocalOrPasswordChangeToken(this.cellRsCmp.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; 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/test/java/io/personium/core/model/BoxUrlRsCmpTest.java b/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java index fb889151c..29c761393 100644 --- a/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java +++ b/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java @@ -72,7 +72,7 @@ public void checkAccessContext_Normal_unit_user_token() { // None. // Run method - boxUrlRsCmp.checkAccessContext(ac, privilege); + boxUrlRsCmp.checkAccessContext(privilege); } /** @@ -98,7 +98,7 @@ public void checkAccessContext_Normal_match_box_schema() throws Exception { // None. // Run method - boxUrlRsCmp.checkAccessContext(ac, privilege); + boxUrlRsCmp.checkAccessContext(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(); // 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/fs/DavCmpFsImplTest.java b/src/test/java/io/personium/core/model/impl/fs/DavCmpFsImplTest.java index 7178c5dd5..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 @@ -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); From 3e2639be9f57722074b233edd16871dddc04d9b5 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Wed, 21 Aug 2019 17:38:38 +0900 Subject: [PATCH 52/69] refactoring: DavRsCmp has an AccessContest. so use it instead of hand it via parameter. --- src/main/java/io/personium/core/model/CellRsCmp.java | 5 ++++- .../java/io/personium/core/rs/cell/CellCtlResource.java | 2 +- .../java/io/personium/core/rs/cell/CellExportResource.java | 6 +++--- .../java/io/personium/core/rs/cell/CellImportResource.java | 6 +++--- src/main/java/io/personium/core/rs/cell/CellResource.java | 6 +++--- .../io/personium/core/rs/cell/CellSnapshotResource.java | 4 ++-- src/main/java/io/personium/core/rs/cell/RuleResource.java | 6 +++--- src/main/java/io/personium/core/ws/WebSocketService.java | 4 ++-- 8 files changed, 21 insertions(+), 18 deletions(-) diff --git a/src/main/java/io/personium/core/model/CellRsCmp.java b/src/main/java/io/personium/core/model/CellRsCmp.java index 3b8048c9d..85fe04286 100644 --- a/src/main/java/io/personium/core/model/CellRsCmp.java +++ b/src/main/java/io/personium/core/model/CellRsCmp.java @@ -128,6 +128,7 @@ public Box getBox() { /** * @return AccessContext */ + @Override public AccessContext getAccessContext() { return this.accessContext; } @@ -155,7 +156,9 @@ public boolean hasSubjectPrivilege(Privilege privilege) { * @param ac Access context * @param privilege Required privilege */ - public void checkAccessContext(AccessContext ac, Privilege privilege) { + @Override + public void checkAccessContext(Privilege privilege) { + AccessContext ac = this.getAccessContext(); // If UnitUser token, then OK. if (ac.isUnitUserToken(privilege)) { return; 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 67c83ee39..6e519736d 100644 --- a/src/main/java/io/personium/core/rs/cell/CellCtlResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellCtlResource.java @@ -76,7 +76,7 @@ public CellCtlResource(final AccessContext accessContext, final String pCredHead @Override public void checkAccessContext(final AccessContext ac, Privilege privilege) { - this.cellRsCmp.checkAccessContext(ac, privilege); + this.cellRsCmp.checkAccessContext(privilege); } /** 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 d8ea86993..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. - this.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 6cac29cc0..c0e09137b 100644 --- a/src/main/java/io/personium/core/rs/cell/CellResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellResource.java @@ -464,7 +464,7 @@ public Response propfind(final Reader requestBodyXml, @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,7 +562,7 @@ 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, CommonUtils.HttpMethod.PROPFIND 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 ea1e7ff74..8b29faf41 100644 --- a/src/main/java/io/personium/core/rs/cell/CellSnapshotResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellSnapshotResource.java @@ -79,7 +79,7 @@ public Response propfind(Reader requestBodyXml, @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,7 +91,7 @@ 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.CommonUtils.HttpMethod.PROPFIND ).build(); 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/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; From 4d0efec9e39f5721fa1d6c7df93c8ee2a27ad5fb Mon Sep 17 00:00:00 2001 From: akioshimono Date: Wed, 21 Aug 2019 18:16:33 +0900 Subject: [PATCH 53/69] refactoring: ODataResource has an AccessContest. so use it instead of hand it via parameter. --- .../personium/core/bar/BarFileInstaller.java | 2 +- .../rs/box/ODataSvcCollectionResource.java | 10 +++++----- .../core/rs/box/ODataSvcSchemaResource.java | 10 +++++----- .../core/rs/cell/CellCtlResource.java | 6 +++--- .../core/rs/odata/ODataBatchResource.java | 9 +++++---- .../core/rs/odata/ODataEntitiesResource.java | 11 +++------- .../core/rs/odata/ODataEntityResource.java | 20 ++++++------------- .../core/rs/odata/ODataLinksResource.java | 18 +++++++---------- .../core/rs/odata/ODataMergeResource.java | 2 +- .../core/rs/odata/ODataPropertyResource.java | 13 +++++------- .../core/rs/odata/ODataResource.java | 19 ++++++++++++------ .../core/rs/unit/UnitCtlResource.java | 14 +++---------- .../core/rs/unit/UnitCtlResourceTest.java | 8 ++++---- 13 files changed, 61 insertions(+), 81 deletions(-) diff --git a/src/main/java/io/personium/core/bar/BarFileInstaller.java b/src/main/java/io/personium/core/bar/BarFileInstaller.java index 701d5f22b..121713a65 100644 --- a/src/main/java/io/personium/core/bar/BarFileInstaller.java +++ b/src/main/java/io/personium/core/bar/BarFileInstaller.java @@ -241,7 +241,7 @@ 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); diff --git a/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java b/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java index 84e5c916a..a149d897b 100644 --- a/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java +++ b/src/main/java/io/personium/core/rs/box/ODataSvcCollectionResource.java @@ -117,7 +117,7 @@ public Response propfind(final Reader requestBodyXml, @PROPPATCH public Response proppatch(final Reader requestBodyXml) { //Access control - this.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.WRITE_PROPERTIES); + this.checkAccessContext(BoxPrivilege.WRITE_PROPERTIES); Response response = this.davRsCmp.doProppatch(requestBodyXml); @@ -156,7 +156,7 @@ public Response report() { @ACL public Response acl(final Reader reader) { //Access control - this.checkAccessContext(this.getAccessContext(), BoxPrivilege.WRITE_ACL); + this.checkAccessContext(BoxPrivilege.WRITE_ACL); Response response = this.davRsCmp.getDavCmp().acl(reader).build(); // post event to EventBus @@ -228,7 +228,7 @@ public Response delete( @OPTIONS public Response optionsRoot() { //Access control - this.checkAccessContext(this.getAccessContext(), BoxPrivilege.READ); + this.checkAccessContext(BoxPrivilege.READ); return ResourceUtils.responseBuilderForOptions( HttpMethod.GET, HttpMethod.DELETE, @@ -254,7 +254,7 @@ public Response move( } @Override - public void checkAccessContext(AccessContext ac, Privilege privilege) { + public void checkAccessContext(Privilege privilege) { this.davRsCmp.checkAccessContext(privilege); } @@ -285,7 +285,7 @@ public boolean hasPrivilegeForBatch(AccessContext ac) { } @Override - public boolean hasPrivilege(AccessContext ac, Privilege privilege) { + public boolean hasPrivilege(Privilege privilege) { return this.davRsCmp.hasSubjectPrivilege(privilege); } diff --git a/src/main/java/io/personium/core/rs/box/ODataSvcSchemaResource.java b/src/main/java/io/personium/core/rs/box/ODataSvcSchemaResource.java index 6eb906fe0..0e35cf95c 100644 --- a/src/main/java/io/personium/core/rs/box/ODataSvcSchemaResource.java +++ b/src/main/java/io/personium/core/rs/box/ODataSvcSchemaResource.java @@ -89,7 +89,7 @@ public final class ODataSvcSchemaResource extends ODataResource { } @Override - public void checkAccessContext(AccessContext ac, Privilege privilege) { + public void checkAccessContext(Privilege privilege) { this.davRsCmp.checkAccessContext(privilege); } @@ -103,7 +103,7 @@ public AcceptableAuthScheme getAcceptableAuthScheme() { } @Override - public boolean hasPrivilege(AccessContext ac, Privilege privilege) { + public boolean hasPrivilege(Privilege privilege) { return this.davRsCmp.hasSubjectPrivilege(privilege); } @@ -125,7 +125,7 @@ public Response getRoot(@Context final UriInfo uriInfo, @QueryParam("$format") final String format, @Context HttpHeaders httpHeaders) { //Access control - this.checkAccessContext(this.getAccessContext(), BoxPrivilege.READ); + this.checkAccessContext(BoxPrivilege.READ); //From the contents of $ format and Accept header, //Should Schema's Atom ServiceDocument be returned? //It is judged whether EDMX of data should be returned or not. @@ -164,7 +164,7 @@ private boolean isAtomSvcRequest(HttpHeaders h) { @Path("{first: \\$}metadata") public Response getMetadata() { //Access control - this.checkAccessContext(this.getAccessContext(), BoxPrivilege.READ); + this.checkAccessContext(BoxPrivilege.READ); //Return EDMX of the schema //Auth header check return super.doGetMetadata(); @@ -179,7 +179,7 @@ public Response getMetadata() { // @Path("") public Response optionsRoot() { //Access control - this.checkAccessContext(this.getAccessContext(), BoxPrivilege.READ); + this.checkAccessContext(BoxPrivilege.READ); return super.doGetOptionsMetadata(); } 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 6e519736d..b4f0d0349 100644 --- a/src/main/java/io/personium/core/rs/cell/CellCtlResource.java +++ b/src/main/java/io/personium/core/rs/cell/CellCtlResource.java @@ -55,7 +55,7 @@ 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; @@ -75,7 +75,7 @@ public CellCtlResource(final AccessContext accessContext, final String pCredHead } @Override - public void checkAccessContext(final AccessContext ac, Privilege privilege) { + public void checkAccessContext(Privilege privilege) { this.cellRsCmp.checkAccessContext(privilege); } @@ -89,7 +89,7 @@ public AcceptableAuthScheme getAcceptableAuthScheme() { } @Override - public boolean hasPrivilege(AccessContext ac, Privilege privilege) { + public boolean hasPrivilege(Privilege privilege) { return this.cellRsCmp.hasSubjectPrivilege(privilege); } 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 3a7254da8..9557719e4 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataEntityResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataEntityResource.java @@ -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,8 +488,7 @@ 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, 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 aa260ce20..716c8c944 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataPropertyResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataPropertyResource.java @@ -55,7 +55,6 @@ 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()); @@ -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/unit/UnitCtlResource.java b/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java index a28ecdae2..98c11ee0f 100644 --- a/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java +++ b/src/main/java/io/personium/core/rs/unit/UnitCtlResource.java @@ -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; } @@ -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; } - - } } 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 a252fd64f..f089e859a 100644 --- a/src/test/java/io/personium/core/rs/unit/UnitCtlResourceTest.java +++ b/src/test/java/io/personium/core/rs/unit/UnitCtlResourceTest.java @@ -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 @@ -289,7 +289,7 @@ public void checkAccessContext_Error_type_local() throws Exception { try { // Run method - unitCtlResource.checkAccessContext(ac, privilege); + unitCtlResource.checkAccessContext(privilege); fail("Not throws exception."); } catch (PersoniumCoreException e) { // Confirm result From 8b192b9f12b64be1204930eb82b5e8b5ac62310a Mon Sep 17 00:00:00 2001 From: akioshimono Date: Wed, 21 Aug 2019 19:07:58 +0900 Subject: [PATCH 54/69] Fix broken tests --- src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java b/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java index 29c761393..7e629eb03 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); @@ -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(); @@ -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); From 872c5d849195e5e16a33166a0c9677e80dc4bd6f Mon Sep 17 00:00:00 2001 From: akioshimono Date: Wed, 21 Aug 2019 19:15:02 +0900 Subject: [PATCH 55/69] Implementation of scope requirement to Cell Level APIs --- src/main/java/io/personium/core/auth/AccessContext.java | 8 +------- src/main/java/io/personium/core/model/CellRsCmp.java | 6 ++++++ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index e39515019..8a98be943 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -967,10 +967,7 @@ private static AccessContext createAccessContext(Cell cell, String requestURIHos * @param cellPriv * @return */ - public boolean hasCellPrivilege(CellPrivilege cellPriv) { - return hasScopeCellPrivilege(cellPriv) && hasSubjectCellPrivilege(cellPriv); - } - private boolean hasScopeCellPrivilege(CellPrivilege cellPriv) { + public boolean hasScopeCellPrivilege(CellPrivilege cellPriv) { for (CellPrivilege scopePriv : this.scopePrivileges) { if (scopePriv.includes(cellPriv)) { return true; @@ -979,7 +976,4 @@ private boolean hasScopeCellPrivilege(CellPrivilege cellPriv) { // TODO scope role check return false; } - private boolean hasSubjectCellPrivilege(CellPrivilege cellPriv) { - return this.hasSubjectPrivilegeForAcl(this.cell.getAcl(), cellPriv); - } } diff --git a/src/main/java/io/personium/core/model/CellRsCmp.java b/src/main/java/io/personium/core/model/CellRsCmp.java index 85fe04286..56ada7c9e 100644 --- a/src/main/java/io/personium/core/model/CellRsCmp.java +++ b/src/main/java/io/personium/core/model/CellRsCmp.java @@ -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; @@ -180,6 +181,11 @@ public void checkAccessContext(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()); + } } /** From d4d137fa47be4c71d5926153bf2313710a07852c Mon Sep 17 00:00:00 2001 From: akioshimono Date: Wed, 21 Aug 2019 19:21:21 +0900 Subject: [PATCH 56/69] Fix PMD warnings --- src/main/java/io/personium/core/auth/ScopeArbitrator.java | 2 +- .../java/io/personium/core/rs/cell/TokenEndPointResource.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/personium/core/auth/ScopeArbitrator.java b/src/main/java/io/personium/core/auth/ScopeArbitrator.java index ed0857d5e..0f3532c26 100644 --- a/src/main/java/io/personium/core/auth/ScopeArbitrator.java +++ b/src/main/java/io/personium/core/auth/ScopeArbitrator.java @@ -116,6 +116,6 @@ private boolean check(String scope) { } private boolean isRole(String scope) { String id = this.cell.roleResourceUrlToId(scope, PersoniumUnitConfig.getBaseUrl()); - return (id != null); + return id != null; } } 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 389d2b3ff..c589db9fc 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -222,7 +222,7 @@ public final Response token(@Context final UriInfo uriInfo, } else if (OAuth2Helper.GrantType.REFRESH_TOKEN.equals(grantType)) { return this.receiveRefresh(target, pOwner, schema, refreshToken, expiresIn, rTokenExpiresIn); } else if (OAuth2Helper.GrantType.AUTHORIZATION_CODE.equals(grantType)) { - return receiveCode(target, pOwner, schema, code, expiresIn, rTokenExpiresIn, scope); + return receiveCode(target, pOwner, schema, code, expiresIn, rTokenExpiresIn); } else { // Call Auth Plugins return this.callAuthPlugins(grantType, formParams, target, pOwner, @@ -445,7 +445,7 @@ public static String clientAuth(final String clientId, final String clientSecret * @return API response */ private Response receiveCode(final String target, String owner, String schema, - final String code, long expiresIn, long rTokenExpiresIn, String[] scope) { + final String code, long expiresIn, long rTokenExpiresIn) { if (code == null) { //If code is not set, it is regarded as a parse error throw PersoniumCoreAuthnException.TOKEN_PARSE_ERROR.realm(this.cell.getUrl()); From 5723f2070858796e0d45ff95b81bc91fbe2517b6 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Wed, 21 Aug 2019 22:22:12 +0900 Subject: [PATCH 57/69] Fix PMD warning --- src/main/java/io/personium/core/bar/BarFileInstaller.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/io/personium/core/bar/BarFileInstaller.java b/src/main/java/io/personium/core/bar/BarFileInstaller.java index 121713a65..ba8862406 100644 --- a/src/main/java/io/personium/core/bar/BarFileInstaller.java +++ b/src/main/java/io/personium/core/bar/BarFileInstaller.java @@ -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(CellPrivilege.BOX_BAR_INSTALL); //[400] Request header format check checkHeaders(headers); - } /** From 05ac00f58b6cb56d0520efa8a81d52399a46462f Mon Sep 17 00:00:00 2001 From: akioshimono Date: Thu, 22 Aug 2019 01:14:52 +0900 Subject: [PATCH 58/69] All OAuth2 tokens should be able to carry scope info. --- pom.xml | 2 +- .../io/personium/core/auth/AccessContext.java | 7 ++ .../personium/core/bar/BarFileInstaller.java | 4 +- .../core/rs/cell/AuthzEndPointResource.java | 2 +- .../core/rs/cell/TokenEndPointResource.java | 34 ++++++---- .../rs/odata/ODataSentMessageResource.java | 3 +- .../core/rule/action/TokenBuilder.java | 19 +++--- .../core/auth/AccessContextTest.java | 10 ++- .../test/jersey/cell/MessageApproveTest.java | 2 +- .../test/jersey/cell/MessageReceivedTest.java | 4 +- .../test/jersey/cell/UnitUserCellTest.java | 8 +-- .../test/jersey/cell/auth/AuthCookieTest.java | 4 +- .../cell/auth/BasicAuthCellLevelTest.java | 2 +- .../auth/BasicAuthDavCollectionLevelTest.java | 66 +++++++++---------- .../auth/BasicAuthSvcCollectionLevelTest.java | 10 +-- .../test/jersey/cell/auth/X509AuthTest.java | 12 ++-- .../cell/auth/token/TokenAcceptanceTest.java | 12 +++- .../jersey/cell/auth/token/TokenTest.java | 34 +++++----- .../test/utils/ReceivedMessageUtils.java | 2 +- 19 files changed, 138 insertions(+), 99 deletions(-) diff --git a/pom.xml b/pom.xml index e58e51faf..34fbcc809 100644 --- a/pom.xml +++ b/pom.xml @@ -32,7 +32,7 @@ io.personium personium-lib-common - 1.5.0 + 1.5.1-SNAPSHOT io.personium diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index 8a98be943..ffbfe4a7a 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -279,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. diff --git a/src/main/java/io/personium/core/bar/BarFileInstaller.java b/src/main/java/io/personium/core/bar/BarFileInstaller.java index ba8862406..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. 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 075ae50ad..e0290f984 100644 --- a/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java @@ -550,7 +550,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); } 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 c589db9fc..00e85b2d3 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -305,20 +305,21 @@ 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. @@ -571,6 +572,9 @@ private Response receiveSaml2(final String target, final String owner, //Authentication is successful ------------------------------- + //TODO + String[] scopes = this.cell.getScopeArbitrator(schema, true).request(tcToken.getScope()).getResults(); + //Create a refresh token based on the authentication information long issuedAt = new Date().getTime(); VisitorRefreshToken rToken = new VisitorRefreshToken( @@ -578,7 +582,7 @@ private Response receiveSaml2(final String target, final String owner, 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); @@ -590,12 +594,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 VisitorLocalAccessToken(issuedAt, expiresIn, getIssuerUrl(), - tcToken.getSubject(), rolesHere, schemaVerified); + 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); } @@ -712,8 +720,8 @@ 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.getScopes() != null && accessToken.getScopes().length > 0) { - resp.put(OAuth2Helper.Key.SCOPE, AbstractOAuth2Token.Scope.toConcatValue(accessToken.getScopes())); + 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()); @@ -875,7 +883,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); @@ -900,11 +908,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( @@ -955,7 +963,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/ODataSentMessageResource.java b/src/main/java/io/personium/core/rs/odata/ODataSentMessageResource.java index 399a6f635..62c5bee5a 100644 --- a/src/main/java/io/personium/core/rs/odata/ODataSentMessageResource.java +++ b/src/main/java/io/personium/core/rs/odata/ODataSentMessageResource.java @@ -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("\\('(.+)'\\)"); 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 92419a49c..b80f33c1d 100644 --- a/src/main/java/io/personium/core/rule/action/TokenBuilder.java +++ b/src/main/java/io/personium/core/rule/action/TokenBuilder.java @@ -127,18 +127,21 @@ public Optional build() { // AccountAccessToken ResidentLocalAccessToken token = new ResidentLocalAccessToken(new Date().getTime(), - cellUrl, - subject, - schema, scope); + this.cellUrl, + this.subject, + this.schema, + this.scope); accessToken = token.toTokenString(); } else { // CellLocalAccessToken VisitorLocalAccessToken token = new VisitorLocalAccessToken(new Date().getTime(), - cellUrl, - subject, - roleList, - schema); + VisitorLocalAccessToken.ACCESS_TOKEN_EXPIRES_MILLISECS, + this.cellUrl, + this.subject, + this.roleList, + this.schema, + this.scope); accessToken = token.toTokenString(); } } else { @@ -149,7 +152,7 @@ public Optional build() { subject, targetCellUrl, roleList, - schema); + schema, scope); accessToken = token.toTokenString(); } diff --git a/src/test/java/io/personium/core/auth/AccessContextTest.java b/src/test/java/io/personium/core/auth/AccessContextTest.java index 8cf987a0f..ff918c8be 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; @@ -278,8 +279,13 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { // Token発行処理 VisitorLocalAccessToken token = new VisitorLocalAccessToken( - UrlUtils.getBaseUrl() + "/cellowner", cell.getOwnerNormalized(), null, - UrlUtils.getBaseUrl() + "/cellowner"); + new Date().getTime(), + VisitorLocalAccessToken.ACCESS_TOKEN_EXPIRES_MILLISECS, + UrlUtils.getBaseUrl() + "/cellowner", + cell.getOwnerNormalized(), + null, + UrlUtils.getBaseUrl() + "/cellowner", + new String[] {"scope"}); // p_cookie_peerとして、ランダムなUUIDを設定する String dcCookiePeer = UUID.randomUUID().toString(); 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 969c26b79..287c4a08e 100644 --- a/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java +++ b/src/test/java/io/personium/test/jersey/cell/MessageApproveTest.java @@ -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 4e07077ec..415dca118 100644 --- a/src/test/java/io/personium/test/jersey/cell/UnitUserCellTest.java +++ b/src/test/java/io/personium/test/jersey/cell/UnitUserCellTest.java @@ -313,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); @@ -593,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(); @@ -611,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(); @@ -792,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/AuthCookieTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthCookieTest.java index ca254af58..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) 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/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 index feb4ef300..f51d7b926 100644 --- 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 @@ -98,7 +98,9 @@ public final void Should_FailRefreshingToken_When_NewClientSpecifiedForTokenWith // Generate AppAuth Token List roleList = new ArrayList(); - TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl, appCellUrl + "#account1", usrCellUrl, roleList ,null); + TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl, appCellUrl + "#account1", + usrCellUrl, roleList, + null, null); // Refresh Token HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), null, appCellUrl, appAuthToken.toTokenString()); @@ -131,7 +133,9 @@ public final void Should_FailRefreshingToken_When_ClientIdNotMatchesSchemaInRefr // Generate AppAuth Token List roleList = new ArrayList(); - TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl1, appCellUrl1 + "#account1", usrCellUrl, roleList ,null); + TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl1, appCellUrl1 + "#account1", + usrCellUrl, roleList, + null, null); // Refresh Token HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl2, appCellUrl1, appAuthToken.toTokenString()); @@ -163,7 +167,9 @@ public final void Should_SuccessRefrehingToken__When_ClientIdMatchesSchemaInRefr // Generate AppAuth Token List roleList = new ArrayList(); - TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl, appCellUrl + "#account1", usrCellUrl, roleList ,null); + TransCellAccessToken appAuthToken = new TransCellAccessToken(appCellUrl, appCellUrl + "#account1", + usrCellUrl, roleList, + null, null); // Refresh Token HttpResponse res = refreshToken(usrCellUrl, clrt.toTokenString(), appCellUrl, appCellUrl, appAuthToken.toTokenString()); 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 6334dbb12..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 @@ -60,6 +60,9 @@ 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. @@ -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) @@ -116,7 +118,7 @@ public TokenTest() { // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) ResidentRefreshToken validToken = new ResidentRefreshToken( issuedAt - AbstractOAuth2Token.SECS_IN_A_DAY * 1000 + MILLISECS_IN_AN_MINITE, - issuer, subject, schema, new String[] {"scope1", "scope2"}); + issuer, subject, schema, SCOPE_SAMPLE); // アプリセルに対して認証 Http.request("authn/refresh-cl.txt") @@ -149,11 +151,12 @@ public TokenTest() { String subject = origIssuer + "#account1"; List origRoleList = new ArrayList(); String schema = ""; + String[] scope = new String[] {"scope"}; // 期限切れでないトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) VisitorRefreshToken validToken = new VisitorRefreshToken( id, issuedAt - AbstractOAuth2Token.SECS_IN_A_DAY * 1000 + MILLISECS_IN_AN_MINITE, - issuer, subject, origIssuer, origRoleList, schema); + issuer, subject, origIssuer, origRoleList, schema, scope); // Refresh Http.request("authn/refresh-cl.txt") .with("remoteCell", TEST_CELL2) @@ -164,7 +167,7 @@ public TokenTest() { // 期限切れのトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) VisitorRefreshToken invalidToken = new VisitorRefreshToken( id, issuedAt - AbstractOAuth2Token.SECS_IN_A_DAY * 1000 - MILLISECS_IN_AN_MINITE, - issuer, subject, origIssuer, origRoleList, schema); + issuer, subject, origIssuer, origRoleList, schema, scope); // Refresh Http.request("authn/refresh-cl.txt") .with("remoteCell", TEST_CELL2) @@ -191,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) @@ -205,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) @@ -258,11 +261,13 @@ 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分余裕を持たせる) 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); @@ -270,7 +275,8 @@ public TokenTest() { // 期限切れのトークンを生成(IT環境の通信時間を考慮して1分余裕を持たせる) 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); @@ -289,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); @@ -302,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); @@ -316,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/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") From 5e4cbe9b2ee170cbbd92f660169b265b9ba94dc4 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Thu, 22 Aug 2019 01:43:02 +0900 Subject: [PATCH 59/69] minor modification of comments and local variable names. --- .../java/io/personium/core/auth/AccessContext.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index ffbfe4a7a..d7d71e6a1 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -150,7 +150,7 @@ private enum InvalidReason { /** CellPrivilege granted for App as scope. */ private Set scopePrivileges = new HashSet<>(); /** Roles granted for App as scope. */ - private Set scopeRole = new HashSet<>(); + private Set scopeRoles = new HashSet<>(); /** confidentialLevel. */ private String confidentialLevel; @@ -555,8 +555,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) { @@ -806,7 +808,7 @@ private static AccessContext createBearerAuthz(String authzHeaderValue, Cell cel } if (scope.startsWith("https://")||scope.startsWith("http://")) { try { - ret.scopeRole.add(new Role(new URL(scope))); + ret.scopeRoles.add(new Role(new URL(scope))); } catch (MalformedURLException e) { throw new RuntimeException(e); } From 6778c8fc2e5d197085079205ce0f80f63cf40b7d Mon Sep 17 00:00:00 2001 From: akioshimono Date: Thu, 22 Aug 2019 10:59:06 +0900 Subject: [PATCH 60/69] minor refactoring --- .../io/personium/core/auth/AccessContext.java | 37 ++++++++++--------- .../core/auth/AccessContextTest.java | 2 +- .../personium/core/model/BoxUrlRsCmpTest.java | 2 +- .../core/rs/cell/CellResourceTest.java | 2 +- .../core/rs/unit/UnitCtlResourceTest.java | 2 +- 5 files changed, 23 insertions(+), 22 deletions(-) diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index d7d71e6a1..ab00a9bbc 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -72,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"; @@ -445,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()) @@ -478,12 +479,12 @@ public void checkResidentLocalOrPasswordChangeToken(AcceptableAuthScheme accepta } 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 if cope lacking - if (TYPE_ACCOUNT.equals(this.getType()) &&!this.hasScopeCellPrivilege(CellPrivilege.AUTH)) { + // 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()); } } @@ -757,7 +758,7 @@ private static AccessContext createBearerAuthz(String authzHeaderValue, Cell cel AccessContext ret = new AccessContext(null, cell, baseUri, uriInfo); if (tk instanceof ResidentLocalAccessToken) { - ret.accessType = TYPE_ACCOUNT; + ret.accessType = TYPE_RESIDENT; //Retrieve role information. String acct = tk.getSubject(); ret.roles = cell.getRoleListForAccount(acct); @@ -774,7 +775,7 @@ private static AccessContext createBearerAuthz(String authzHeaderValue, Cell cel ret.issuer = tk.getIssuer(); } else if (tk instanceof VisitorLocalAccessToken) { VisitorLocalAccessToken clat = (VisitorLocalAccessToken) tk; - ret.accessType = TYPE_LOCAL; + ret.accessType = TYPE_VISITOR; //Acquire roll information and pack it. ret.roles = clat.getRoles(); ret.subject = tk.getSubject(); diff --git a/src/test/java/io/personium/core/auth/AccessContextTest.java b/src/test/java/io/personium/core/auth/AccessContextTest.java index ff918c8be..3c690a4f5 100644 --- a/src/test/java/io/personium/core/auth/AccessContextTest.java +++ b/src/test/java/io/personium/core/auth/AccessContextTest.java @@ -296,7 +296,7 @@ public void testCreateBearerAuthzCellNullParamBearerSpace() { // 第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()); } /** diff --git a/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java b/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java index 7e629eb03..287802827 100644 --- a/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java +++ b/src/test/java/io/personium/core/model/BoxUrlRsCmpTest.java @@ -254,7 +254,7 @@ public void checkAccessContext_Error_not_has_privilege_type_other() throws Excep doReturn(false).when(boxUrlRsCmp).hasSubjectPrivilege(privilege); - doReturn(AccessContext.TYPE_LOCAL).when(ac).getType(); + doReturn(AccessContext.TYPE_VISITOR).when(ac).getType(); // Run method try { 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/unit/UnitCtlResourceTest.java b/src/test/java/io/personium/core/rs/unit/UnitCtlResourceTest.java index f089e859a..320dda11d 100644 --- a/src/test/java/io/personium/core/rs/unit/UnitCtlResourceTest.java +++ b/src/test/java/io/personium/core/rs/unit/UnitCtlResourceTest.java @@ -282,7 +282,7 @@ 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; From 37d556fea1b17fff0e586b14bf64a026d90b74dc Mon Sep 17 00:00:00 2001 From: akioshimono Date: Fri, 23 Aug 2019 09:06:31 +0900 Subject: [PATCH 61/69] set log level to info and reduce the amount of logging --- src/main/resources/logback.xml | 2 +- src/main/resources/personium-log-level.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 From 0979c18e1b88797eb0d57b49d31223cd701c5644 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Fri, 23 Aug 2019 12:11:19 +0900 Subject: [PATCH 62/69] Temporarily disable Scope checks --- src/main/java/io/personium/core/model/CellRsCmp.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/personium/core/model/CellRsCmp.java b/src/main/java/io/personium/core/model/CellRsCmp.java index 56ada7c9e..b48c2628a 100644 --- a/src/main/java/io/personium/core/model/CellRsCmp.java +++ b/src/main/java/io/personium/core/model/CellRsCmp.java @@ -184,7 +184,8 @@ public void checkAccessContext(Privilege privilege) { if (privilege instanceof CellPrivilege && !this.accessContext.hasScopeCellPrivilege((CellPrivilege)privilege)) { - throw PersoniumCoreException.Auth.INSUFFICIENT_SCOPE.params(privilege.getName()); + // TODO Temporarily commenting out. +// throw PersoniumCoreException.Auth.INSUFFICIENT_SCOPE.params(privilege.getName()); } } From 0c23540c0a122de8e296eddad017ebd149913223 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Fri, 23 Aug 2019 20:00:24 +0900 Subject: [PATCH 63/69] minor comment change --- src/main/java/io/personium/core/model/CellRsCmp.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/io/personium/core/model/CellRsCmp.java b/src/main/java/io/personium/core/model/CellRsCmp.java index b48c2628a..a2d9bad19 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. From 1f3e930e2c356a50e06447b05036c3dc00a8be09 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Tue, 27 Aug 2019 12:41:50 +0900 Subject: [PATCH 64/69] Fix for #468 --- .../core/PersoniumCoreAuthnException.java | 17 ++-- .../io/personium/core/auth/OAuth2Helper.java | 13 +++ .../core/rs/cell/TokenEndPointResource.java | 49 +++++++++-- .../resources/personium-messages.properties | 4 +- .../rs/cell/TokenEndPointResourceTest.java | 88 ++++++++++++++++++- .../test/jersey/cell/auth/AuthErrorTest.java | 24 ++--- 6 files changed, 164 insertions(+), 31 deletions(-) diff --git a/src/main/java/io/personium/core/PersoniumCoreAuthnException.java b/src/main/java/io/personium/core/PersoniumCoreAuthnException.java index cdc225fa4..03c44edf7 100644 --- a/src/main/java/io/personium/core/PersoniumCoreAuthnException.java +++ b/src/main/java/io/personium/core/PersoniumCoreAuthnException.java @@ -53,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. @@ -66,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); @@ -127,11 +127,10 @@ public final class PersoniumCoreAuthnException extends PersoniumCoreException { public static final PersoniumCoreAuthnException AUTH_HEADER_IS_INVALID = create("PR400-AN-0018", Error.INVALID_CLIENT); /** - * Password change required. + * Invalid assertion type parameter. */ - public static final PersoniumCoreAuthnException PASSWORD_CHANGE_REQUIRED = - create("PR401-AN-0001", Error.UNAUTHORIZED_CLIENT); - + public static final PersoniumCoreAuthnException INVALID_CLIENT_ASSERTION_TYPE = + create("PR400-AN-0022", Error.INVALID_CLIENT); /** * Authenticated Client does not match the refresh token. */ @@ -142,6 +141,12 @@ public final class PersoniumCoreAuthnException extends PersoniumCoreException { */ 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); + /** diff --git a/src/main/java/io/personium/core/auth/OAuth2Helper.java b/src/main/java/io/personium/core/auth/OAuth2Helper.java index 68a98311a..d90c04e7c 100644 --- a/src/main/java/io/personium/core/auth/OAuth2Helper.java +++ b/src/main/java/io/personium/core/auth/OAuth2Helper.java @@ -211,6 +211,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. */ @@ -300,6 +312,7 @@ public static class Key { * p_owner value. */ public static final String TRUE_STR = "true"; + /** * refresh_token_expires_in. */ 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 00e85b2d3..d6427e294 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -148,6 +148,8 @@ 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(Key.P_COOKIE); @@ -178,9 +180,11 @@ public final Response token(@Context final UriInfo uriInfo, String schema = null; // Authenticate client first if necessary. - // If neither Scope nor authzHeader nor clientId exists, client authentication is not performed. - if (clientId != null || authzHeader != null) { - schema = clientAuth(clientId, clientSecret, authzHeader, cell.getUrl()); + // 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 @@ -350,18 +354,48 @@ private String addTrainlingSlash(final String url) { return url; } + public static String clientAuth( + final String clientId, final String clientSecret, + final String clientAssertionType, final String clientAssertion, + final String authzHeader, final String cellUrl) { + // When clientAssertionType is spesified, + if (clientAssertionType != null || clientAssertion != null) { + // Then clientAssertionType should be valid value. + if (!OAuth2Helper.GrantType.SAML2_BEARER.equals(clientAssertionType)) { + throw PersoniumCoreAuthnException.INVALID_CLIENT_ASSERTION_TYPE.params(OAuth2Helper.GrantType.SAML2_BEARER); + } + // Just ignore clientSecret, authzHeader + // + return clientAuth(clientId, clientAssertion, + null, cellUrl); + } else { + // When clientAssertionType is NOT spesified, + // clientId should be specified. + if (clientId == null) { + throw PersoniumCoreAuthnException.CLIENT_SECRET_ISSUER_MISMATCH.realm(cellUrl); + } + // Then use clientId, clientSecret or authHeader + return clientAuth(clientId, clientSecret, + authzHeader, cellUrl); + + } + } + + /** * Client authentication processing. - * @param clientId Schema + * @param clientId Schema URL. if null is specified then skip check. * @param clientSecret token * @param authzHeader Value of Authorization Header * @param cellUrl Cell URL * @return null: Client authentication failed. */ - public static String clientAuth(final String clientId, final String clientSecret, + public static String clientAuth( + final String clientId, final String clientSecret, final String authzHeader, final String cellUrl) { String targetClientId = clientId; String targetClientSecret = clientSecret; + if (targetClientSecret == null) { targetClientSecret = ""; } @@ -391,7 +425,7 @@ public static String clientAuth(final String clientId, final String clientSecret } catch (TokenParseException e) { //Perth failure PersoniumCoreLog.Auth.TOKEN_PARSE_ERROR.params(e.getMessage()).writeLog(); - throw PersoniumCoreAuthnException.CLIENT_SECRET_PARSE_ERROR.realm( + throw PersoniumCoreAuthnException.CLIENT_ASSERTION_PARSE_ERROR.realm( cellUrl).reason(e); } catch (TokenDsigException e) { //Signature validation error @@ -412,7 +446,8 @@ public static String clientAuth(final String clientId, final String clientSecret } // Confirm that Issuer is equal to ID - if (!targetClientId.equals(tcToken.getIssuer())) { + // if clientId is null, then just skip this check + if (clientId != null && !targetClientId.equals(tcToken.getIssuer())) { throw PersoniumCoreAuthnException.CLIENT_SECRET_ISSUER_MISMATCH.realm(cellUrl); } diff --git a/src/main/resources/personium-messages.properties b/src/main/resources/personium-messages.properties index 1e6234b84..dfc3b03e0 100644 --- a/src/main/resources/personium-messages.properties +++ b/src/main/resources/personium-messages.properties @@ -208,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. @@ -231,7 +231,7 @@ 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. 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 990b6f04d..379d001b6 100644 --- a/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java +++ b/src/test/java/io/personium/core/rs/cell/TokenEndPointResourceTest.java @@ -19,6 +19,7 @@ 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; @@ -68,6 +69,8 @@ import io.personium.common.auth.token.Role; 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; @@ -89,6 +92,7 @@ public class TokenEndPointResourceTest { private TokenEndPointResource tokenEndPointResource; private Cell mockCell; private CellRsCmp mockCellRsCmp; + private UriInfo mockUriInfo; @BeforeClass public static void beforeClass() { @@ -190,6 +194,9 @@ public T getLink(String title, Class linkClass) { this.tokenEndPointResource = PowerMockito.spy(new TokenEndPointResource(mockCell, this.mockCellRsCmp)); + this.mockUriInfo = mock(UriInfo.class); + doReturn(new URI(cellUrl)).when(this.mockUriInfo).getBaseUri(); + } /** @@ -326,9 +333,12 @@ 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 cellUrl = "https://personium/testcell/"; String xForwadedFor = "1.2.3.4"; //PowerMockito.doReturn(cellUrl).when(tokenEndPointResource, "getIssuerUrl"); @@ -338,14 +348,84 @@ public void testToken_password() throws Exception { formParams.add("password", "password"); formParams.add("scope", "root https://personium/appcell/"); - UriInfo uriInfo = mock(UriInfo.class); - doReturn(new URI(cellUrl)).when(uriInfo).getBaseUri(); - Response res = tokenEndPointResource.token(uriInfo, null, formParams, xForwadedFor); + 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/test/jersey/cell/auth/AuthErrorTest.java b/src/test/java/io/personium/test/jersey/cell/auth/AuthErrorTest.java index 4ba426a7e..4c808bd99 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 @@ -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); @@ -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); @@ -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); @@ -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); From 9a2fbd8b04a6a2512f37e72c5d24393d2940ef27 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Tue, 27 Aug 2019 21:55:02 +0900 Subject: [PATCH 65/69] Minor Bug fix --- .../io/personium/core/rs/cell/TokenEndPointResource.java | 5 +++-- .../io/personium/test/jersey/cell/auth/AuthErrorTest.java | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) 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 d6427e294..e9b4f53b0 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -370,8 +370,9 @@ public static String clientAuth( null, cellUrl); } else { // When clientAssertionType is NOT spesified, - // clientId should be specified. - if (clientId == null) { + + // clientId or authz header should be specified. + if (clientId == null && authzHeader == null) { throw PersoniumCoreAuthnException.CLIENT_SECRET_ISSUER_MISMATCH.realm(cellUrl); } // Then use clientId, clientSecret or authHeader 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 4c808bd99..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 @@ -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) From 077610ab74cce7c473ea793d6a4b80c8b2ad8a05 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Thu, 29 Aug 2019 18:23:59 +0900 Subject: [PATCH 66/69] implementation for Issue #470 --- .../personium/core/PersoniumUnitConfig.java | 38 +++++++++++- .../io/personium/core/auth/OAuth2Helper.java | 24 ++++---- .../personium/core/auth/ScopeArbitrator.java | 58 +++++++++---------- .../java/io/personium/core/model/Cell.java | 4 +- .../io/personium/core/model/CellRsCmp.java | 3 +- .../core/rs/cell/AuthzEndPointResource.java | 16 +++-- .../core/rs/cell/TokenEndPointResource.java | 10 ++-- .../personium-unit-config-default.properties | 16 ++++- .../core/auth/ScopeArbitratorTest.java | 18 +++++- 9 files changed, 121 insertions(+), 66 deletions(-) diff --git a/src/main/java/io/personium/core/PersoniumUnitConfig.java b/src/main/java/io/personium/core/PersoniumUnitConfig.java index 35595ea1a..acd459afa 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. @@ -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 + "token.defaultScope.ropc"; + + /** Default scope of token for grant_type=assertion . */ + public static final String TOKEN_DEFAULT_SCOPE_ASSERTION = KEY_ROOT + "token.defaultScope.assertion"; + + /** Default scope of token for grant_type=code . */ + public static final String TOKEN_DEFAULT_SCOPE_CODE = KEY_ROOT + "token.defaultScope.grant_code"; + } /** @@ -1473,6 +1484,29 @@ public static boolean isDavEncryptEnabled() { return Boolean.parseBoolean(get(Security.DAV_ENCRYPT_ENABLED)); } + /** + * + * @return scope string + */ + public static boolean getTokenDefaultScopeRopc() { + return Boolean.parseBoolean(get(Security.TOKEN_DEFAULT_SCOPE_ROPC)); + } + /** + * + * @return scope string + */ + public static boolean getTokenDefaultScopeCode() { + return Boolean.parseBoolean(get(Security.TOKEN_DEFAULT_SCOPE_CODE)); + } + /** + * + * @return scope string + */ + public static boolean getTokenDefaultScopeAssertion() { + return Boolean.parseBoolean(get(Security.TOKEN_DEFAULT_SCOPE_ASSERTION)); + } + + /** * Get message queue implementation of EventBus. * @return message queue diff --git a/src/main/java/io/personium/core/auth/OAuth2Helper.java b/src/main/java/io/personium/core/auth/OAuth2Helper.java index d90c04e7c..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. @@ -21,23 +22,18 @@ 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. */ diff --git a/src/main/java/io/personium/core/auth/ScopeArbitrator.java b/src/main/java/io/personium/core/auth/ScopeArbitrator.java index 0f3532c26..5d718d002 100644 --- a/src/main/java/io/personium/core/auth/ScopeArbitrator.java +++ b/src/main/java/io/personium/core/auth/ScopeArbitrator.java @@ -14,8 +14,7 @@ /** * Class for scope arbitration object. - * Create an instance with Cell and Box information and a flag whether the token - * authentication is done via ROPC or not. + * 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. @@ -33,35 +32,29 @@ 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[] { - CellPrivilege.ROOT.getName(), - CellPrivilege.MESSAGE.getName(), - CellPrivilege.MESSAGE_READ.getName(), - CellPrivilege.EVENT.getName(), - CellPrivilege.EVENT_READ.getName(), - CellPrivilege.ACL.getName(), - CellPrivilege.ACL_READ.getName(), - CellPrivilege.AUTH.getName(), - CellPrivilege.AUTH_READ.getName(), - CellPrivilege.SOCIAL.getName(), - CellPrivilege.SOCIAL_READ.getName(), - CellPrivilege.BOX.getName(), - CellPrivilege.BOX_BAR_INSTALL.getName(), - CellPrivilege.BOX_READ.getName(), - CellPrivilege.LOG.getName(), - CellPrivilege.LOG_READ.getName(), - CellPrivilege.PROPFIND.getName(), - CellPrivilege.RULE.getName(), - CellPrivilege.RULE_READ.getName(), OAuth2Helper.Scope.OPENID })); - public ScopeArbitrator(Cell cell, Box box, boolean ropc) { + public ScopeArbitrator(Cell cell, Box box, String grantType) { this.cell = cell; this.box = box; - this.isRopc = ropc; + this.grantType = grantType; + String unitMaxScopeStr = null; + if (OAuth2Helper.GrantType.PASSWORD.equals(this.grantType)) { + unitMaxScopeStr = PersoniumUnitConfig.get(PersoniumUnitConfig.Security.TOKEN_DEFAULT_SCOPE_ROPC); + } else if (OAuth2Helper.GrantType.AUTHORIZATION_CODE.equals(this.grantType)) { + unitMaxScopeStr = PersoniumUnitConfig.get(PersoniumUnitConfig.Security.TOKEN_DEFAULT_SCOPE_CODE); + } else if (OAuth2Helper.GrantType.SAML2_BEARER.equals(this.grantType)) { + unitMaxScopeStr = PersoniumUnitConfig.get(PersoniumUnitConfig.Security.TOKEN_DEFAULT_SCOPE_ASSERTION); + } else { + unitMaxScopeStr = PersoniumUnitConfig.get(PersoniumUnitConfig.Security.TOKEN_DEFAULT_SCOPE_ROPC); + } + this.unitMaxScopePrivilege = Privilege.get(CellPrivilege.class, unitMaxScopeStr); } public ScopeArbitrator requestString(String requestScopes) { return this.request(AbstractOAuth2Token.Scope.parse(requestScopes)); @@ -72,14 +65,13 @@ public ScopeArbitrator request(String[] requestScopes) { } // remove empty entry this.requestedScopes.remove(""); - if (this.requestedScopes.size() == 0 && this.isRopc) { - // if ROPC and no scope requested then root will be granted. - this.requestedScopes.add("root"); - } 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); @@ -90,6 +82,10 @@ 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://")) { @@ -99,17 +95,19 @@ private boolean check(String scope) { } return false; } + // If not, it should probably be Cell Privilege. // make sure. - if (!VALID_NON_URL_SCOPES.contains(scope)) { + 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.isRopc) { + if (this.unitMaxScopePrivilege != null && this.unitMaxScopePrivilege.includes(cp)) { return true; } - // if not the reject all .. (Tentatively) + // if not then reject all .. (Tentatively) // TODO implement Box configuration to allow Cell Level privilege, and refer to that // setting. return false; diff --git a/src/main/java/io/personium/core/model/Cell.java b/src/main/java/io/personium/core/model/Cell.java index 0cbd262a0..a10a8e108 100644 --- a/src/main/java/io/personium/core/model/Cell.java +++ b/src/main/java/io/personium/core/model/Cell.java @@ -339,9 +339,9 @@ public Box getBoxForSchema(String boxSchema) { } - public ScopeArbitrator getScopeArbitrator(String clientId, boolean isRopc) { + public ScopeArbitrator getScopeArbitrator(String clientId, String grantType) { Box box = this.getBoxForSchema(clientId); - return new ScopeArbitrator(this, box, isRopc); + return new ScopeArbitrator(this, box, grantType); } /** * It gets the Accounts to specify the Account name. diff --git a/src/main/java/io/personium/core/model/CellRsCmp.java b/src/main/java/io/personium/core/model/CellRsCmp.java index a2d9bad19..d09d998ae 100644 --- a/src/main/java/io/personium/core/model/CellRsCmp.java +++ b/src/main/java/io/personium/core/model/CellRsCmp.java @@ -184,8 +184,7 @@ public void checkAccessContext(Privilege privilege) { if (privilege instanceof CellPrivilege && !this.accessContext.hasScopeCellPrivilege((CellPrivilege)privilege)) { - // TODO Temporarily commenting out. -// throw PersoniumCoreException.Auth.INSUFFICIENT_SCOPE.params(privilege.getName()); + throw PersoniumCoreException.Auth.INSUFFICIENT_SCOPE.params(privilege.getName()); } } 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 e0290f984..d7683b896 100644 --- a/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/AuthzEndPointResource.java @@ -77,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; @@ -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); } 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 e9b4f53b0..029c8b45f 100644 --- a/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java +++ b/src/main/java/io/personium/core/rs/cell/TokenEndPointResource.java @@ -309,7 +309,7 @@ private Response callAuthPlugins(String grantType, MultivaluedMap Date: Thu, 29 Aug 2019 23:50:20 +0900 Subject: [PATCH 67/69] bug fix --- .../personium/core/PersoniumUnitConfig.java | 18 +++++++-------- .../io/personium/core/auth/AccessContext.java | 22 +++++++++++++++++++ .../personium/core/auth/ScopeArbitrator.java | 8 +++---- 3 files changed, 35 insertions(+), 13 deletions(-) diff --git a/src/main/java/io/personium/core/PersoniumUnitConfig.java b/src/main/java/io/personium/core/PersoniumUnitConfig.java index acd459afa..dad6bfde4 100644 --- a/src/main/java/io/personium/core/PersoniumUnitConfig.java +++ b/src/main/java/io/personium/core/PersoniumUnitConfig.java @@ -191,13 +191,13 @@ public static final class Security { 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 + "token.defaultScope.ropc"; + 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 + "token.defaultScope.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 + "token.defaultScope.grant_code"; + public static final String TOKEN_DEFAULT_SCOPE_CODE = KEY_ROOT + "security.token.defaultScope.grant_code"; } @@ -1488,22 +1488,22 @@ public static boolean isDavEncryptEnabled() { * * @return scope string */ - public static boolean getTokenDefaultScopeRopc() { - return Boolean.parseBoolean(get(Security.TOKEN_DEFAULT_SCOPE_ROPC)); + public static String getTokenDefaultScopeRopc() { + return get(Security.TOKEN_DEFAULT_SCOPE_ROPC); } /** * * @return scope string */ - public static boolean getTokenDefaultScopeCode() { - return Boolean.parseBoolean(get(Security.TOKEN_DEFAULT_SCOPE_CODE)); + public static String getTokenDefaultScopeCode() { + return get(Security.TOKEN_DEFAULT_SCOPE_CODE); } /** * * @return scope string */ - public static boolean getTokenDefaultScopeAssertion() { - return Boolean.parseBoolean(get(Security.TOKEN_DEFAULT_SCOPE_ASSERTION)); + public static String getTokenDefaultScopeAssertion() { + return get(Security.TOKEN_DEFAULT_SCOPE_ASSERTION); } diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index ab00a9bbc..c25875f82 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -690,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. @@ -983,6 +1002,9 @@ public boolean hasScopeCellPrivilege(CellPrivilege cellPriv) { return true; } } + // if principal:All is granted that privilege then return true; + Acl acl = this.cell.getAcl(); + //acl.allows(this); // TODO scope role check return false; } diff --git a/src/main/java/io/personium/core/auth/ScopeArbitrator.java b/src/main/java/io/personium/core/auth/ScopeArbitrator.java index 5d718d002..561449dda 100644 --- a/src/main/java/io/personium/core/auth/ScopeArbitrator.java +++ b/src/main/java/io/personium/core/auth/ScopeArbitrator.java @@ -46,13 +46,13 @@ public ScopeArbitrator(Cell cell, Box box, String grantType) { this.grantType = grantType; String unitMaxScopeStr = null; if (OAuth2Helper.GrantType.PASSWORD.equals(this.grantType)) { - unitMaxScopeStr = PersoniumUnitConfig.get(PersoniumUnitConfig.Security.TOKEN_DEFAULT_SCOPE_ROPC); + unitMaxScopeStr = PersoniumUnitConfig.getTokenDefaultScopeRopc(); } else if (OAuth2Helper.GrantType.AUTHORIZATION_CODE.equals(this.grantType)) { - unitMaxScopeStr = PersoniumUnitConfig.get(PersoniumUnitConfig.Security.TOKEN_DEFAULT_SCOPE_CODE); + unitMaxScopeStr = PersoniumUnitConfig.getTokenDefaultScopeCode(); } else if (OAuth2Helper.GrantType.SAML2_BEARER.equals(this.grantType)) { - unitMaxScopeStr = PersoniumUnitConfig.get(PersoniumUnitConfig.Security.TOKEN_DEFAULT_SCOPE_ASSERTION); + unitMaxScopeStr = PersoniumUnitConfig.getTokenDefaultScopeAssertion(); } else { - unitMaxScopeStr = PersoniumUnitConfig.get(PersoniumUnitConfig.Security.TOKEN_DEFAULT_SCOPE_ROPC); + unitMaxScopeStr = PersoniumUnitConfig.getTokenDefaultScopeRopc(); } this.unitMaxScopePrivilege = Privilege.get(CellPrivilege.class, unitMaxScopeStr); } From d7cecaf291a6adfdec2b0b3572e935f2ee9e6040 Mon Sep 17 00:00:00 2001 From: akioshimono Date: Sat, 31 Aug 2019 04:14:10 +0900 Subject: [PATCH 68/69] modification of CHANGELOG and removing unnessesary codes --- CHANGELOG.md | 15 ++++++++++++--- .../io/personium/core/auth/AccessContext.java | 3 --- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57286b508..df70e8eb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,18 @@ ## 1.7.18 -IMPROVEMENTS: -* Limit Cell Level API Access to tokens issued via ROPC process. ([#445](https://github.com/personium/personium-core/issues/445)) +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)) -* Token refreshing between apps disabled. ([#463](https://github.com/personium/personium-core/issues/463)) +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: diff --git a/src/main/java/io/personium/core/auth/AccessContext.java b/src/main/java/io/personium/core/auth/AccessContext.java index c25875f82..d5b853821 100644 --- a/src/main/java/io/personium/core/auth/AccessContext.java +++ b/src/main/java/io/personium/core/auth/AccessContext.java @@ -1002,9 +1002,6 @@ public boolean hasScopeCellPrivilege(CellPrivilege cellPriv) { return true; } } - // if principal:All is granted that privilege then return true; - Acl acl = this.cell.getAcl(); - //acl.allows(this); // TODO scope role check return false; } From 6f70b7826f54a34d480f6d174fdd7b754fe4ee4c Mon Sep 17 00:00:00 2001 From: akioshimono Date: Mon, 2 Sep 2019 12:41:47 +0900 Subject: [PATCH 69/69] For 1.7.18 release --- pom.xml | 2 +- .../personium-unit-config-default.properties | 11 +++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index 34fbcc809..d07da3cf5 100644 --- a/pom.xml +++ b/pom.xml @@ -32,7 +32,7 @@ io.personium personium-lib-common - 1.5.1-SNAPSHOT + 1.5.1 io.personium diff --git a/src/main/resources/personium-unit-config-default.properties b/src/main/resources/personium-unit-config-default.properties index 7e876b173..1bf46bea6 100644 --- a/src/main/resources/personium-unit-config-default.properties +++ b/src/main/resources/personium-unit-config-default.properties @@ -78,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 @@ -86,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 @@ -99,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 @@ -111,6 +108,8 @@ 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