Skip to content

Support authorizedCollections option for listCollections helpers #1270

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Dec 8, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions config/detekt/baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
<ID>LongMethod:KotlinSerializerCodecTest.kt$KotlinSerializerCodecTest$@Test fun testDataClassOptionalBsonValues()</ID>
<ID>MaxLineLength:MapReduceFlow.kt$MapReduceFlow$*</ID>
<ID>MaxLineLength:MapReduceIterable.kt$MapReduceIterable$*</ID>
<ID>MaxLineLength:ListCollectionsFlow.kt$ListCollectionsFlow$*</ID>
<ID>MaxLineLength:ListCollectionsIterable.kt$ListCollectionsIterable$*</ID>
<ID>MaxLineLength:ListCollectionNamesIterable.kt$ListCollectionNamesIterable$*</ID>
<ID>MaxLineLength:ListCollectionNamesFlow.kt$ListCollectionNamesFlow$*</ID>
<ID>SwallowedException:MockitoHelper.kt$MockitoHelper.DeepReflectionEqMatcher$e: Throwable</ID>
<ID>TooManyFunctions:ClientSession.kt$ClientSession : jClientSession</ID>
<ID>TooManyFunctions:FindFlow.kt$FindFlow&lt;T : Any> : Flow</ID>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,10 +307,11 @@ public AsyncWriteOperation<Void> dropIndex(final Bson keys, final DropIndexOptio
}

public <TResult> AsyncReadOperation<AsyncBatchCursor<TResult>> listCollections(final String databaseName, final Class<TResult> resultClass,
final Bson filter, final boolean collectionNamesOnly,
final Bson filter, final boolean collectionNamesOnly, final boolean authorizedCollections,
final Integer batchSize, final long maxTimeMS,
final BsonValue comment) {
return operations.listCollections(databaseName, resultClass, filter, collectionNamesOnly, batchSize, maxTimeMS, comment);
return operations.listCollections(databaseName, resultClass, filter, collectionNamesOnly, authorizedCollections,
batchSize, maxTimeMS, comment);
}

