Browse Source

Merge e57db098b7 into b3279cb974

pull/15627/merge
Oleksandra Matviienko 3 hours ago
committed by GitHub
parent
commit
aa1da7b274
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 4
      application/src/main/java/org/thingsboard/server/controller/AdminController.java
  2. 2
      application/src/main/java/org/thingsboard/server/service/sync/vc/DefaultEntitiesVersionControlService.java
  3. 13
      common/util/src/main/java/org/thingsboard/common/util/SsrfProtectionValidator.java
  4. 85
      common/util/src/test/java/org/thingsboard/common/util/SsrfProtectionValidatorTest.java
  5. 72
      common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java
  6. 19
      common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java
  7. 43
      common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProvider.java
  8. 67
      common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidator.java
  9. 103
      common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProviderTest.java
  10. 227
      common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidatorTest.java

4
application/src/main/java/org/thingsboard/server/controller/AdminController.java

@ -293,7 +293,7 @@ public class AdminController extends BaseController {
@PostMapping("/repositorySettings")
public DeferredResult<RepositorySettings> saveRepositorySettings(@RequestBody RepositorySettings settings) throws ThingsboardException {
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.WRITE);
settings.setLocalOnly(false); // only to be used in tests
settings.setLocalOnly(false); // force off for the tenant API: localOnly bypasses RepositoryUriValidator, so it must never be tenant-controlled (part of the SSRF defense)
ListenableFuture<RepositorySettings> future = versionControlService.saveVersionControlSettings(getTenantId(), settings);
return wrapFuture(Futures.transform(future, savedSettings -> {
savedSettings.setPassword(null);
@ -322,7 +322,7 @@ public class AdminController extends BaseController {
@Parameter(description = "A JSON value representing the Repository Settings.")
@RequestBody RepositorySettings settings) throws Exception {
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ);
settings.setLocalOnly(false); // only to be used in tests
settings.setLocalOnly(false); // force off for the tenant API: localOnly bypasses RepositoryUriValidator, so it must never be tenant-controlled (part of the SSRF defense)
return wrapFuture(versionControlService.checkVersionControlAccess(getTenantId(), settings), vcRequestTimeout);
}

2
application/src/main/java/org/thingsboard/server/service/sync/vc/DefaultEntitiesVersionControlService.java

@ -502,6 +502,7 @@ public class DefaultEntitiesVersionControlService implements EntitiesVersionCont
@Override
public ListenableFuture<RepositorySettings> saveVersionControlSettings(TenantId tenantId, RepositorySettings versionControlSettings) {
checkBranchName(versionControlSettings.getDefaultBranch());
RepositoryUriValidator.validate(versionControlSettings);
var restoredSettings = this.repositorySettingsService.restore(tenantId, versionControlSettings);
try {
var future = gitServiceQueue.initRepository(tenantId, restoredSettings);
@ -522,6 +523,7 @@ public class DefaultEntitiesVersionControlService implements EntitiesVersionCont
@Override
public ListenableFuture<Void> checkVersionControlAccess(TenantId tenantId, RepositorySettings settings) throws ThingsboardException {
checkBranchName(settings.getDefaultBranch());
RepositoryUriValidator.validate(settings);
settings = this.repositorySettingsService.restore(tenantId, settings);
try {
return gitServiceQueue.testRepository(tenantId, settings);

13
common/util/src/main/java/org/thingsboard/common/util/SsrfProtectionValidator.java

@ -48,7 +48,18 @@ public class SsrfProtectionValidator {
throw new RuntimeException("URI is invalid: only HTTP and HTTPS schemes are allowed, got: " + scheme);
}
String host = uri.getHost();
validateHost(uri.getHost(), ssrfProtectionEnabled);
}
public static void validateHost(String host) {
validateHost(host, enabled);
}
static void validateHost(String host, boolean ssrfProtectionEnabled) {
if (!ssrfProtectionEnabled) {
return;
}
if (host == null || host.isEmpty()) {
throw new RuntimeException("URI is invalid: hostname is missing");
}

85
common/util/src/test/java/org/thingsboard/common/util/SsrfProtectionValidatorTest.java

@ -564,4 +564,89 @@ public class SsrfProtectionValidatorTest {
}
}
// --- validateHost(String) direct tests ---
@ParameterizedTest
@ValueSource(strings = {"example.com", "8.8.8.8", "github.com"})
void testValidateHostAllowsPublicHosts(String host) {
assertThatNoException().isThrownBy(() -> SsrfProtectionValidator.validateHost(host, true));
}
@ParameterizedTest
@ValueSource(strings = {"127.0.0.1", "10.0.0.1", "192.168.1.1", "172.16.0.1", "169.254.169.254", "0.0.0.0"})
void testValidateHostBlocksPrivateIps(String host) {
assertThatThrownBy(() -> SsrfProtectionValidator.validateHost(host, true))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("URI is invalid");
}
@Test
void testValidateHostBlocksLocalhost() {
assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("localhost", true))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("URI is invalid");
}
@Test
void testValidateHostBlocksIpv6Loopback() {
assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("::1", true))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("URI is invalid");
assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("[::1]", true))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("URI is invalid");
}
@Test
void testValidateHostBlocksInternalSuffix() {
assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("server.internal", true))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("URI is invalid");
assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("app.local", true))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("URI is invalid");
}
@Test
void testValidateHostRejectsNullOrEmpty() {
assertThatThrownBy(() -> SsrfProtectionValidator.validateHost(null, true))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("hostname is missing");
assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("", true))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("hostname is missing");
}
@Test
void testValidateHostDisabledSkipsAllChecks() {
// Even with private IP and null host, validation is a no-op when disabled
assertThatNoException().isThrownBy(() -> SsrfProtectionValidator.validateHost("127.0.0.1", false));
assertThatNoException().isThrownBy(() -> SsrfProtectionValidator.validateHost(null, false));
}
@Test
void testValidateHostHonorsAllowList() {
try {
SsrfProtectionValidator.setAllowedHosts(List.of("10.0.0.0/8"));
assertThatNoException().isThrownBy(() -> SsrfProtectionValidator.validateHost("10.1.2.3", true));
} finally {
SsrfProtectionValidator.setAllowedHosts(Collections.emptyList());
}
}
@Test
void testValidateHostUsesStaticEnabledFlag() {
boolean original = SsrfProtectionValidator.isEnabled();
try {
SsrfProtectionValidator.setEnabled(true);
assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("127.0.0.1"))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("URI is invalid");
SsrfProtectionValidator.setEnabled(false);
assertThatNoException().isThrownBy(() -> SsrfProtectionValidator.validateHost("127.0.0.1"));
} finally {
SsrfProtectionValidator.setEnabled(original);
}
}
}

