From 8163e073f223ec44bdaaea1c7906c7afb1a58c9c Mon Sep 17 00:00:00 2001 From: lprimak Date: Wed, 19 Aug 2026 19:48:37 -0500 Subject: [PATCH 1/5] bugfix: added formDataKey= in resubmit check --- .../java/org/apache/shiro/ee/filters/FormResubmitSupport.java | 3 ++- .../org/apache/shiro/ee/filters/FormResubmitValidator.java | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java index 20e8b6108f..7edbb7b20e 100644 --- a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java +++ b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java @@ -109,6 +109,7 @@ public class FormResubmitSupport { static final String FORM_RESUBMIT_WHITELIST = "org.apache.shiro.form-resubmit-whitelist"; static final String FORM_RESUBMIT_BLACKLIST = "org.apache.shiro.form-resubmit-blacklist"; static final String FORM_DATA_CACHE = "org.apache.shiro.form-data-cache"; + static final String FORM_DATA_KEY_PREFIX = "formDataKey="; // encoded view state private static final String FACES_VIEW_STATE = "jakarta.faces.ViewState"; private static final String FACES_VIEW_STATE_EQUALS = FACES_VIEW_STATE + "="; @@ -742,7 +743,7 @@ private static boolean checkWhitelistClient(URI savedRequestURI, String contextP contextPath, FORM_RESUBMIT_CHECK_SERVLET_PATH))) .timeout(Duration.ofSeconds(3)).header(CONTENT_TYPE, "text/plain") .POST(HttpRequest.BodyPublishers.ofString(rememberMeManager.getCipherService() - .encrypt(savedFormDataKey.getBytes(StandardCharsets.UTF_8), + .encrypt((FORM_DATA_KEY_PREFIX + savedFormDataKey).getBytes(StandardCharsets.UTF_8), rememberMeManager.getEncryptionCipherKey()).toBase64())).build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); diff --git a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitValidator.java b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitValidator.java index 72ec2f5472..07cade479b 100644 --- a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitValidator.java +++ b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitValidator.java @@ -31,6 +31,7 @@ import java.util.stream.Collectors; import static org.apache.shiro.SecurityUtils.getSecurityManager; import static org.apache.shiro.ee.filters.FormResubmitSupport.FORM_DATA_CACHE; +import static org.apache.shiro.ee.filters.FormResubmitSupport.FORM_DATA_KEY_PREFIX; import static org.apache.shiro.ee.filters.FormResubmitSupport.decrypt; import static org.apache.shiro.ee.filters.FormResubmitSupport.getRememberMeManager; import static org.apache.shiro.web.filter.authc.NoAccessFilter.FORM_RESUBMIT_CHECK_SERVLET_PATH; @@ -45,7 +46,8 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { try { - String formDataKey = decrypt(request.getReader().lines().collect(Collectors.joining()), rememberMeManager); + String formDataKey = decrypt(request.getReader().lines().collect(Collectors.joining()), rememberMeManager) + .substring(FORM_DATA_KEY_PREFIX.length()); var cache = getSecurityManager(DefaultSecurityManager.class) .getCacheManager().getCache(FORM_DATA_CACHE); Optional.ofNullable(cache.get(UUID.fromString(formDataKey))).orElseThrow(IllegalCallerException::new); From 396404c8ea6fe39e31a20fd3aef3df51c9ce1818 Mon Sep 17 00:00:00 2001 From: lprimak Date: Wed, 19 Aug 2026 19:54:02 -0500 Subject: [PATCH 2/5] bugfix: set rememberMe deletion cookie up correctly --- .../main/java/org/apache/shiro/web/servlet/SimpleCookie.java | 5 ++--- .../apache/shiro/web/mgt/CookieRememberMeManagerTest.java | 2 ++ 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/web/src/main/java/org/apache/shiro/web/servlet/SimpleCookie.java b/web/src/main/java/org/apache/shiro/web/servlet/SimpleCookie.java index d7d2644a3c..961c728dc2 100644 --- a/web/src/main/java/org/apache/shiro/web/servlet/SimpleCookie.java +++ b/web/src/main/java/org/apache/shiro/web/servlet/SimpleCookie.java @@ -423,7 +423,6 @@ private static String toCookieDate(Date date) { @Override public void removeFrom(HttpServletRequest request, HttpServletResponse response) { String name = getName(); - String value = DELETED_COOKIE_VALUE; //don't need to add extra size to the response - comments are irrelevant for deletions String comment = null; String domain = getDomain(); @@ -431,12 +430,12 @@ public void removeFrom(HttpServletRequest request, HttpServletResponse response) //always zero for deletion int maxAge = 0; int version = getVersion(); - boolean secure = isSecure(); + boolean secure = isSecure() && request.isSecure(); //no need to add the extra text, plus the value 'deleteMe' is not sensitive at all boolean httpOnly = false; SameSiteOptions sameSite = getSameSite(); - addCookieHeader(response, name, value, null, domain, path, maxAge, version, secure, httpOnly, sameSite); + addCookieHeader(response, name, DELETED_COOKIE_VALUE, null, domain, path, maxAge, version, secure, httpOnly, sameSite); LOGGER.trace("Removed '{}' cookie by setting maxAge=0", name); } diff --git a/web/src/test/java/org/apache/shiro/web/mgt/CookieRememberMeManagerTest.java b/web/src/test/java/org/apache/shiro/web/mgt/CookieRememberMeManagerTest.java index 60043aecfc..73288ba080 100644 --- a/web/src/test/java/org/apache/shiro/web/mgt/CookieRememberMeManagerTest.java +++ b/web/src/test/java/org/apache/shiro/web/mgt/CookieRememberMeManagerTest.java @@ -241,6 +241,7 @@ void getRememberedPrincipalsNoMoreDefaultCipher() { }; expect(mockRequest.getCookies()).andReturn(cookies); + expect(mockRequest.isSecure()).andReturn(false); replay(mockRequest); CookieRememberMeManager mgr = new CookieRememberMeManager(); @@ -350,6 +351,7 @@ void shouldIgnoreInvalidCookieValues() { expect(mockRequest.getAttribute(ShiroHttpServletRequest.IDENTITY_REMOVED_KEY)).andReturn(null); expect(mockRequest.getContextPath()).andReturn(null); expect(mockRequest.getCookies()).andReturn(cookies); + expect(mockRequest.isSecure()).andReturn(false); replay(mockRequest); // when From c8599d20fb6ac8e35944923018a936a4aa91d299 Mon Sep 17 00:00:00 2001 From: lprimak Date: Wed, 19 Aug 2026 20:35:13 -0500 Subject: [PATCH 3/5] bugfix: improve cookie handling in form resubmission support --- .../shiro/ee/filters/FormResubmitSupport.java | 2 +- .../ee/filters/FormResubmitSupportCookies.java | 17 +++++++++++++++-- .../shiro/ee/filters/FormSupportTest.java | 18 +++++++++++++++--- 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java index 7edbb7b20e..c3e78686b6 100644 --- a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java +++ b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupport.java @@ -573,7 +573,7 @@ private static String processResubmitResponse(HttpResponse response, .entrySet().stream().filter(not(entry -> entry.getKey() .startsWith(getSessionCookieName(servletContext, getSecurityManager())))) .forEach(entry -> addCookie(originalResponse, servletContext, - entry.getKey(), entry.getValue(), -1, false)); + entry.getKey(), entry.getValue())); if ((response.statusCode() == FOUND || redirect) && isPartialAjaxRequest) { originalResponse.setHeader(CONTENT_TYPE, TEXT_XML); originalResponse.setCharacterEncoding(StandardCharsets.UTF_8.name()); diff --git a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupportCookies.java b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupportCookies.java index a0f7df7b8a..d4f381a4a8 100644 --- a/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupportCookies.java +++ b/support/jakarta-ee/src/main/java/org/apache/shiro/ee/filters/FormResubmitSupportCookies.java @@ -22,6 +22,7 @@ import java.time.Duration; import java.util.List; import java.util.Map; +import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import jakarta.servlet.ServletContext; @@ -59,6 +60,18 @@ static void addCookie(@NonNull HttpServletResponse response, ServletContext serv response.addCookie(cookie); } + static void addCookie(@NonNull HttpServletResponse response, ServletContext servletContext, + @NonNull String cookieName, @NonNull HttpCookie inputCookie) { + var cookie = new Cookie(cookieName, inputCookie.getValue()); + cookie.setPath(inputCookie.getPath() != null ? inputCookie.getPath() : servletContext.getContextPath()); + cookie.setMaxAge(Math.toIntExact(inputCookie.getMaxAge())); + cookie.setHttpOnly(inputCookie.isHttpOnly()); + if (EnvironmentLoaderListener.isFormResubmitSecureCookies(servletContext)) { + cookie.setSecure(true); + } + response.addCookie(cookie); + } + static void deleteCookie(@NonNull HttpServletResponse response, ServletContext servletContext, @NonNull String cookieName) { var cookieToDelete = new Cookie(cookieName, "tbd"); @@ -94,9 +107,9 @@ static String getSessionCookieName(ServletContext context, org.apache.shiro.mgt. } } - static Map transformCookieHeader(@NonNull List cookies) { + static Map transformCookieHeader(@NonNull List cookies) { return cookieStreamFromHeader(cookies) - .collect(Collectors.toMap(HttpCookie::getName, HttpCookie::getValue, (var, v2) -> v2)); + .collect(Collectors.toMap(HttpCookie::getName, Function.identity(), (var, v2) -> v2)); } static Stream cookieStreamFromHeader(@NonNull List cookies) { diff --git a/support/jakarta-ee/src/test/java/org/apache/shiro/ee/filters/FormSupportTest.java b/support/jakarta-ee/src/test/java/org/apache/shiro/ee/filters/FormSupportTest.java index 4ff4cfc5ae..36ab39bf52 100644 --- a/support/jakarta-ee/src/test/java/org/apache/shiro/ee/filters/FormSupportTest.java +++ b/support/jakarta-ee/src/test/java/org/apache/shiro/ee/filters/FormSupportTest.java @@ -23,11 +23,13 @@ import static org.apache.shiro.ee.filters.FormResubmitSupport.noJSFAjaxRequests; import static org.apache.shiro.ee.filters.FormResubmitSupportCookies.transformCookieHeader; +import java.net.HttpCookie; import java.net.URLDecoder; import java.time.Duration; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import jakarta.servlet.http.HttpServletRequest; import static org.assertj.core.api.Assertions.assertThat; @@ -327,11 +329,21 @@ void clientSideStateSavingNoAjax() { @Test void parseCookies() { - var map = Map.of("name1", "value1", "name2", "value2", "name3", "value3"); + var map = Map.of("name1", "value1", "name2", "value2", "name3", "value3") + .entrySet().stream() + .collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, + entry -> { + var cookie = new HttpCookie(entry.getKey(), entry.getValue()); + if (entry.getKey().equals("name2")) { + cookie.setPath("/my/path"); + } + return cookie; + })); + assertThat(transformCookieHeader(List.of("name1=value1", "name2=value2; path=/my/path", "name3=value3"))).isEqualTo(map); - assertThat(transformCookieHeader(List.of("name="))).isEqualTo(Map.of("name", "")); + assertThat(transformCookieHeader(List.of("name="))).isEqualTo(Map.of("name", new HttpCookie("name", ""))); assertThat(transformCookieHeader(List.of("JSESSIONID=\"abc\"; $Version=\"1\"; $Path=\"/mypath\""))) - .isEqualTo(Map.of("JSESSIONID", "abc")); + .isEqualTo(Map.of("JSESSIONID", new HttpCookie("JSESSIONID", "abc"))); } @Test From 8ba4786b36dbcc6abcdb4fe429a4c4de3913fb2a Mon Sep 17 00:00:00 2001 From: lprimak Date: Wed, 19 Aug 2026 21:51:05 -0500 Subject: [PATCH 4/5] bugfix: removed unnecessary setCredentialsMatcher() call in DefaultLdapRealm --- .../java/org/apache/shiro/realm/ldap/DefaultLdapRealm.java | 3 --- .../org/apache/shiro/realm/ldap/DefaultLdapRealmTest.java | 4 ++-- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/core/src/main/java/org/apache/shiro/realm/ldap/DefaultLdapRealm.java b/core/src/main/java/org/apache/shiro/realm/ldap/DefaultLdapRealm.java index b0a0199797..4856b3d075 100644 --- a/core/src/main/java/org/apache/shiro/realm/ldap/DefaultLdapRealm.java +++ b/core/src/main/java/org/apache/shiro/realm/ldap/DefaultLdapRealm.java @@ -22,7 +22,6 @@ import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; -import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.ldap.UnsupportedAuthenticationMechanismException; @@ -109,8 +108,6 @@ public class DefaultLdapRealm extends AuthorizingRealm { * {@link JndiLdapContextFactory}. */ public DefaultLdapRealm() { - //Credentials Matching is not necessary - the LDAP directory will do it automatically: - setCredentialsMatcher(new AllowAllCredentialsMatcher()); //Any Object principal and Object credentials may be passed to the LDAP provider, so accept any token: setAuthenticationTokenClass(AuthenticationToken.class); this.contextFactory = new JndiLdapContextFactory(); diff --git a/core/src/test/java/org/apache/shiro/realm/ldap/DefaultLdapRealmTest.java b/core/src/test/java/org/apache/shiro/realm/ldap/DefaultLdapRealmTest.java index f2ab25f5d0..ea1be3403f 100644 --- a/core/src/test/java/org/apache/shiro/realm/ldap/DefaultLdapRealmTest.java +++ b/core/src/test/java/org/apache/shiro/realm/ldap/DefaultLdapRealmTest.java @@ -21,7 +21,7 @@ import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.UsernamePasswordToken; -import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher; +import org.apache.shiro.authc.credential.SimpleCredentialsMatcher; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -61,7 +61,7 @@ public void setUp() { @Test void testDefaultInstance() { - assertThat(realm.getCredentialsMatcher() instanceof AllowAllCredentialsMatcher).isTrue(); + assertThat(realm.getCredentialsMatcher() instanceof SimpleCredentialsMatcher).isTrue(); assertThat(realm.getAuthenticationTokenClass()).isEqualTo(AuthenticationToken.class); assertThat(realm.getContextFactory() instanceof JndiLdapContextFactory).isTrue(); } From 098733e7dd2f715de454a8d2b96ac80fb16e4f2d Mon Sep 17 00:00:00 2001 From: lprimak Date: Wed, 19 Aug 2026 21:52:11 -0500 Subject: [PATCH 5/5] chore: fix line endings in mvnw.cmd --- mvnw.cmd | 378 +++++++++++++++++++++++++++---------------------------- 1 file changed, 189 insertions(+), 189 deletions(-) diff --git a/mvnw.cmd b/mvnw.cmd index 5761d94892..92450f9327 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -1,189 +1,189 @@ -<# : batch portion -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Apache Maven Wrapper startup batch script, version 3.3.4 -@REM -@REM Optional ENV vars -@REM MVNW_REPOURL - repo url base for downloading maven distribution -@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output -@REM ---------------------------------------------------------------------------- - -@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) -@SET __MVNW_CMD__= -@SET __MVNW_ERROR__= -@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% -@SET PSModulePath= -@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( - IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) -) -@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% -@SET __MVNW_PSMODULEP_SAVE= -@SET __MVNW_ARG0_NAME__= -@SET MVNW_USERNAME= -@SET MVNW_PASSWORD= -@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) -@echo Cannot start maven from wrapper >&2 && exit /b 1 -@GOTO :EOF -: end batch / begin powershell #> - -$ErrorActionPreference = "Stop" -if ($env:MVNW_VERBOSE -eq "true") { - $VerbosePreference = "Continue" -} - -# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties -$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl -if (!$distributionUrl) { - Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" -} - -switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { - "maven-mvnd-*" { - $USE_MVND = $true - $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" - $MVN_CMD = "mvnd.cmd" - break - } - default { - $USE_MVND = $false - $MVN_CMD = $script -replace '^mvnw','mvn' - break - } -} - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ -if ($env:MVNW_REPOURL) { - $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } - $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" -} -$distributionUrlName = $distributionUrl -replace '^.*/','' -$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' - -$MAVEN_M2_PATH = "$HOME/.m2" -if ($env:MAVEN_USER_HOME) { - $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" -} - -if (-not (Test-Path -Path $MAVEN_M2_PATH)) { - New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null -} - -$MAVEN_WRAPPER_DISTS = $null -if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { - $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" -} else { - $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" -} - -$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" -$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' -$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" - -if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { - Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" - Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" - exit $? -} - -if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { - Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" -} - -# prepare tmp dir -$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile -$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" -$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null -trap { - if ($TMP_DOWNLOAD_DIR.Exists) { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } - } -} - -New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null - -# Download and Install Apache Maven -Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -Write-Verbose "Downloading from: $distributionUrl" -Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -$webclient = New-Object System.Net.WebClient -if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { - $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) -} -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum -if ($distributionSha256Sum) { - if ($USE_MVND) { - Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." - } - Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash - if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { - Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." - } -} - -# unzip and move -Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null - -# Find the actual extracted directory name (handles snapshots where filename != directory name) -$actualDistributionDir = "" - -# First try the expected directory name (for regular distributions) -$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" -$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" -if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { - $actualDistributionDir = $distributionUrlNameMain -} - -# If not found, search for any directory with the Maven executable (for snapshots) -if (!$actualDistributionDir) { - Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { - $testPath = Join-Path $_.FullName "bin/$MVN_CMD" - if (Test-Path -Path $testPath -PathType Leaf) { - $actualDistributionDir = $_.Name - } - } -} - -if (!$actualDistributionDir) { - Write-Error "Could not find Maven distribution directory in extracted archive" -} - -Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" -Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null -try { - Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null -} catch { - if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { - Write-Error "fail to move MAVEN_HOME" - } -} finally { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } -} - -Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.4 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"