Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<nextcloud_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.
71 changes: 70 additions & 1 deletion lib/Search/ProfileFieldDirectorySearchService.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,14 +114,83 @@ 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<array{
* user_uid: string,
* display_name: string,
* matched_fields: list<array{field_key: string, field_label: string, value: string}>
* }>}
*/
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;
if (is_array($scalar) || is_object($scalar) || $scalar === null) {
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 {
Expand Down
6 changes: 5 additions & 1 deletion lib/Search/ProfileFieldSearchProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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/<MCP_MAILBOX_FIELD_ID>"
| 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/<MCP_DECISION_FIELD_ID>"
| 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 |
46 changes: 46 additions & 0 deletions tests/php/Unit/Search/ProfileFieldDirectorySearchServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
19 changes: 19 additions & 0 deletions tests/php/Unit/Search/ProfileFieldSearchProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading