From 4a6e05d9953c51152f81e8d1046f8355b9e6444a Mon Sep 17 00:00:00 2001 From: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:27:59 -0300 Subject: [PATCH] feat(profile_fields): add admin exact-UID lookup to global search Expose populated administrative profile fields through Nextcloud search using uid:. Return paginated field results and deny private lookups to non-admins. Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> (cherry picked from commit 28974e9b0661719fa372c0fb9ba19ac3d907b3e0) Signed-off-by: Vitor Mattos <1079143+vitormattos@users.noreply.github.com> --- README.md | 18 +++++ .../ProfileFieldDirectorySearchService.php | 71 ++++++++++++++++++- lib/Search/ProfileFieldSearchProvider.php | 6 +- .../api/profile_fields_unified_search.feature | 52 ++++++++++++++ ...ProfileFieldDirectorySearchServiceTest.php | 46 ++++++++++++ .../Search/ProfileFieldSearchProviderTest.php | 19 +++++ 6 files changed, 210 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 129f3433..5fe1c8cc 100644 --- a/README.md +++ b/README.md @@ -52,3 +52,21 @@ Run the app commands from the Nextcloud stack root, not from the host PHP enviro ### Workflow automation ![Workflow automation](img/screenshots/workflow-notify-admins.png) + +## Nextcloud global search integration + +Profile Fields already registers the `profile_fields.directory` provider in Nextcloud global +search. MCP clients that consume Nextcloud's global search can use this provider +without any connector-specific modification. Searches match stored field values, +respecting field visibility and the caller's Nextcloud privileges. + +For administrative inspection of a single profile, an **instance administrator** can +search for `uid:` with provider `profile_fields.directory`. The +results contain one populated field per paginated search entry, including hidden +admin-managed fields. Group administrators and regular users receive no results +from this exact-UID lookup. Normal directory search behavior is unchanged. + +This is a read-only discovery interface, **not** a mailbox provisioning API or a +bulk-export mechanism. Use the existing `profile_fields:data:import --dry-run` and +`profile_fields:data:import` commands for validated, idempotent administrative +imports. Never infer a cooperado's approval from a technical mailbox match. diff --git a/lib/Search/ProfileFieldDirectorySearchService.php b/lib/Search/ProfileFieldDirectorySearchService.php index cf63b5a4..495d39e7 100644 --- a/lib/Search/ProfileFieldDirectorySearchService.php +++ b/lib/Search/ProfileFieldDirectorySearchService.php @@ -114,6 +114,75 @@ public function search(?IUser $actor, string $term, int $limit, int $offset): ar ]; } + /** + * Inspect one user's populated fields via the global search provider. + * + * Each field is a separate paginated search result, so connectors that + * consume search snippets do not silently lose fields from a profile. + * This privileged lookup deliberately returns nothing to non-admins. + * + * @return array{total: int, items: list + * }>} + */ + public function searchByUserUid(?IUser $actor, string $userUid, int $limit, int $offset): array { + if ($limit < 1) { + throw new InvalidArgumentException('limit must be greater than 0'); + } + if ($offset < 0) { + throw new InvalidArgumentException('offset must be greater than or equal to 0'); + } + + $actorUid = $actor?->getUID(); + if ($actorUid === null || !$this->groupManager->isAdmin($actorUid)) { + return ['total' => 0, 'items' => []]; + } + + $userUid = trim($userUid); + if ($userUid === '') { + return ['total' => 0, 'items' => []]; + } + $user = $this->userManager->get($userUid); + if ($user === null) { + return ['total' => 0, 'items' => []]; + } + + $definitions = []; + foreach ($this->fieldDefinitionService->findActiveOrdered() as $definition) { + $definitions[$definition->getId()] = $definition; + } + + $items = []; + foreach ($this->fieldValueMapper->findByUserUid($userUid) as $fieldValue) { + $definition = $definitions[$fieldValue->getFieldDefinitionId()] ?? null; + if ($definition === null) { + continue; + } + + $scalarValue = $this->extractScalarValue($fieldValue); + if ($scalarValue === null) { + continue; + } + + $items[] = [ + 'user_uid' => $userUid, + 'display_name' => $this->resolveDisplayName($user, $userUid), + 'matched_fields' => [[ + 'field_key' => $definition->getFieldKey(), + 'field_label' => $definition->getLabel(), + 'value' => $scalarValue, + ]], + ]; + } + + return [ + 'total' => count($items), + 'items' => array_slice($items, $offset, $limit), + ]; + } + private function extractScalarValue(FieldValue $value): ?string { $decoded = json_decode($value->getValueJson(), true); $scalar = $decoded['value'] ?? null; @@ -121,7 +190,7 @@ private function extractScalarValue(FieldValue $value): ?string { return null; } - return trim((string)$scalar); + return is_bool($scalar) ? ($scalar ? 'true' : 'false') : trim((string)$scalar); } private function isSearchableForActor(FieldExposurePolicy $exposurePolicy, string $currentVisibility, bool $actorIsAdmin, bool $actorIsAuthenticated): bool { diff --git a/lib/Search/ProfileFieldSearchProvider.php b/lib/Search/ProfileFieldSearchProvider.php index 0d5be329..899f2322 100644 --- a/lib/Search/ProfileFieldSearchProvider.php +++ b/lib/Search/ProfileFieldSearchProvider.php @@ -50,7 +50,11 @@ public function search(IUser $user, ISearchQuery $query): SearchResult { } $cursor = $this->normalizeCursor($query->getCursor()); - $result = $this->searchService->search($user, $term, $query->getLimit(), $cursor); + if (str_starts_with(mb_strtolower($term), 'uid:')) { + $result = $this->searchService->searchByUserUid($user, substr($term, 4), $query->getLimit(), $cursor); + } else { + $result = $this->searchService->search($user, $term, $query->getLimit(), $cursor); + } $entries = array_map(fn (array $item): SearchResultEntry => $this->buildEntry($item), $result['items']); if ($cursor + count($entries) >= $result['total']) { return SearchResult::complete($this->getName(), $entries); diff --git a/tests/integration/features/api/profile_fields_unified_search.feature b/tests/integration/features/api/profile_fields_unified_search.feature index 2f44df06..f400d50f 100644 --- a/tests/integration/features/api/profile_fields_unified_search.feature +++ b/tests/integration/features/api/profile_fields_unified_search.feature @@ -137,3 +137,55 @@ Feature: profile fields unified search | (jq).ocs.data.entries[0].subline | Unified Region Hidden: LATAM - Hidden | | (jq).ocs.data.entries[1].title | profileviewer-displayname | | (jq).ocs.data.entries[1].subline | Unified Region Private: LATAM - Private | + + Scenario: admins can inspect each hidden field of an exact UID with pagination + Given as user "admin" + When sending "post" to ocs "/apps/profile_fields/api/v1/definitions" + | fieldKey | mailcow_mailbox | + | label | Mailbox | + | type | email | + | editPolicy | admins | + | exposurePolicy | hidden | + | sortOrder | 10 | + | active | true | + Then the response should have a status code 201 + And fetch field "(MCP_MAILBOX_FIELD_ID)(jq).ocs.data.id" from previous JSON response + When sending "post" to ocs "/apps/profile_fields/api/v1/definitions" + | fieldKey | mail_admin_decision | + | label | Authorization | + | type | text | + | editPolicy | admins | + | exposurePolicy | hidden | + | sortOrder | 20 | + | active | true | + Then the response should have a status code 201 + And fetch field "(MCP_DECISION_FIELD_ID)(jq).ocs.data.id" from previous JSON response + When sending "put" to ocs "/apps/profile_fields/api/v1/users/profileuser/values/" + | value | test@example.org | + | currentVisibility | private | + Then the response should have a status code 200 + When sending "put" to ocs "/apps/profile_fields/api/v1/users/profileuser/values/" + | value | pending | + | currentVisibility | private | + Then the response should have a status code 200 + When sending "get" to ocs "/search/providers/profile_fields.directory/search?term=uid%3Aprofileuser&limit=1&from=/settings/users" + Then the response should have a status code 200 + And the response should be a JSON array with the following mandatory values + | key | value | + | (jq).ocs.data.isPaginated | true | + | (jq).ocs.data.cursor | 1 | + | (jq).ocs.data.entries | (jq)length == 1 | + | (jq).ocs.data.entries[0].subline | Mailbox: test@example.org | + When sending "get" to ocs "/search/providers/profile_fields.directory/search?term=uid%3Aprofileuser&limit=1&cursor=1&from=/settings/users" + Then the response should have a status code 200 + And the response should be a JSON array with the following mandatory values + | key | value | + | (jq).ocs.data.isPaginated | false | + | (jq).ocs.data.entries | (jq)length == 1 | + | (jq).ocs.data.entries[0].subline | Authorization: pending | + Given as user "profileviewer" + When sending "get" to ocs "/search/providers/profile_fields.directory/search?term=uid%3Aprofileuser&from=/settings/users" + Then the response should have a status code 200 + And the response should be a JSON array with the following mandatory values + | key | value | + | (jq).ocs.data.entries | (jq)length == 0 | diff --git a/tests/php/Unit/Search/ProfileFieldDirectorySearchServiceTest.php b/tests/php/Unit/Search/ProfileFieldDirectorySearchServiceTest.php index 222ee8d8..9d714732 100644 --- a/tests/php/Unit/Search/ProfileFieldDirectorySearchServiceTest.php +++ b/tests/php/Unit/Search/ProfileFieldDirectorySearchServiceTest.php @@ -164,6 +164,52 @@ public function testSearchSupportsPagination(): void { $this->assertSame('bruno', $result['items'][0]['user_uid']); } + public function testAdminCanInspectAllPopulatedFieldsForExactUidWithPagination(): void { + $actor = $this->createMock(IUser::class); + $actor->method('getUID')->willReturn('admin'); + $this->groupManager->expects($this->once())->method('isAdmin')->with('admin')->willReturn(true); + $this->userManager->expects($this->once())->method('get')->with('alice')->willReturn($this->buildUser('Alice Doe')); + + $mailbox = $this->buildDefinition(1, 'mailcow_mailbox', 'Mailbox', userVisible: false); + $status = $this->buildDefinition(2, 'mail_provisioning_status', 'Authorization status', userVisible: false); + $disabled = $this->buildDefinition(3, 'archived_mail_status', 'Archived status', userVisible: false); + $disabled->setActive(false); + $this->fieldDefinitionService->expects($this->once())->method('findActiveOrdered')->willReturn([$mailbox, $status]); + $this->fieldValueMapper->expects($this->once())->method('findByUserUid')->with('alice')->willReturn([ + $this->buildValue(1, 'alice', 'private', 'alice@example.org'), + $this->buildValue(2, 'alice', 'private', 'pending'), + $this->buildValue(3, 'alice', 'private', 'ignore-me'), + ]); + + $result = $this->service->searchByUserUid($actor, 'alice', 1, 1); + $this->assertSame(2, $result['total']); + $this->assertCount(1, $result['items']); + $this->assertSame('alice', $result['items'][0]['user_uid']); + $this->assertSame('Alice Doe', $result['items'][0]['display_name']); + $this->assertSame('mail_provisioning_status', $result['items'][0]['matched_fields'][0]['field_key']); + $this->assertSame('pending', $result['items'][0]['matched_fields'][0]['value']); + } + + public function testNonAdminCannotLookupPrivateFieldsByUid(): void { + $actor = $this->createMock(IUser::class); + $actor->method('getUID')->willReturn('groupadmin'); + $this->groupManager->expects($this->once())->method('isAdmin')->with('groupadmin')->willReturn(false); + $this->fieldValueMapper->expects($this->never())->method('findByUserUid'); + $this->fieldDefinitionService->expects($this->never())->method('findActiveOrdered'); + $this->userManager->expects($this->never())->method('get'); + + $this->assertSame(['total' => 0, 'items' => []], $this->service->searchByUserUid($actor, 'alice', 20, 0)); + } + + public function testUnknownUidDoesNotLoadStoredValues(): void { + $actor = $this->createMock(IUser::class); + $actor->method('getUID')->willReturn('admin'); + $this->groupManager->method('isAdmin')->willReturn(true); + $this->userManager->method('get')->with('does-not-exist')->willReturn(null); + $this->fieldValueMapper->expects($this->never())->method('findByUserUid'); + $this->assertSame(['total' => 0, 'items' => []], $this->service->searchByUserUid($actor, 'does-not-exist', 20, 0)); + } + private function buildDefinition(int $id, string $fieldKey, string $label, bool $userVisible = true): FieldDefinition { $definition = new FieldDefinition(); $definition->setId($id); diff --git a/tests/php/Unit/Search/ProfileFieldSearchProviderTest.php b/tests/php/Unit/Search/ProfileFieldSearchProviderTest.php index 42ce1871..16d7c30b 100644 --- a/tests/php/Unit/Search/ProfileFieldSearchProviderTest.php +++ b/tests/php/Unit/Search/ProfileFieldSearchProviderTest.php @@ -159,6 +159,25 @@ public function testSearchBuildsAvatarBackedEntries(): void { $this->assertSame('https://cloud.test/settings/users?search=alice', $entry['resourceUrl']); } + public function testExactUidQueryDelegatesToPrivilegedLookup(): void { + $l10n = $this->buildL10n(); + $urlGenerator = $this->createMock(IURLGenerator::class); + $service = $this->createMock(ProfileFieldDirectorySearchService::class); + $actor = $this->createMock(IUser::class); + $query = $this->createMock(ISearchQuery::class); + $query->method('getTerm')->willReturn('uid:alice'); + $query->method('getLimit')->willReturn(10); + $query->method('getCursor')->willReturn(null); + + $service->expects($this->once())->method('searchByUserUid') + ->with($actor, 'alice', 10, 0) + ->willReturn(['total' => 0, 'items' => []]); + $service->expects($this->never())->method('search'); + + $provider = new ProfileFieldSearchProvider($l10n, $urlGenerator, $service); + $this->assertSame([], $provider->search($actor, $query)->jsonSerialize()['entries']); + } + private function buildL10n(): IL10N&MockObject { $l10n = $this->createMock(IL10N::class); $l10n->method('t')->willReturnCallback(static fn (string $text): string => $text);