Reload global IP policy with gerrit reload-config Filesystem polling applies global IP policy edits on a later permission check, rather than at an explicit administrator-controlled reload. Use Gerrit's existing reload-config command to apply policy changes without requiring a restart or a change to gerrit.config. Load GlobalIpPolicyProvider eagerly at startup and register it as a GerritConfigListener, including for unchanged-config events. Permission checks read a volatile in-memory snapshot without filesystem polling or refresh locks. File edits take effect only after a reload on each server. Retain the current policy and log an error if a reload cannot read or parse the file, including deletion of a previously present file. This prevents a failed reload from discarding active restrictions. Clear rules explicitly by reloading an empty file. A never-present file stays optional; startup load errors still follow failClosedOnGlobalPolicyError, and a successful reload can recover from an invalid startup policy. Add unit and daemon acceptance coverage for explicit reloads, unchanged config, HTTP/SSH visibility, failed-reload retention and recovery, and admin-only command access. Document per-server reloads and policy-only command output, and update mode acceptance tests to reload instead of poll. Change-Id: I7f227a8eb50460119ad3f4487642aa84e37b8f5a
diff --git a/src/main/java/com/googlesource/gerrit/modules/access/ipsubnet/GlobalIpPolicyProvider.java b/src/main/java/com/googlesource/gerrit/modules/access/ipsubnet/GlobalIpPolicyProvider.java index 5db2d8c..29d2bd3 100644 --- a/src/main/java/com/googlesource/gerrit/modules/access/ipsubnet/GlobalIpPolicyProvider.java +++ b/src/main/java/com/googlesource/gerrit/modules/access/ipsubnet/GlobalIpPolicyProvider.java
@@ -14,9 +14,14 @@ package com.googlesource.gerrit.modules.access.ipsubnet; -import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Multimap; +import com.google.common.flogger.FluentLogger; import com.google.gerrit.entities.Project; +import com.google.gerrit.server.config.ConfigUpdatedEvent; +import com.google.gerrit.server.config.ConfigUpdatedEvent.ConfigUpdateEntry; +import com.google.gerrit.server.config.ConfigUpdatedEvent.UpdateResult; +import com.google.gerrit.server.config.GerritConfigListener; import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; @@ -24,16 +29,14 @@ import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; -import java.nio.file.attribute.BasicFileAttributes; -import java.nio.file.attribute.FileTime; import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.function.LongSupplier; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.lib.Config; @Singleton -final class GlobalIpPolicyProvider { +final class GlobalIpPolicyProvider implements GerritConfigListener { + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); + record GlobalPolicy( boolean valid, IpSubnetPolicyEvaluator.CompiledPolicy globalPolicy, @@ -60,57 +63,60 @@ } private final Path path; - private final LongSupplier nanoTime; - private CacheEntry cache; - private boolean checked; - private long lastCheckNanos; + private volatile GlobalPolicy policy; + // A missing file is optional only until a file-based policy has been encountered. + private boolean fileEverPresent; @Inject GlobalIpPolicyProvider(IpSubnetAccessConfig config) { - this(config, System::nanoTime); - } - - @VisibleForTesting - GlobalIpPolicyProvider(IpSubnetAccessConfig config, LongSupplier nanoTime) { this.path = config.globalPolicyPath(); - this.nanoTime = nanoTime; - this.cache = CacheEntry.empty(); + this.policy = readPolicy(true); + if (!policy.valid()) { + logger.atSevere().log( + "Failed to load global policy from %s: %s", + path, policy.errorMessage().orElse("Unknown error")); + } } - synchronized GlobalPolicy get() { - long now = nanoTime.getAsLong(); - if (checked && now - lastCheckNanos < TimeUnit.SECONDS.toNanos(5)) { - return cache.policy; - } - // Serialize refreshes and throttle missing/invalid files as well as valid ones. - checked = true; - lastCheckNanos = now; - try { - BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); - FileTime mtime = attributes.lastModifiedTime(); - long size = attributes.size(); - CacheEntry current = cache; - if (current.matches(mtime, size)) { - return current.policy; + GlobalPolicy get() { + return policy; + } + + @Override + public synchronized Multimap<UpdateResult, ConfigUpdateEntry> configUpdated( + ConfigUpdatedEvent event) { + // The external policy file can change even when gerrit.config has not. + GlobalPolicy loaded = readPolicy(!fileEverPresent && policy.valid()); + if (loaded.valid()) { + policy = loaded; + if (fileEverPresent) { + logger.atInfo().log("Reloaded global policy from %s", path); } + } else { + logger.atSevere().log( + "Failed to reload global policy from %s; retaining current policy: %s", + path, loaded.errorMessage().orElse("Unknown error")); + } + // This listener does not accept or reject any gerrit.config settings. + return ConfigUpdatedEvent.NO_UPDATES; + } - GlobalPolicy loaded = loadFile(path); - cache = new CacheEntry(Optional.of(mtime), size, loaded); - return loaded; + private GlobalPolicy readPolicy(boolean allowMissing) { + try { + String text = Files.readString(path, StandardCharsets.UTF_8); + fileEverPresent = true; + return parseFile(text); } catch (NoSuchFileException e) { - cache = CacheEntry.empty(); - return cache.policy; + return allowMissing + ? GlobalPolicy.empty() + : GlobalPolicy.invalid("Global policy file does not exist: " + path); } catch (IOException e) { - GlobalPolicy invalid = - GlobalPolicy.invalid("Failed to load global policy: " + e.getMessage()); - cache = CacheEntry.fromInvalid(invalid); - return invalid; + fileEverPresent = true; + return GlobalPolicy.invalid("Failed to read " + path + ": " + e.getMessage()); } } - private static GlobalPolicy loadFile(Path path) throws IOException { - String text = Files.readString(path, StandardCharsets.UTF_8); - + private static GlobalPolicy parseFile(String text) { Config cfg = new Config(); try { cfg.fromText(text); @@ -139,18 +145,4 @@ return GlobalPolicy.invalid("Invalid global CIDR policy: " + e.getMessage()); } } - - private record CacheEntry(Optional<FileTime> mtime, long size, GlobalPolicy policy) { - static CacheEntry empty() { - return new CacheEntry(Optional.empty(), -1L, GlobalPolicy.empty()); - } - - static CacheEntry fromInvalid(GlobalPolicy policy) { - return new CacheEntry(Optional.empty(), -1L, policy); - } - - boolean matches(FileTime fileTime, long fileSize) { - return mtime.isPresent() && mtime.get().equals(fileTime) && size == fileSize; - } - } }
diff --git a/src/main/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetAccessModule.java b/src/main/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetAccessModule.java index 9629ebf..22fb2d4 100644 --- a/src/main/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetAccessModule.java +++ b/src/main/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetAccessModule.java
@@ -14,6 +14,8 @@ package com.googlesource.gerrit.modules.access.ipsubnet; +import com.google.gerrit.extensions.registration.DynamicSet; +import com.google.gerrit.server.config.GerritConfigListener; import com.google.gerrit.server.permissions.PermissionBackend; import com.google.inject.AbstractModule; import com.google.inject.Scopes; @@ -24,5 +26,7 @@ protected void configure() { bind(PermissionBackend.class).to(IpSubnetPermissionBackend.class).in(Scopes.SINGLETON); bind(RequestRemotePeer.class); + bind(GlobalIpPolicyProvider.class).asEagerSingleton(); + DynamicSet.bind(binder(), GerritConfigListener.class).to(GlobalIpPolicyProvider.class); } }
diff --git a/src/main/resources/Documentation/about.md b/src/main/resources/Documentation/about.md index 93446af..bd13cad 100644 --- a/src/main/resources/Documentation/about.md +++ b/src/main/resources/Documentation/about.md
@@ -11,9 +11,19 @@ `DefaultPermissionBackend`; denied checks receive a denied project view, behaving like a hidden project. -IPv4 and IPv6 CIDRs are supported; prefixes from one address family do not -match addresses from the other. See [configuration](config.md) for -installation, policy ordering, inheritance, and refresh behavior. +Global policy is controlled by server administrators, not project owners. +Its CIDR lists are always enforced, even when project policy uses +`LOG_ONLY`. See [configuration](config.md) for policy settings and +[metrics](metrics.md) for decision observability. + +Project policy is read through `PluginConfigFactory` with inheritance and +uses Gerrit's project cache lifecycle for updates. Global policy is loaded +at startup and refreshed when an administrator runs `gerrit reload-config`. +Permission checks use the in-memory snapshot without checking the filesystem. +Failed reloads retain the current policy and log an error. + +CIDR matching supports IPv4 and IPv6; prefixes from one address family do +not match addresses from the other. Client address and proxies --------------------------
diff --git a/src/main/resources/Documentation/config.md b/src/main/resources/Documentation/config.md index 3dc4785..4614031 100644 --- a/src/main/resources/Documentation/config.md +++ b/src/main/resources/Documentation/config.md
@@ -132,11 +132,26 @@ Project owners can change that per-project policy; the global-file union alone cannot express an additional, admin-only project allow restriction. -On project permission checks with a resolvable IP, the global file's -modification time and size are checked at most once every five seconds. -The policy is reloaded when either changes; file creation and removal are -also detected. Read errors are retried at the next eligible check without -requiring a metadata change. +The global policy file is loaded at startup. After editing it, run the SSH +command `gerrit reload-config` to refresh the policy on each Gerrit server; +no change to `gerrit.config` is necessary. File edits alone do not take effect. +Permission checks use an in-memory snapshot, without filesystem polling. +A policy-only reload may print `No config entries updated!` because the +listener does not change `gerrit.config` settings. Check the server logs for +the policy reload result. + +A failed reload (including a previously present file that is now missing, +an unreadable file, or an invalid file) retains the current policy and +reports an error in the server logs. To intentionally clear the global +rules, empty the file and reload rather than deleting it. +A file that has never been present remains optional on reload and does not +produce an error. + +At startup, a missing file still means no global rules; an unreadable or +invalid file follows `failClosedOnGlobalPolicyError`. A successful reload +can recover from an invalid startup policy. This command reloads the policy +contents, not the module or its `gerrit.config` settings; changing those +settings still requires a restart. global.blockedSubnet / project.NAME.blockedSubnet : IPv4 or IPv6 CIDR prefix to deny. Deny project permission checks for a
diff --git a/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/GlobalIpPolicyProviderTest.java b/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/GlobalIpPolicyProviderTest.java index a20a0ca..ead1c5e 100644 --- a/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/GlobalIpPolicyProviderTest.java +++ b/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/GlobalIpPolicyProviderTest.java
@@ -19,47 +19,113 @@ import static org.junit.Assume.assumeTrue; import com.google.gerrit.entities.Project; +import com.google.gerrit.server.config.ConfigUpdatedEvent; import com.google.gerrit.server.config.SitePaths; import java.net.InetAddress; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; +import java.util.ArrayList; +import java.util.List; import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.Level; +import org.apache.log4j.Logger; +import org.apache.log4j.spi.LoggingEvent; import org.eclipse.jgit.lib.Config; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class GlobalIpPolicyProviderTest { @Rule public TemporaryFolder tempDir = new TemporaryFolder(); - private final AtomicLong nanoTime = new AtomicLong(); - private Path file; - private GlobalIpPolicyProvider provider; - @Before - public void setUp() throws Exception { - file = tempDir.getRoot().toPath().resolve("policy.config"); - Config cfg = new Config(); - cfg.setString("plugin", "access-ipsubnet", "globalPolicyPath", file.toString()); - provider = - new GlobalIpPolicyProvider( - new IpSubnetAccessConfig(cfg, new SitePaths(tempDir.getRoot().toPath())), - nanoTime::get); + @Test + public void missingOptionalFileReloadDoesNotLogError() throws Exception { + Path file = tempDir.getRoot().toPath().resolve("policy.config"); + GlobalIpPolicyProvider provider = newProvider(file); + try (LogCapture logs = new LogCapture()) { + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); + assertThat(provider.get().valid()).isTrue(); + assertThat(logs.records.stream().anyMatch(r -> r.getLevel().isGreaterOrEqual(Level.ERROR))) + .isFalse(); + } } @Test - public void fileChangesAreDeferredUntilNextCheck() throws Exception { + public void fileCreatedAfterStartupThenDeletedRetainsPolicyAndLogsError() throws Exception { + Path file = tempDir.getRoot().toPath().resolve("policy.config"); + GlobalIpPolicyProvider provider = newProvider(file); + // Even an empty file counts as a successfully loaded file-based policy. + Files.writeString(file, ""); + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); + GlobalIpPolicyProvider.GlobalPolicy loaded = provider.get(); + Files.delete(file); + try (LogCapture logs = new LogCapture()) { + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); + assertThat(provider.get()).isSameInstanceAs(loaded); + assertThat(logs.records).hasSize(1); + assertThat(logs.records.get(0).getLevel()).isEqualTo(Level.ERROR); + } + } + + private GlobalIpPolicyProvider newProvider(Path file) throws Exception { + Config cfg = new Config(); + cfg.setString("plugin", "access-ipsubnet", "globalPolicyPath", file.toString()); + return new GlobalIpPolicyProvider( + new IpSubnetAccessConfig(cfg, new SitePaths(tempDir.getRoot().toPath()))); + } + + private static class LogCapture implements AutoCloseable { + final List<LoggingEvent> records = new ArrayList<>(); + private final Logger logger = Logger.getLogger(GlobalIpPolicyProvider.class.getName()); + private final Level previousLevel = logger.getLevel(); + private final AppenderSkeleton handler = + new AppenderSkeleton() { + @Override + protected void append(LoggingEvent record) { + records.add(record); + } + + @Override + public boolean requiresLayout() { + return false; + } + + @Override + public void close() {} + }; + + LogCapture() { + logger.setLevel(Level.ALL); + logger.addAppender(handler); + } + + @Override + public void close() { + logger.removeAppender(handler); + logger.setLevel(previousLevel); + } + } + + @Test + public void fileChangesRequireReload() throws Exception { + Path file = tempDir.getRoot().toPath().resolve("policy.config"); Files.writeString(file, "[global]\nblockedSubnet = 192.0.2.0/24\n"); - GlobalIpPolicyProvider.GlobalPolicy original = provider.get(); + Config cfg = new Config(); + cfg.setString("plugin", "access-ipsubnet", "globalPolicyPath", file.toString()); + GlobalIpPolicyProvider provider = + new GlobalIpPolicyProvider( + new IpSubnetAccessConfig(cfg, new SitePaths(tempDir.getRoot().toPath()))); Files.writeString(file, "[global]\nblockedSubnet = 198.51.100.0/24\n"); + GlobalIpPolicyProvider.GlobalPolicy original = provider.get(); + assertThat(original.globalPolicy().blocked.get(0).matches(InetAddress.getByName("192.0.2.1"))) + .isTrue(); assertThat(provider.get()).isSameInstanceAs(original); - nanoTime.set(TimeUnit.SECONDS.toNanos(5) - 1); - assertThat(provider.get()).isSameInstanceAs(original); - nanoTime.incrementAndGet(); + // An unchanged gerrit.config still triggers policy reload. + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); GlobalIpPolicyProvider.GlobalPolicy updated = provider.get(); assertThat( IpSubnetPolicyEvaluator.evaluate( @@ -77,39 +143,126 @@ .isTrue(); Files.delete(file); assertThat(provider.get()).isSameInstanceAs(updated); - nanoTime.addAndGet(TimeUnit.SECONDS.toNanos(5)); + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); + assertThat(provider.get()).isSameInstanceAs(updated); + Files.writeString(file, ""); + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); assertThat(provider.get().effectivePolicy(Project.nameKey("p")).blocked).isEmpty(); } @Test - public void missingAndInvalidFilesAreAlsoThrottled() throws Exception { + public void failedReloadRetainsLastValidPolicy() throws Exception { + Path file = tempDir.getRoot().toPath().resolve("policy.config"); + Config cfg = new Config(); + cfg.setString("plugin", "access-ipsubnet", "globalPolicyPath", file.toString()); + GlobalIpPolicyProvider provider = + new GlobalIpPolicyProvider( + new IpSubnetAccessConfig(cfg, new SitePaths(tempDir.getRoot().toPath()))); GlobalIpPolicyProvider.GlobalPolicy missing = provider.get(); assertThat(missing.valid()).isTrue(); + assertThat(missing.globalPolicy().blocked).isEmpty(); + assertThat(missing.globalPolicy().allowed).isEmpty(); + assertThat(missing.projectPolicies()).isEmpty(); Files.writeString(file, "[global]\nblockedSubnet = not-a-cidr\n"); assertThat(provider.get()).isSameInstanceAs(missing); - nanoTime.addAndGet(TimeUnit.SECONDS.toNanos(5)); + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); GlobalIpPolicyProvider.GlobalPolicy invalid = provider.get(); - assertThat(invalid.valid()).isFalse(); + assertThat(invalid).isSameInstanceAs(missing); Files.writeString(file, "[global]\nblockedSubnet = 192.0.2.0/24\n"); assertThat(provider.get()).isSameInstanceAs(invalid); - nanoTime.addAndGet(TimeUnit.SECONDS.toNanos(5)); + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); assertThat(provider.get().valid()).isTrue(); } @Test - public void readFailureIsRetriedAfterPermissionsAreRestored() throws Exception { + public void invalidStartupRecoversOnlyOnReload() throws Exception { + Path file = tempDir.getRoot().toPath().resolve("policy.config"); + Files.writeString(file, "[broken"); + Config cfg = new Config(); + cfg.setString("plugin", "access-ipsubnet", "globalPolicyPath", file.toString()); + GlobalIpPolicyProvider provider = + new GlobalIpPolicyProvider( + new IpSubnetAccessConfig(cfg, new SitePaths(tempDir.getRoot().toPath()))); + assertThat(provider.get().valid()).isFalse(); + Files.writeString(file, ""); + assertThat(provider.get().valid()).isFalse(); + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); + assertThat(provider.get().valid()).isTrue(); + } + + @Test + public void failedReloadLogsErrorAndRetainsNonemptyPolicy() throws Exception { + Path file = tempDir.getRoot().toPath().resolve("policy.config"); + Files.writeString(file, "[global]\nblockedSubnet = 192.0.2.0/24\n"); + Config cfg = new Config(); + cfg.setString("plugin", "access-ipsubnet", "globalPolicyPath", file.toString()); + GlobalIpPolicyProvider provider = + new GlobalIpPolicyProvider( + new IpSubnetAccessConfig(cfg, new SitePaths(tempDir.getRoot().toPath()))); + GlobalIpPolicyProvider.GlobalPolicy original = provider.get(); + List<LoggingEvent> records = new ArrayList<>(); + AppenderSkeleton handler = + new AppenderSkeleton() { + @Override + protected void append(LoggingEvent record) { + records.add(record); + } + + @Override + public boolean requiresLayout() { + return false; + } + + @Override + public void close() {} + }; + Logger logger = Logger.getLogger(GlobalIpPolicyProvider.class.getName()); + Level previousLevel = logger.getLevel(); + logger.setLevel(Level.ALL); + logger.addAppender(handler); + try { + for (String invalid : new String[] {"[broken", "[global]\nblockedSubnet = bad\n"}) { + Files.writeString(file, invalid); + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); + assertThat(provider.get()).isSameInstanceAs(original); + } + Files.delete(file); + Files.createDirectory(file); + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); + assertThat(provider.get()).isSameInstanceAs(original); + assertThat(records).hasSize(3); + for (LoggingEvent record : records) { + assertThat(record.getLevel()).isEqualTo(Level.ERROR); + assertThat(record.getRenderedMessage()).contains("retaining current policy"); + assertThat(record.getRenderedMessage()).contains(file.toString()); + } + } finally { + logger.removeAppender(handler); + logger.setLevel(previousLevel); + } + } + + @Test + public void readFailureRecoversAfterPermissionsAreRestoredAndReloaded() throws Exception { + Path file = tempDir.getRoot().toPath().resolve("policy.config"); Files.writeString(file, "[global]\nblockedSubnet = 192.0.2.0/24\n"); assumeTrue(Files.getFileStore(file).supportsFileAttributeView("posix")); Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(file); + Config cfg = new Config(); + cfg.setString("plugin", "access-ipsubnet", "globalPolicyPath", file.toString()); + GlobalIpPolicyProvider provider; try { Files.setPosixFilePermissions(file, Set.of()); assumeFalse(Files.isReadable(file)); + provider = + new GlobalIpPolicyProvider( + new IpSubnetAccessConfig(cfg, new SitePaths(tempDir.getRoot().toPath()))); assertThat(provider.get().valid()).isFalse(); } finally { Files.setPosixFilePermissions(file, permissions); } assertThat(provider.get().valid()).isFalse(); - nanoTime.addAndGet(TimeUnit.SECONDS.toNanos(5)); + provider.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); assertThat(provider.get().valid()).isTrue(); assertThat(provider.get().effectivePolicy(Project.nameKey("p")).blocked).hasSize(1); }
diff --git a/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetGlobalModeIT.java b/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetGlobalModeIT.java index b7bbc91..2b98db9 100644 --- a/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetGlobalModeIT.java +++ b/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetGlobalModeIT.java
@@ -14,6 +14,7 @@ package com.googlesource.gerrit.modules.access.ipsubnet; +import com.google.gerrit.acceptance.UseSsh; import com.google.gerrit.entities.Project; import com.google.gerrit.server.config.SitePaths; import com.google.gerrit.testing.ConfigSuite; @@ -24,6 +25,7 @@ import org.junit.Test; /** Exercises mode selection through real project configuration and HTTP permission checks. */ +@UseSsh public class IpSubnetGlobalModeIT extends AbstractIpSubnetDaemonTest { @Inject private SitePaths sitePaths; @@ -121,8 +123,9 @@ setLoopbackBlocked(false); assertProjectStatus(userRestSession, 404); } finally { - Files.deleteIfExists(file); + Files.writeString(file, ""); refreshGlobalPolicy(); + Files.deleteIfExists(file); } assertProjectStatus(userRestSession, 200); } @@ -156,7 +159,7 @@ } private void refreshGlobalPolicy() throws Exception { - // Global policy is polled at most once every five seconds on permission checks. - Thread.sleep(5100); + adminSshSession.exec("gerrit reload-config"); + adminSshSession.assertSuccess(); } }
diff --git a/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetGlobalPolicyReloadIT.java b/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetGlobalPolicyReloadIT.java new file mode 100644 index 0000000..e102f89 --- /dev/null +++ b/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetGlobalPolicyReloadIT.java
@@ -0,0 +1,153 @@ +// Copyright (C) 2026 The Android Open Source 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 com.googlesource.gerrit.modules.access.ipsubnet; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.gerrit.acceptance.UseSsh; +import com.google.gerrit.server.config.SitePaths; +import com.google.inject.Inject; +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** Exercises the real reload command, listener wiring, and HTTP/SSH policy snapshots. */ +@UseSsh +public class IpSubnetGlobalPolicyReloadIT extends AbstractIpSubnetDaemonTest { + @Inject private SitePaths sitePaths; + private Path policyFile; + + @Before + public void setUpPolicyFile() throws Exception { + policyFile = sitePaths.resolve("etc/access-ipsubnet.config"); + Files.createDirectories(policyFile.getParent()); + assertVisibility(true); + } + + @After + public void clearPolicy() throws Exception { + if (policyFile == null) { + return; + } + // Deleting the policy alone intentionally retains restrictions on reload. + if (Files.isDirectory(policyFile)) { + Files.delete(policyFile); + } + Files.writeString(policyFile, ""); + reloadPolicy(); + Files.delete(policyFile); + } + + @Test + public void fileEditsDoNotApplyUntilReloadWithUnchangedGerritConfig() throws Exception { + Files.writeString(policyFile, loopbackBlock()); + // Exceed the previous polling interval to detect accidental filesystem polling. + Thread.sleep(5100); + assertVisibility(true); + // Nothing in gerrit.config has changed; this is a policy-only reload. + String output = reloadPolicy(); + assertThat(output).contains("No config entries updated!"); + assertVisibility(false); + } + + @Test + public void emptyFileClearsRestrictionsOnlyAfterReload() throws Exception { + blockLoopback(); + Files.writeString(policyFile, ""); + assertVisibility(false); + reloadPolicy(); + assertVisibility(true); + } + + @Test + public void missingFileReloadRetainsRestrictions() throws Exception { + blockLoopback(); + Files.delete(policyFile); + assertFailedReloadRetainsRestrictionsAndRecovers(); + } + + @Test + public void invalidConfigReloadRetainsRestrictions() throws Exception { + blockLoopback(); + Files.writeString(policyFile, "[broken"); + assertFailedReloadRetainsRestrictionsAndRecovers(); + } + + @Test + public void invalidCidrReloadRetainsRestrictions() throws Exception { + blockLoopback(); + Files.writeString(policyFile, "[global]\nblockedSubnet = not-a-cidr\n"); + assertFailedReloadRetainsRestrictionsAndRecovers(); + } + + @Test + public void unreadableFileReloadRetainsRestrictions() throws Exception { + blockLoopback(); + Files.delete(policyFile); + // A directory is a deterministic read error, even when tests run with elevated privileges. + Files.createDirectory(policyFile); + reloadPolicy(); + assertVisibility(false); + Files.delete(policyFile); + Files.writeString(policyFile, ""); + reloadPolicy(); + assertVisibility(true); + } + + @Test + public void nonAdminCannotReloadPolicy() throws Exception { + Files.writeString(policyFile, loopbackBlock()); + userSshSession.exec("gerrit reload-config"); + userSshSession.assertFailure(); + assertVisibility(true); + reloadPolicy(); + assertVisibility(false); + } + + private void assertFailedReloadRetainsRestrictionsAndRecovers() throws Exception { + // Policy-file errors are logged rather than reported as command failures. + reloadPolicy(); + assertVisibility(false); + Files.writeString(policyFile, ""); + reloadPolicy(); + assertVisibility(true); + } + + private void blockLoopback() throws Exception { + Files.writeString(policyFile, loopbackBlock()); + reloadPolicy(); + assertVisibility(false); + } + + private String loopbackBlock() { + return "[global]\nblockedSubnet = 127.0.0.0/8\nblockedSubnet = ::1/128\n"; + } + + private String reloadPolicy() throws Exception { + String output = adminSshSession.exec("gerrit reload-config"); + adminSshSession.assertSuccess(); + return output; + } + + private void assertVisibility(boolean visible) throws Exception { + assertProjectStatus(userRestSession, visible ? 200 : 404); + assertProjectStatus(anonymousRestSession, visible ? 200 : 404); + String output = userSshSession.exec("gerrit ls-projects --prefix " + project.get()); + userSshSession.assertSuccess(); + assertThat(output.trim()).isEqualTo(visible ? project.get() : ""); + } +}
diff --git a/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetPermissionBackendTest.java b/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetPermissionBackendTest.java index 1447eff..b0ec92b 100644 --- a/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetPermissionBackendTest.java +++ b/src/test/java/com/googlesource/gerrit/modules/access/ipsubnet/IpSubnetPermissionBackendTest.java
@@ -22,12 +22,15 @@ import com.google.gerrit.acceptance.TestMetricMaker; import com.google.gerrit.entities.Account; import com.google.gerrit.entities.Project; +import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.server.AccessPath; import com.google.gerrit.server.AnonymousUser; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.InternalUser; import com.google.gerrit.server.RemotePeer; +import com.google.gerrit.server.config.ConfigUpdatedEvent; +import com.google.gerrit.server.config.GerritConfigListener; import com.google.gerrit.server.config.PluginConfig; import com.google.gerrit.server.config.PluginConfigFactory; import com.google.gerrit.server.config.SitePaths; @@ -38,8 +41,10 @@ import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; +import com.google.inject.Key; import com.google.inject.OutOfScopeException; import com.google.inject.Provider; +import com.google.inject.TypeLiteral; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.file.Files; @@ -114,10 +119,10 @@ protected void configure() { bind(DefaultPermissionBackend.class).toInstance(delegate); bind(CurrentUser.class).toProvider(requestUserProvider); + DynamicSet.setOf(binder(), GerritConfigListener.class); install(new IpSubnetAccessModule()); bind(ProjectCache.class).toInstance(cache); bind(PluginConfigFactory.class).toInstance(factory); - bind(GlobalIpPolicyProvider.class).toInstance(new GlobalIpPolicyProvider(config)); bind(IpSubnetAccessConfig.class).toInstance(config); bind(IpDecisionLogger.class).toInstance(new IpDecisionLogger(metrics, config)); } @@ -152,6 +157,24 @@ } @Test + public void reloadListenerUpdatesTheBackendPolicySnapshot() throws Exception { + Injector injector = systemInjector(); + GlobalIpPolicyProvider provider = injector.getInstance(GlobalIpPolicyProvider.class); + GlobalIpPolicyProvider.GlobalPolicy original = provider.get(); + Files.writeString( + new IpSubnetAccessConfig(cfg, new SitePaths(tempDir.getRoot().toPath())).globalPolicyPath(), + ""); + DynamicSet<GerritConfigListener> listeners = + injector.getInstance(Key.get(new TypeLiteral<DynamicSet<GerritConfigListener>>() {})); + assertThat(listeners).containsExactly(provider); + for (GerritConfigListener listener : listeners) { + listener.configUpdated(new ConfigUpdatedEvent(new Config(), new Config())); + } + assertThat(provider.get()).isNotSameInstanceAs(original); + assertThat(provider.get().globalPolicy().blocked).isEmpty(); + } + + @Test public void systemInjectorCanLoadWithoutTransportBinding() throws Exception { requestUserProvider = () -> {