72
common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java

@ -7,6 +7,12 @@ import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.SystemReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
@ -55,6 +61,72 @@ public class DefaultGitRepositoryService implements GitRepositoryService {
if (StringUtils.isEmpty(repositoriesFolder)) {
repositoriesFolder = defaultFolder;
}
installRedirectHardeningSystemReader();
}
private static synchronized void installRedirectHardeningSystemReader() {
SystemReader current = SystemReader.getInstance();
if (current instanceof RedirectHardeningSystemReader) {
return;
}
SystemReader.setInstance(new RedirectHardeningSystemReader(current));
}
private static final class RedirectHardeningSystemReader extends SystemReader {
private final SystemReader delegate;
RedirectHardeningSystemReader(SystemReader delegate) {
this.delegate = delegate;
}
@Override
public StoredConfig getUserConfig() throws ConfigInvalidException, IOException {
StoredConfig config = delegate.getUserConfig();
// SSRF hardening: keep http.followRedirects off — a followed
// redirect on the info/refs GET is itself the probe being closed.
config.setString("http", null, "followRedirects", "false");
return config;
}
@Override
public String getHostname() {
return delegate.getHostname();
}
@Override
public String getenv(String variable) {
return delegate.getenv(variable);
}
@Override
public String getProperty(String key) {
return delegate.getProperty(key);
}
@Override
public FileBasedConfig openUserConfig(Config parent, FS fs) {
return delegate.openUserConfig(parent, fs);
}
@Override
public FileBasedConfig openSystemConfig(Config parent, FS fs) {
return delegate.openSystemConfig(parent, fs);
}
@Override
public FileBasedConfig openJGitConfig(Config parent, FS fs) {
return delegate.openJGitConfig(parent, fs);
}
@Override
public long getCurrentTime() {
return delegate.getCurrentTime();
}
@Override
public int getTimezone(long when) {
return delegate.getTimezone(when);
}
}
@Override

19
common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java

@ -44,7 +44,6 @@ import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.RemoteRefUpdate;
import org.eclipse.jgit.transport.SshTransport;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.transport.sshd.JGitKeyCache;
import org.eclipse.jgit.transport.sshd.ServerKeyDatabase;
import org.eclipse.jgit.transport.sshd.SshdSessionFactory;
@ -117,6 +116,7 @@ public class GitRepository {
}
public static GitRepository clone(RepositorySettings settings, File directory) throws GitAPIException {
RepositoryUriValidator.validate(settings);
log.debug("Executing clone [{}]", settings.getRepositoryUri());
CloneCommand cloneCommand = Git.cloneRepository()
.setURI(settings.getRepositoryUri())
@ -167,6 +167,7 @@ public class GitRepository {
if (settings.isLocalOnly()) {
return;
}
RepositoryUriValidator.validate(settings);
log.debug("Executing test [{}]", settings.getRepositoryUri());
AuthHandler authHandler = AuthHandler.createFor(settings, directory);
if (settings.isReadOnly()) {
@ -194,6 +195,7 @@ public class GitRepository {
if (settings.isLocalOnly()) {
return false;
}
RepositoryUriValidator.validate(settings);
log.debug("Executing fetch [{}]", settings.getRepositoryUri());
FetchResult result = execute(git.fetch()
.setRemoveDeletedRefs(true));
@ -362,6 +364,7 @@ public class GitRepository {
if (settings.isLocalOnly()) {
return;
}
RepositoryUriValidator.validate(settings);
log.debug("Executing push [{}][{}]", settings.getRepositoryUri(), remoteBranch);
Iterable<PushResult> result = execute(git.push()
.setRefSpecs(new RefSpec(localBranch + ":" + remoteBranch)));
@ -533,7 +536,7 @@ public class GitRepository {
CredentialsProvider credentialsProvider = null;
SshdSessionFactory sshSessionFactory = null;
if (RepositoryAuthMethod.USERNAME_PASSWORD.equals(settings.getAuthMethod())) {
credentialsProvider = newCredentialsProvider(settings.getUsername(), settings.getPassword());
credentialsProvider = newCredentialsProvider(settings.getUsername(), settings.getPassword(), extractHost(settings.getRepositoryUri()));
} else if (RepositoryAuthMethod.PRIVATE_KEY.equals(settings.getAuthMethod())) {
if (StringUtils.startsWith(settings.getRepositoryUri(), "https://")) {
throw new IllegalArgumentException("Invalid URI format for private key authentication");
@ -557,8 +560,16 @@ public class GitRepository {
}
}
private static CredentialsProvider newCredentialsProvider(String username, String password) {
return new UsernamePasswordCredentialsProvider(username, password == null ? "" : password);
private static CredentialsProvider newCredentialsProvider(String username, String password, String allowedHost) {
return new HostScopedCredentialsProvider(username, password, allowedHost);
}
private static String extractHost(String repositoryUri) {
try {
return new URIish(repositoryUri.trim()).getHost();
} catch (Exception e) {
return null;
}
}
private static SshdSessionFactory newSshdSessionFactory(String privateKey, String password, File directory) {

43
common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProvider.java

@ -0,0 +1,43 @@
/**
* Copyright © 2016-2026 The Thingsboard Authors
*
* 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 org.thingsboard.server.service.sync.vc;
import org.eclipse.jgit.errors.UnsupportedCredentialItem;
import org.eclipse.jgit.transport.CredentialItem;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
class HostScopedCredentialsProvider extends UsernamePasswordCredentialsProvider {
private final String allowedHost;
HostScopedCredentialsProvider(String username, String password, String allowedHost) {
super(username, password == null ? "" : password);
this.allowedHost = allowedHost;
}
@Override
public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
if (uri == null || allowedHost == null) {
return false;
}
String requestedHost = uri.getHost();
if (requestedHost == null || !allowedHost.equalsIgnoreCase(requestedHost)) {
return false;
}
return super.get(uri, items);
}
}

67
common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidator.java

@ -0,0 +1,67 @@
/**
* Copyright © 2016-2026 The Thingsboard Authors
*
* 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 org.thingsboard.server.service.sync.vc;
import org.eclipse.jgit.transport.URIish;
import org.thingsboard.common.util.SsrfProtectionValidator;
import org.thingsboard.server.common.data.sync.vc.RepositorySettings;
import java.net.URISyntaxException;
import java.util.Set;
public final class RepositoryUriValidator {
private static final Set<String> ALLOWED_SCHEMES = Set.of("http", "https", "ssh");
private RepositoryUriValidator() {
}
public static void validate(RepositorySettings settings) {
if (settings == null || settings.isLocalOnly()) {
return;
}
String uri = settings.getRepositoryUri();
if (uri == null || uri.isBlank()) {
throw new IllegalArgumentException("Repository URI is required");
}
URIish parsed;
try {
parsed = new URIish(uri.trim());
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Repository URI is invalid: " + e.getMessage(), e);
}
// URIish returns null scheme for scp-style git@host:path; treat as ssh
String scheme = parsed.getScheme();
String effectiveScheme = scheme == null ? "ssh" : scheme.toLowerCase();
if (!ALLOWED_SCHEMES.contains(effectiveScheme)) {
throw new IllegalArgumentException("Repository URI scheme '" + effectiveScheme + "' is not allowed. " +
"Allowed schemes: http, https, ssh");
}
String host = parsed.getHost();
if (host == null || host.isEmpty()) {
throw new IllegalArgumentException("Repository URI is missing a hostname");
}
// Validate the host extracted by URIish — the same parser JGit uses for transport.
// Using java.net.URI here would risk parser-disagreement SSRF bypasses
// (e.g. http://evil.com#@127.0.0.1/ where URI.getHost() and URIish.getHost() differ).
try {
SsrfProtectionValidator.validateHost(host);
} catch (RuntimeException e) {
throw new IllegalArgumentException("Repository URI is not allowed: " + e.getMessage() +
". If this host should be accessible, contact the platform administrator about SSRF allow-list.", e);
}
}
}

103
common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProviderTest.java

@ -0,0 +1,103 @@
/**
* Copyright © 2016-2026 The Thingsboard Authors
*
* 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 org.thingsboard.server.service.sync.vc;
import org.eclipse.jgit.transport.CredentialItem;
import org.eclipse.jgit.transport.URIish;
import org.junit.jupiter.api.Test;
import java.net.URISyntaxException;
import static org.assertj.core.api.Assertions.assertThat;
class HostScopedCredentialsProviderTest {
@Test
void sameHostReturnsCredentials() throws URISyntaxException {
HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", "pass", "github.com");
URIish uri = new URIish("https://github.com/owner/repo.git");
CredentialItem.Username userItem = new CredentialItem.Username();
CredentialItem.Password passItem = new CredentialItem.Password();
boolean result = provider.get(uri, userItem, passItem);
assertThat(result).isTrue();
assertThat(userItem.getValue()).isEqualTo("user");
assertThat(new String(passItem.getValue())).isEqualTo("pass");
}
@Test
void crossHostReturnsFalseAndDoesNotPopulateItems() throws URISyntaxException {
HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", "pass", "github.com");
URIish redirectTarget = new URIish("https://attacker.example.com/owner/repo.git");
CredentialItem.Username userItem = new CredentialItem.Username();
CredentialItem.Password passItem = new CredentialItem.Password();
boolean result = provider.get(redirectTarget, userItem, passItem);
assertThat(result).isFalse();
assertThat(userItem.getValue()).isNull();
assertThat(passItem.getValue()).isNull();
}
@Test
void hostComparisonIsCaseInsensitive() throws URISyntaxException {
HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", "pass", "GitHub.COM");
URIish uri = new URIish("https://github.com/owner/repo.git");
CredentialItem.Username userItem = new CredentialItem.Username();
boolean result = provider.get(uri, userItem);
assertThat(result).isTrue();
assertThat(userItem.getValue()).isEqualTo("user");
}
@Test
void crossHostToPrivateIpIsRefused() throws URISyntaxException {
HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", "pass", "github.com");
URIish internalRedirect = new URIish("http://10.0.0.5/owner/repo.git");
CredentialItem.Username userItem = new CredentialItem.Username();
boolean result = provider.get(internalRedirect, userItem);
assertThat(result).isFalse();
assertThat(userItem.getValue()).isNull();
}
@Test
void nullAllowedHostRefuses() throws URISyntaxException {
HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", "pass", null);
URIish uri = new URIish("https://github.com/owner/repo.git");
CredentialItem.Username userItem = new CredentialItem.Username();
boolean result = provider.get(uri, userItem);
assertThat(result).isFalse();
assertThat(userItem.getValue()).isNull();
}
@Test
void nullPasswordIsNormalizedToEmpty() throws URISyntaxException {
HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", null, "github.com");
URIish uri = new URIish("https://github.com/owner/repo.git");
CredentialItem.Password passItem = new CredentialItem.Password();
boolean result = provider.get(uri, passItem);
assertThat(result).isTrue();
assertThat(new String(passItem.getValue())).isEmpty();
}
}

227
common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidatorTest.java

@ -0,0 +1,227 @@
/**
* Copyright © 2016-2026 The Thingsboard Authors
*
* 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 org.thingsboard.server.service.sync.vc;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.thingsboard.common.util.SsrfProtectionValidator;
import org.thingsboard.server.common.data.sync.vc.RepositorySettings;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@ResourceLock("SsrfProtectionValidator") // shares static state with SsrfProtectionValidatorTest
class RepositoryUriValidatorTest {
@AfterEach
void reset() {
SsrfProtectionValidator.setEnabled(false);
SsrfProtectionValidator.setAllowedHosts(Collections.emptyList());
SsrfProtectionValidator.setAdditionalBlockedHosts(Collections.emptyList());
}
private static RepositorySettings settings(String uri) {
RepositorySettings s = new RepositorySettings();
s.setRepositoryUri(uri);
return s;
}
private static RepositorySettings localOnly(String uri) {
RepositorySettings s = settings(uri);
s.setLocalOnly(true);
return s;
}
// --- localOnly skip ---
@Test
void localOnlySkipsAllValidation() {
// Even file:// and unresolvable hosts pass when localOnly=true
assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(localOnly("file:///etc/passwd")));
assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(localOnly("anything-not-a-uri")));
}
@Test
void nullSettingsIsNoOp() {
assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(null));
}
// --- null / blank URI ---
@Test
void nullUriIsRejected() {
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings(null)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Repository URI is required");
}
@Test
void blankUriIsRejected() {
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings(" ")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Repository URI is required");
}
// --- scheme whitelist ---
@ParameterizedTest
@ValueSource(strings = {
"file:///tmp/repo",
"git://github.com/foo/bar",
"ftp://server/repo"
})
void disallowedSchemesAreRejected(String uri) {
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings(uri)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("scheme");
}
@ParameterizedTest
@ValueSource(strings = {
"http://example.com/foo.git",
"https://example.com/foo.git",
"ssh://git@example.com/foo.git",
"git@github.com:owner/repo.git" // scp-style → SSH inferred
})
void allowedSchemesPassWhenSsrfDisabled(String uri) {
SsrfProtectionValidator.setEnabled(false);
assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings(uri)));
}
// --- host checks ---
@Test
void emptyHostIsRejected() {
// http:/// (no host)
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("https:///path")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("hostname");
}
// --- SSRF integration: HTTP/HTTPS ---
@Test
void httpPrivateIpRejectedWhenSsrfEnabled() {
SsrfProtectionValidator.setEnabled(true);
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("https://10.0.0.5/repo.git")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("not allowed");
}
@Test
void httpLocalhostRejectedWhenSsrfEnabled() {
SsrfProtectionValidator.setEnabled(true);
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("http://localhost/repo.git")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("not allowed");
}
@Test
void httpPublicIpAllowedWhenSsrfEnabled() {
SsrfProtectionValidator.setEnabled(true);
assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("https://8.8.8.8/foo.git")));
}
// --- SSRF integration: SSH (uses validateHost) ---
@Test
void sshPrivateIpRejectedWhenSsrfEnabled() {
SsrfProtectionValidator.setEnabled(true);
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("ssh://git@192.168.1.10/foo.git")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("not allowed");
}
@Test
void scpStyleSshPrivateIpRejectedWhenSsrfEnabled() {
SsrfProtectionValidator.setEnabled(true);
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("git@10.0.0.1:owner/repo.git")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("not allowed");
}
@Test
void sshInternalSuffixRejectedWhenSsrfEnabled() {
SsrfProtectionValidator.setEnabled(true);
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("ssh://git@server.internal/foo.git")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("not allowed");
}
@Test
void sshPublicHostAllowedWhenSsrfEnabled() {
SsrfProtectionValidator.setEnabled(true);
assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("ssh://git@github.com/foo/bar.git")));
assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("git@github.com:foo/bar.git")));
}
// --- allow-list interaction ---
@Test
void sshHostInAllowListPassesEvenWhenPrivate() {
SsrfProtectionValidator.setEnabled(true);
SsrfProtectionValidator.setAllowedHosts(List.of("10.0.0.0/8"));
assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("ssh://git@10.1.2.3/foo.git")));
}
@Test
void httpHostInAllowListPassesEvenWhenPrivate() {
SsrfProtectionValidator.setEnabled(true);
SsrfProtectionValidator.setAllowedHosts(List.of("internal-git.corp"));
assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("https://internal-git.corp/foo.git")));
}
// --- Parser-consistency: host must come from URIish (the parser JGit transport uses) ---
@Test
void userInfoBeforeInternalHostIsRejected() {
// http://github.com@127.0.0.1/ — URIish parses userinfo=github.com, host=127.0.0.1.
// JGit transport will connect to 127.0.0.1. Validator must see the same host.
SsrfProtectionValidator.setEnabled(true);
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("http://github.com@127.0.0.1/repo.git")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("not allowed");
}
@Test
void userInfoBeforePrivateCidrHostIsRejected() {
SsrfProtectionValidator.setEnabled(true);
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("https://fake-user:fake-pass@10.0.0.5/repo.git")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("not allowed");
}
@Test
void userInfoBeforePublicHostIsAllowed() {
// The userinfo is just credentials — host is what matters.
SsrfProtectionValidator.setEnabled(true);
assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("https://user:pass@github.com/repo.git")));
}
@Test
void ipv6LoopbackLiteralIsRejected() {
SsrfProtectionValidator.setEnabled(true);
assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("https://[::1]/repo.git")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("not allowed");
}
}
Loading…
Cancel
Save