public <TResult> AsyncReadOperation<AsyncBatchCursor<TResult>> listDatabases(final Class<TResult> resultClass, final Bson filter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import com.mongodb.MongoCommandException;
import com.mongodb.MongoNamespace;
import com.mongodb.internal.VisibleForTesting;
import com.mongodb.internal.async.AsyncBatchCursor;
import com.mongodb.internal.async.SingleResultCallback;
import com.mongodb.internal.async.function.AsyncCallbackSupplier;
Expand All @@ -37,6 +38,7 @@
import java.util.function.Supplier;

import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE;
import static com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback;
import static com.mongodb.internal.operation.AsyncOperationHelper.CommandReadTransformerAsync;
import static com.mongodb.internal.operation.AsyncOperationHelper.createReadCommandAndExecuteAsync;
Expand All @@ -49,6 +51,7 @@
import static com.mongodb.internal.operation.CommandOperationHelper.rethrowIfNotNamespaceError;
import static com.mongodb.internal.operation.CursorHelper.getCursorDocumentFromBatchSize;
import static com.mongodb.internal.operation.DocumentHelper.putIfNotNull;
import static com.mongodb.internal.operation.DocumentHelper.putIfTrue;
import static com.mongodb.internal.operation.OperationHelper.LOGGER;
import static com.mongodb.internal.operation.OperationHelper.canRetryRead;
import static com.mongodb.internal.operation.SingleBatchCursor.createEmptySingleBatchCursor;
Expand All @@ -62,6 +65,8 @@
* An operation that provides a cursor allowing iteration through the metadata of all the collections in a database. This operation
* ensures that the value of the {@code name} field of each returned document is the simple name of the collection rather than the full
* namespace.
* <p>
* See <a href="https://docs.mongodb.com/manual/reference/command/listCollections/">{@code listCollections}</a></p>.
*
* <p>This class is not part of the public API and may be removed or changed at any time</p>
*/
Expand All @@ -73,6 +78,7 @@ public class ListCollectionsOperation<T> implements AsyncReadOperation<AsyncBatc
private int batchSize;
private long maxTimeMS;
private boolean nameOnly;
private boolean authorizedCollections;
private BsonValue comment;

public ListCollectionsOperation(final String databaseName, final Decoder<T> decoder) {
Expand Down Expand Up @@ -137,6 +143,20 @@ public ListCollectionsOperation<T> comment(@Nullable final BsonValue comment) {
return this;
}

public ListCollectionsOperation<T> authorizedCollections(final boolean authorizedCollections) {
this.authorizedCollections = authorizedCollections;
return this;
}

/**
* This method is used by tests via the reflection API. See
* {@code com.mongodb.reactivestreams.client.internal.TestHelper.assertOperationIsTheSameAs}.
*/
@VisibleForTesting(otherwise = PRIVATE)
public boolean isAuthorizedCollections() {
return authorizedCollections;
}

@Override
public BatchCursor<T> execute(final ReadBinding binding) {
RetryState retryState = initialRetryState(retryReads);
Expand Down Expand Up @@ -206,6 +226,7 @@ private BsonDocument getCommand() {
if (nameOnly) {
command.append("nameOnly", BsonBoolean.TRUE);
}
putIfTrue(command, "authorizedCollections", authorizedCollections);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed, add a unit test for this.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

The added ListCollectionsOperationTest tests the public method ListCollectionsOperation.execute instead of testing the (currently private) method getCommand. This way it covers more of ListCollectionsOperation. Since mocking is needed for this, I introduced MongoMockito.mock (see its documentation for the detailed explanation and links to demo tests). I demonstrated it to @vbabanin and @rozza, and my understanding was that they liked this improvement over Mockito.mock.

if (maxTimeMS > 0) {
command.put("maxTimeMS", new BsonInt64(maxTimeMS));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -686,12 +686,14 @@ DropIndexOperation dropIndex(final Bson keys, final DropIndexOptions dropIndexOp

<TResult> ListCollectionsOperation<TResult> listCollections(final String databaseName, final Class<TResult> resultClass,
final Bson filter, final boolean collectionNamesOnly,
final boolean authorizedCollections,
@Nullable final Integer batchSize, final long maxTimeMS,
final BsonValue comment) {
return new ListCollectionsOperation<>(databaseName, codecRegistry.get(resultClass))
.retryReads(retryReads)
.filter(toBsonDocument(filter))
.nameOnly(collectionNamesOnly)
.authorizedCollections(authorizedCollections)
.batchSize(batchSize == null ? 0 : batchSize)
.maxTime(maxTimeMS, MILLISECONDS)
.comment(comment);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,11 @@ public WriteOperation<Void> dropIndex(final Bson keys, final DropIndexOptions op

public <TResult> ReadOperation<BatchCursor<TResult>> listCollections(final String databaseName, final Class<TResult> resultClass,
final Bson filter, final boolean collectionNamesOnly,
final boolean authorizedCollections,
@Nullable final Integer batchSize, final long maxTimeMS,
final BsonValue comment) {
return operations.listCollections(databaseName, resultClass, filter, collectionNamesOnly, batchSize, maxTimeMS, comment);
return operations.listCollections(databaseName, resultClass, filter, collectionNamesOnly, authorizedCollections,
batchSize, maxTimeMS, comment);
}

public <TResult> ReadOperation<BatchCursor<TResult>> listDatabases(final Class<TResult> resultClass, final Bson filter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,12 +190,28 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica
collection.size() == 2
}

@IgnoreIf({ serverVersionLessThan(4, 0) })
def 'should only get collection names when nameOnly and authorizedCollections are requested'() {
given:
def operation = new ListCollectionsOperation(databaseName, new DocumentCodec())
.nameOnly(true)
.authorizedCollections(true)
getCollectionHelper().create('collection6', new CreateCollectionOptions())

when:
def cursor = operation.execute(getBinding())
def collection = cursor.next()[0]

then:
collection.size() == 2
}

@IgnoreIf({ serverVersionLessThan(3, 4) || serverVersionAtLeast(4, 0) })
def 'should only get all field names when nameOnly is requested on server versions that do not support nameOnly'() {
given:
def operation = new ListCollectionsOperation(databaseName, new DocumentCodec())
.nameOnly(true)
getCollectionHelper().create('collection6', new CreateCollectionOptions())
getCollectionHelper().create('collection7', new CreateCollectionOptions())

when:
def cursor = operation.execute(getBinding())
Expand All @@ -205,6 +221,21 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica
collection.size() > 2
}

@IgnoreIf({ serverVersionLessThan(4, 0) })
def 'should get all fields when authorizedCollections is requested and nameOnly is not requested'() {
given:
def operation = new ListCollectionsOperation(databaseName, new DocumentCodec())
.nameOnly(false)
.authorizedCollections(true)
getCollectionHelper().create('collection8', new CreateCollectionOptions())

when:
def cursor = operation.execute(getBinding())
def collection = cursor.next()[0]

then:
collection.size() > 2
}

def 'should return collection names if a collection exists asynchronously'() {
given:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 2008-present MongoDB, Inc.
*
* 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.mongodb.kotlin.client.coroutine.syncadapter

import com.mongodb.client.ListCollectionNamesIterable as JListCollectionNamesIterable
import com.mongodb.kotlin.client.coroutine.ListCollectionNamesFlow
import java.util.concurrent.TimeUnit
import org.bson.BsonValue
import org.bson.conversions.Bson

data class SyncListCollectionNamesIterable(val wrapped: ListCollectionNamesFlow) :
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is based on com.mongodb.kotlin.client.coroutine.syncadapter.SyncListCollectionsIterable.

JListCollectionNamesIterable, SyncMongoIterable<String>(wrapped) {

override fun batchSize(batchSize: Int): SyncListCollectionNamesIterable = apply { wrapped.batchSize(batchSize) }

override fun maxTime(maxTime: Long, timeUnit: TimeUnit): SyncListCollectionNamesIterable = apply {
wrapped.maxTime(maxTime, timeUnit)
}

override fun filter(filter: Bson?): SyncListCollectionNamesIterable = apply { wrapped.filter(filter) }

override fun comment(comment: String?): SyncListCollectionNamesIterable = apply { wrapped.comment(comment) }

override fun comment(comment: BsonValue?): SyncListCollectionNamesIterable = apply { wrapped.comment(comment) }

override fun authorizedCollections(authorizedCollections: Boolean): SyncListCollectionNamesIterable = apply {
wrapped.authorizedCollections(authorizedCollections)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,8 @@ package com.mongodb.kotlin.client.coroutine.syncadapter
import com.mongodb.ReadConcern
import com.mongodb.ReadPreference
import com.mongodb.WriteConcern
import com.mongodb.client.AggregateIterable
import com.mongodb.client.ChangeStreamIterable
import com.mongodb.client.ClientSession
import com.mongodb.client.ListCollectionsIterable
import com.mongodb.client.MongoCollection
import com.mongodb.client.*
import com.mongodb.client.MongoDatabase as JMongoDatabase
import com.mongodb.client.MongoIterable
import com.mongodb.client.model.CreateCollectionOptions
import com.mongodb.client.model.CreateViewOptions
import com.mongodb.kotlin.client.coroutine.MongoDatabase
Expand Down Expand Up @@ -102,10 +97,11 @@ data class SyncMongoDatabase(val wrapped: MongoDatabase) : JMongoDatabase {

override fun drop(clientSession: ClientSession) = runBlocking { wrapped.drop(clientSession.unwrapped()) }

override fun listCollectionNames(): MongoIterable<String> = SyncMongoIterable(wrapped.listCollectionNames())
override fun listCollectionNames(): ListCollectionNamesIterable =
SyncListCollectionNamesIterable(wrapped.listCollectionNames())

override fun listCollectionNames(clientSession: ClientSession): MongoIterable<String> =
SyncMongoIterable(wrapped.listCollectionNames(clientSession.unwrapped()))
override fun listCollectionNames(clientSession: ClientSession): ListCollectionNamesIterable =
SyncListCollectionNamesIterable(wrapped.listCollectionNames(clientSession.unwrapped()))

override fun listCollections(): ListCollectionsIterable<Document> =
SyncListCollectionsIterable(wrapped.listCollections())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright 2008-present MongoDB, Inc.
*
* 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.mongodb.kotlin.client.coroutine

import com.mongodb.reactivestreams.client.ListCollectionNamesPublisher
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.reactive.asFlow
import org.bson.BsonValue
import org.bson.conversions.Bson

/**
* Flow for listing collection names.
*
* @see [List collections](https://www.mongodb.com/docs/manual/reference/command/listCollections/)
* @since 5.0
*/
public class ListCollectionNamesFlow(private val wrapped: ListCollectionNamesPublisher) :
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is based on com.mongodb.kotlin.client.coroutine.ListCollectionsFlow.

Flow<String> by wrapped.asFlow() {
/**
* Sets the maximum execution time on the server for this operation.
*
* @param maxTime the max time
* @param timeUnit the time unit, defaults to Milliseconds
* @return this
* @see [Max Time](https://www.mongodb.com/docs/manual/reference/operator/meta/maxTimeMS/)
*/
public fun maxTime(maxTime: Long, timeUnit: TimeUnit = TimeUnit.MILLISECONDS): ListCollectionNamesFlow = apply {
wrapped.maxTime(maxTime, timeUnit)
}

/**
* Sets the number of documents to return per batch.
*
* @param batchSize the batch size
* @return this
* @see [Batch Size](https://www.mongodb.com/docs/manual/reference/method/cursor.batchSize/#cursor.batchSize)
*/
public fun batchSize(batchSize: Int): ListCollectionNamesFlow = apply { wrapped.batchSize(batchSize) }

/**
* Sets the query filter to apply to the returned database names.
*
* @param filter the filter, which may be null.
* @return this
*/
public fun filter(filter: Bson?): ListCollectionNamesFlow = apply { wrapped.filter(filter) }

/**
* Sets the comment for this operation. A null value means no comment is set.
*
* @param comment the comment
* @return this
*/
public fun comment(comment: String?): ListCollectionNamesFlow = apply { wrapped.comment(comment) }

/**
* Sets the comment for this operation. A null value means no comment is set.
*
* @param comment the comment
* @return this
*/
public fun comment(comment: BsonValue?): ListCollectionNamesFlow = apply { wrapped.comment(comment) }

/**
* Sets the `authorizedCollections` field of the `listCollections` command.
*
* @param authorizedCollections If `true`, allows executing the `listCollections` command, which has the `nameOnly`
* field set to `true`, without having the
* [`listCollections` privilege](https://docs.mongodb.com/manual/reference/privilege-actions/#mongodb-authaction-listCollections)
* on the database resource.
* @return `this`.
*/
public fun authorizedCollections(authorizedCollections: Boolean): ListCollectionNamesFlow = apply {
wrapped.authorizedCollections(authorizedCollections)
}

public override suspend fun collect(collector: FlowCollector<String>): Unit = wrapped.asFlow().collect(collector)
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ import com.mongodb.client.model.CreateCollectionOptions
import com.mongodb.client.model.CreateViewOptions
import com.mongodb.reactivestreams.client.MongoDatabase as JMongoDatabase
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.reactive.asFlow
import kotlinx.coroutines.reactive.awaitFirstOrNull
import kotlinx.coroutines.reactive.awaitSingle
import org.bson.Document
Expand Down Expand Up @@ -236,17 +234,19 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) {
* Gets the names of all the collections in this database.
*
* @return an iterable containing all the names of all the collections in this database
* @see [listCollections](https://www.mongodb.com/docs/manual/reference/command/listCollections)
*/
public fun listCollectionNames(): Flow<String> = wrapped.listCollectionNames().asFlow()
public fun listCollectionNames(): ListCollectionNamesFlow = ListCollectionNamesFlow(wrapped.listCollectionNames())

/**
* Gets the names of all the collections in this database.
*
* @param clientSession the client session with which to associate this operation
* @return an iterable containing all the names of all the collections in this database
* @see [listCollections](https://www.mongodb.com/docs/manual/reference/command/listCollections)
*/
public fun listCollectionNames(clientSession: ClientSession): Flow<String> =
wrapped.listCollectionNames(clientSession.wrapped).asFlow()
public fun listCollectionNames(clientSession: ClientSession): ListCollectionNamesFlow =
ListCollectionNamesFlow(wrapped.listCollectionNames(clientSession.wrapped))

/**
* Gets all the collections in this database.
Expand Down
Loading