fix(mongodb): fall back to authorized databases on list denial

This commit is contained in:
zipg authored and GitHub committed 2026-09-28 21:27:15 +08:00
1 parent 657f5a51e0
commit a4426e6494
2 files changed
+254 -1

No files matched your search

@@ -11,6 +11,7 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mongodb.ConnectionString;
import com.mongodb.MongoBulkWriteException;
import com.mongodb.MongoCommandException;
import com.mongodb.MongoNamespace;
import com.mongodb.MongoCredential;
import com.mongodb.MongoClientSettings;
@@ -74,6 +75,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
@@ -110,6 +112,8 @@ public final class MongoAgent {
private static final int MAX_FIND_CURSORS_PER_OWNER = 16;
private static final int MAX_FIND_CURSORS_TOTAL = 64;
private static final int MAX_SESSIONS = 256;
/** MongoDB error code 13 (Unauthorized), returned when the account may not run listDatabases. */
private static final int LIST_DATABASES_UNAUTHORIZED_CODE = 13;
private static final ThreadLocal<MongoClient> CURRENT_CLIENT = new ThreadLocal<>();
private static final ThreadLocal<Set<String>> CURRENT_FIND_CURSOR_OWNER = new ThreadLocal<>();
private static final ConcurrentHashMap<String, MongoCursor<Document>> FIND_CURSORS = new ConcurrentHashMap<>();
@@ -357,13 +361,91 @@ public final class MongoAgent {
private static Object listDatabases() {
MongoClient c = requireClient();
try {
return databaseNameEntries(c.listDatabaseNames());
} catch (RuntimeException error) {
if (!isListDatabasesAuthorizationFailure(error)) {
throw error;
}
// MongoDB servers older than 4.0.4 have no "authorizedDatabases" option, so
// listDatabases always requires the cluster-wide listDatabases privilege there.
// Accounts limited to database-scoped roles are readable but still get an
// Unauthorized error, which used to break the whole database list. Fall back to the
// databases those accounts are actually authorized for.
List<Map<String, String>> authorized = authorizedDatabaseNames(c);
if (authorized.isEmpty()) {
throw error;
}
return authorized;
}
}
private static List<Map<String, String>> databaseNameEntries(Iterable<String> names) {
List<Map<String, String>> result = new ArrayList<>();
for (String name : c.listDatabaseNames()) {
for (String name : names) {
result.add(Collections.singletonMap("name", name));
}
return result;
}
static boolean isListDatabasesAuthorizationFailure(Throwable error) {
for (Throwable current = error; current != null; current = current.getCause()) {
if (!(current instanceof MongoCommandException command)) {
continue;
}
if (command.getErrorCode() == LIST_DATABASES_UNAUTHORIZED_CODE) {
return true;
}
String codeName = command.getErrorCodeName();
if (codeName != null && "unauthorized".equalsIgnoreCase(codeName)) {
return true;
}
}
return false;
}
private static List<Map<String, String>> authorizedDatabaseNames(MongoClient client) {
Document status;
try {
status = client.getDatabase("admin")
.runCommand(new Document("connectionStatus", 1).append("showPrivileges", true));
} catch (RuntimeException error) {
return Collections.emptyList();
}
return databaseNameEntries(databaseNamesFromConnectionStatus(status));
}
/**
* Reads the databases an authenticated account is authorized for from a {@code connectionStatus}
* response. Only the account's own resolved privileges are used, so a database is reported when
* the account really holds an action on it, regardless of where the granting role is defined.
*/
static List<String> databaseNamesFromConnectionStatus(Document status) {
Object authInfo = status == null ? null : status.get("authInfo");
if (!(authInfo instanceof Document authInfoDocument)) {
return Collections.emptyList();
}
Object privileges = authInfoDocument.get("authenticatedUserPrivileges");
if (!(privileges instanceof List<?> privilegeList)) {
return Collections.emptyList();
}
Set<String> names = new TreeSet<>();
for (Object item : privilegeList) {
if (!(item instanceof Document privilege)) {
continue;
}
Object resource = privilege.get("resource");
if (!(resource instanceof Document resourceDocument)) {
continue;
}
Object database = resourceDocument.get("db");
if (database instanceof String name && !name.isEmpty()) {
names.add(name);
}
}
return new ArrayList<>(names);
}
private static Object listCollections(JsonObject params) {
MongoClient c = requireClient();
String database = params.get("database").getAsString();
@@ -14,6 +14,7 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mongodb.MongoBulkWriteException;
import com.mongodb.MongoCommandException;
import com.mongodb.MongoClientSettings;
import com.mongodb.ServerAddress;
import com.mongodb.bulk.BulkWriteError;
@@ -2402,6 +2403,176 @@ class MongoAgentTest {
);
}
@Test
void listDatabasesFallsBackToTheDatabasesTheAccountIsAuthorizedFor() {
List<String> calls = new ArrayList<>();
Document connectionStatus = new Document("ok", 1.0)
.append("authInfo", new Document("authenticatedUserRoles", List.of(
new Document("role", "readWrite").append("db", "shopdb")))
.append("authenticatedUserPrivileges", List.of(
new Document("resource", new Document("db", "shopdb").append("collection", ""))
.append("actions", List.of("find", "insert")),
new Document("resource",
new Document("db", "shopdb").append("collection", "system.js"))
.append("actions", List.of("find")),
new Document("resource", new Document("db", "reports").append("collection", ""))
.append("actions", List.of("find")))));
MongoDatabase admin = (MongoDatabase) Proxy.newProxyInstance(
MongoDatabase.class.getClassLoader(),
new Class<?>[] {MongoDatabase.class},
(proxy, method, args) -> {
if ("runCommand".equals(method.getName())) {
calls.add("connectionStatus");
return connectionStatus;
}
throw new UnsupportedOperationException(method.getName());
}
);
MongoClient client = (MongoClient) Proxy.newProxyInstance(
MongoClient.class.getClassLoader(),
new Class<?>[] {MongoClient.class},
(proxy, method, args) -> {
if ("listDatabaseNames".equals(method.getName())) {
throw mongoCommandError(
13,
"Unauthorized",
"not authorized on admin to execute command { listDatabases: 1, nameOnly: true }"
);
}
if ("getDatabase".equals(method.getName())) {
calls.add("getDatabase:" + args[0]);
return admin;
}
throw new UnsupportedOperationException(method.getName());
}
);
String response = MongoAgent.handleRequest(
"{\"jsonrpc\":\"2.0\",\"id\":21,\"method\":\"list_databases\",\"params\":{}}", client);
JsonObject json = JsonParser.parseString(response).getAsJsonObject();
assertFalse(json.has("error"), json.toString());
JsonArray databases = json.getAsJsonArray("result");
assertEquals(2, databases.size());
assertEquals("reports", databases.get(0).getAsJsonObject().get("name").getAsString());
assertEquals("shopdb", databases.get(1).getAsJsonObject().get("name").getAsString());
assertEquals(List.of("getDatabase:admin", "connectionStatus"), calls);
}
@Test
void listDatabasesKeepsTheUnauthorizedErrorWhenNoAuthorizedDatabaseIsKnown() {
List<String> calls = new ArrayList<>();
MongoDatabase admin = (MongoDatabase) Proxy.newProxyInstance(
MongoDatabase.class.getClassLoader(),
new Class<?>[] {MongoDatabase.class},
(proxy, method, args) -> {
if ("runCommand".equals(method.getName())) {
calls.add("connectionStatus");
return new Document("ok", 1.0).append("authInfo", new Document());
}
throw new UnsupportedOperationException(method.getName());
}
);
MongoClient client = (MongoClient) Proxy.newProxyInstance(
MongoClient.class.getClassLoader(),
new Class<?>[] {MongoClient.class},
(proxy, method, args) -> {
if ("listDatabaseNames".equals(method.getName())) {
throw mongoCommandError(
13,
"Unauthorized",
"not authorized on admin to execute command { listDatabases: 1, nameOnly: true }"
);
}
if ("getDatabase".equals(method.getName())) {
return admin;
}
throw new UnsupportedOperationException(method.getName());
}
);
String response = MongoAgent.handleRequest(
"{\"jsonrpc\":\"2.0\",\"id\":22,\"method\":\"list_databases\",\"params\":{}}", client);
JsonObject json = JsonParser.parseString(response).getAsJsonObject();
assertTrue(json.getAsJsonObject("error").get("message").getAsString()
.contains("error 13 (Unauthorized)"), json.toString());
assertEquals(List.of("connectionStatus"), calls);
}
@Test
void listDatabasesDoesNotProbePrivilegesForUnrelatedFailures() {
List<String> calls = new ArrayList<>();
MongoClient client = (MongoClient) Proxy.newProxyInstance(
MongoClient.class.getClassLoader(),
new Class<?>[] {MongoClient.class},
(proxy, method, args) -> {
if ("listDatabaseNames".equals(method.getName())) {
throw mongoCommandError(11600, "InterruptedAtShutdown", "operation was interrupted");
}
calls.add(method.getName());
throw new UnsupportedOperationException(method.getName());
}
);
String response = MongoAgent.handleRequest(
"{\"jsonrpc\":\"2.0\",\"id\":23,\"method\":\"list_databases\",\"params\":{}}", client);
JsonObject json = JsonParser.parseString(response).getAsJsonObject();
assertTrue(json.getAsJsonObject("error").get("message").getAsString()
.contains("error 11600"), json.toString());
assertEquals(List.of(), calls);
}
@Test
void authorizedDatabaseNamesComeFromTheAccountsOwnPrivileges() {
Document status = new Document("authInfo", new Document("authenticatedUserPrivileges", List.of(
new Document("resource", new Document("db", "shopdb").append("collection", ""))
.append("actions", List.of("find")),
new Document("resource", new Document("db", "shopdb").append("collection", "orders"))
.append("actions", List.of("find")),
new Document("resource", new Document("db", "admin").append("collection", "system.users"))
.append("actions", List.of("find")),
new Document("resource", new Document("db", "").append("collection", ""))
.append("actions", List.of("find")),
new Document("resource", new Document("cluster", true))
.append("actions", List.of("listDatabases")),
new Document("resource", "not-a-resource"),
"not-a-privilege")));
assertEquals(List.of("admin", "shopdb"), MongoAgent.databaseNamesFromConnectionStatus(status));
assertEquals(List.of(), MongoAgent.databaseNamesFromConnectionStatus(new Document()));
assertEquals(List.of(), MongoAgent.databaseNamesFromConnectionStatus(null));
}
@Test
void listDatabasesAuthorizationFailureDetectionFollowsTheCauseChain() {
assertTrue(MongoAgent.isListDatabasesAuthorizationFailure(
new RuntimeException(
"wrapped",
mongoCommandError(13, "Unauthorized", "not authorized on admin")
)
));
assertTrue(MongoAgent.isListDatabasesAuthorizationFailure(
mongoCommandError(0, "Unauthorized", "not authorized")
));
assertFalse(MongoAgent.isListDatabasesAuthorizationFailure(
mongoCommandError(11600, "InterruptedAtShutdown", "operation was interrupted")
));
assertFalse(MongoAgent.isListDatabasesAuthorizationFailure(
new IllegalStateException("Not connected")
));
}
private static MongoCommandException mongoCommandError(int code, String codeName, String message) {
return new MongoCommandException(
BsonDocument.parse("{\"ok\": 0, \"errmsg\": \"" + message + "\", \"code\": " + code
+ ", \"codeName\": \"" + codeName + "\"}"),
new ServerAddress("192.168.80.146", 27017)
);
}
private static JsonObject minimalConnection() {
JsonObject conn = new JsonObject();
conn.addProperty("host", "127.0.0.1");