Skip to content
Merged
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
87 changes: 66 additions & 21 deletions lib/Handler/DocMdpHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

use OCA\Libresign\Db\File;
use OCA\Libresign\Enum\DocMdpLevel;
use OCA\Libresign\Vendor\LibreSign\PdfSignatureValidator\Parser\PdfSignatureInventoryReader;
use OCP\IL10N;

class DocMdpHandler {
Expand Down Expand Up @@ -74,6 +75,11 @@ public function extractDocMdpData($resource): array {
/**
* Extract DocMDP permission level from PDF
*
* The level comes from the certification signature the document uses,
* found by following the PDF structure. A signature dictionary that nothing
* points to does not count. When the structure cannot be read, the level
* comes from the text checks below.
*
* Validates ISO 32000-1 compliance:
* - 12.8.2.2.1: Only ONE DocMDP signature allowed
* - 12.8.2.2.1: DocMDP must be FIRST certifying signature
Expand All @@ -87,6 +93,13 @@ private function extractDocMdpLevel($pdfResource): DocMdpLevel {
rewind($pdfResource);
$content = stream_get_contents($pdfResource);

$inventory = (new PdfSignatureInventoryReader())->readFromString($content);
if ($inventory->isConclusive) {
return $inventory->docMdpPermission === null
? DocMdpLevel::NOT_CERTIFIED
: DocMdpLevel::from($inventory->docMdpPermission->value);
}

$isoStatus = $this->getIsoComplianceStatus($content);
if (!$this->isIsoCompliant($isoStatus) && !$this->isOnlySingleDocMdpViolation($isoStatus)) {
return DocMdpLevel::NOT_CERTIFIED;
Expand Down Expand Up @@ -235,29 +248,32 @@ private function validateTransformParamsVersion(string $content, string $context

private function detectModifications($pdfResource): array {
rewind($pdfResource);
$content = stream_get_contents($pdfResource);
$content = (string)stream_get_contents($pdfResource);
$fileSize = strlen($content);

preg_match_all(
'/ByteRange\s*\[\s*(?<offset1>\d+)\s+(?<length1>\d+)\s+(?<offset2>\d+)\s+(?<length2>\d+)\s*\]/',
$content,
$byteRanges,
PREG_SET_ORDER
);

if (empty($byteRanges)) {
return [
'modified' => false,
'revisionCount' => 0,
'details' => [],
];
$inventory = (new PdfSignatureInventoryReader())->readFromString($content);
$coveredEnds = [];
if ($inventory->isConclusive) {
foreach ($inventory->activeSignatures as $signature) {
$coveredEnds[] = $signature->signedRevisionEnd;
}
} else {
// Compatibility fallback for PDFs whose object graph cannot be parsed.
// These ranges must not authorize the strict validation-data exemption.
preg_match_all(
'/ByteRange\s*\[\s*(?<offset1>\d+)\s+(?<length1>\d+)\s+(?<offset2>\d+)\s+(?<length2>\d+)\s*\]/',
$content,
$byteRanges,
PREG_SET_ORDER
);
foreach ($byteRanges as $range) {
$coveredEnds[] = (int)$range['offset2'] + (int)$range['length2'];
}
}

$modifications = [];
foreach ($byteRanges as $index => $range) {
$coveredEnd = (int)$range['offset2'] + (int)$range['length2'];
foreach ($coveredEnds as $index => $coveredEnd) {
$hasModifications = $coveredEnd < $fileSize;

$modifications[] = [
'signatureIndex' => $index,
'modified' => $hasModifications,
Expand All @@ -267,11 +283,9 @@ private function detectModifications($pdfResource): array {
];
}

$isModified = array_reduce($modifications, fn ($carry, $item) => $carry || $item['modified'], false);

return [
'modified' => $isModified,
'revisionCount' => count($byteRanges),
'modified' => array_reduce($modifications, fn ($carry, $item) => $carry || $item['modified'], false),
'revisionCount' => count($coveredEnds),
'details' => $modifications,
];
}
Expand Down Expand Up @@ -301,6 +315,15 @@ private function validateModifications(DocMdpLevel $docmdpLevel, array $modifica
);
}

if ($this->hasOnlyValidationDataUpdatesFromInventory($pdfResource)) {
// TRANSLATORS Validation result for a certified PDF where, after signing, only long-term validation data (DSS: certificates, CRLs, OCSP responses) or document timestamps were added. DocMDP (document modification policy) permits this at every level.
return $this->buildValidationResult(
true,
File::MODIFICATION_ALLOWED,
$this->l10n->t('Only validation data or document timestamps were added after signing (allowed by DocMDP)')
);
}

$modificationType = $this->analyzeModificationType($pdfResource, $modificationInfo);
$allowedTypes = self::ALLOWED_MODIFICATIONS[$docmdpLevel->name] ?? null;

Expand Down Expand Up @@ -419,6 +442,28 @@ private function analyzeModificationType($pdfResource, array $modificationInfo):
return 'unknown';
}

/**
* Only the active certification signature can define the signed revision.
* An inconclusive inventory cannot grant the validation-data exemption.
*/
private function hasOnlyValidationDataUpdatesFromInventory($pdfResource): bool {
rewind($pdfResource);
$content = (string)stream_get_contents($pdfResource);
$inventory = (new PdfSignatureInventoryReader())->readFromString($content);
if (!$inventory->isConclusive || $inventory->docMdpPermission === null) {
return false;
}
foreach ($inventory->activeSignatures as $signature) {
if ($signature->isCertifying) {
return (new \OCA\Libresign\Vendor\LibreSign\PdfSignatureValidator\Validation\DocMdp\DocMdpValidationDataInspector())->hasOnlyValidationDataUpdates(
$content,
$signature->signedRevisionEnd,
);
}
}
return false;
}

/**
* ISO 32000-1 12.8.2.2.1: A document can contain only one signature field that contains a DocMDP transform method
*/
Expand Down
55 changes: 54 additions & 1 deletion playwright/e2e/footer-policy-hierarchy-ui.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,59 @@ async function ensureFooterTemplateEditorVisible(scope: Page | Locator): Promise
return footerTemplateField
}

/**
* Choose a group through the real NcSelectUsers dropdown. The server already
* filters results by group ID, so wait for those results and use the select's
* own dropdown control if asynchronous updates have closed the menu.
*/
async function selectGroupTargetWithOpenDropdown(dialogScope: Locator, target: string): Promise<void> {
const page = dialogScope.page()
const picker = dialogScope.locator('.nc-select-users').first()
const searchInput = picker.getByRole('combobox')
await expect(searchInput).toBeVisible({ timeout: 8000 })

const searchResponse = page.waitForResponse((response) => {
return response.url().includes('/cloud/groups/details')
&& new URL(response.url()).searchParams.get('search') === target
}, { timeout: 15000 })

await searchInput.fill(target)
const response = await searchResponse
expect(response.ok(), `Failed to search group target ${target}: ${response.status()}`).toBe(true)
const body = await response.json() as { ocs?: { data?: { groups?: Array<{ id: string, displayname?: string }> } } }
const matchingGroup = body.ocs?.data?.groups?.find((group) => group.id === target)
expect(matchingGroup, `OCS returned no matching group for ${target}`).toBeDefined()
const groupLabel = matchingGroup?.displayname || target

await expect(picker).not.toHaveClass(/vs--loading/, { timeout: 8000 })
const option = page.getByRole('option', { name: new RegExp(escapeRegExp(groupLabel), 'i') }).first()
if (await searchInput.getAttribute('aria-expanded') !== 'true') {
// Clicking the dropdown indicator uses vue-select's actual mouse
// handler, which opens the list and restores focus to its search input.
await picker.locator('.vs__open-indicator-button').click()
}
try {
await expect(searchInput).toHaveAttribute('aria-expanded', 'true', { timeout: 8000 })
} catch (error) {
// Report real picker state without weakening the failed assertion.
const state = await picker.evaluate((element) => {
const input = element.querySelector<HTMLInputElement>('[role="combobox"]')
return {
classes: element.className,
expanded: input?.getAttribute('aria-expanded'),
focused: input === document.activeElement,
localOptions: element.querySelectorAll('[role="option"]').length,
dropdown: element.querySelectorAll('.vs__dropdown-menu').length,
}
})
console.error('Group picker state after reopening:', JSON.stringify(state))
throw error
}
await expect(option).toBeVisible({ timeout: 8000 })
await option.click()
await expect(picker.locator('.vs__selected').filter({ hasText: groupLabel })).toBeVisible()
}

async function createFooterRuleViaUi(
page: Page,
scopeName: 'Group' | 'User',
Expand All @@ -280,7 +333,7 @@ async function createFooterRuleViaUi(
await expect(createRuleDialog).toBeVisible({ timeout: 10000 })

if (scopeName === 'Group') {
await selectTarget(createRuleDialog, 'group', target)
await selectGroupTargetWithOpenDropdown(createRuleDialog, target)
} else {
await selectTarget(createRuleDialog, 'user', target)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,66 @@ describe('useRealPolicyWorkbench', () => {
])
})

it('keeps the latest group search after a slow preload completes', async () => {
let resolvePreload!: (value: unknown) => void
const preload = new Promise((resolve) => {
resolvePreload = resolve
})
axiosGet.mockImplementation((url: string, options: { params?: { search?: string } } = {}) => {
if (url === 'cloud/groups/details') {
return options.params?.search === ''
? preload
: Promise.resolve({ data: { ocs: { data: { groups: [
{ id: 'new-group', displayname: 'New Group' },
] } } } })
}
return Promise.resolve({ data: { ocs: { data: { users: {} } } } })
})

const state = createRealPolicyWorkbenchState()
state.openSetting('signature_flow')
state.startEditor({ scope: 'group' })
state.searchAvailableTargets('new-group')
await vi.waitFor(() => expect(state.availableTargets.map((target) => target.id)).toEqual(['new-group']))
expect(state.loadingTargets).toBe(false)

resolvePreload({ data: { ocs: { data: { groups: [{ id: 'old-group', displayname: 'Old Group' }] } } } })
await Promise.resolve()
await Promise.resolve()
expect(state.availableTargets.map((target) => target.id)).toEqual(['new-group'])
})

it('keeps the latest user search after a slow preload completes', async () => {
let resolvePreload!: (value: unknown) => void
const preload = new Promise((resolve) => {
resolvePreload = resolve
})
axiosGet.mockImplementation((url: string, options: { params?: { search?: string } } = {}) => {
if (url === 'cloud/users/details') {
return options.params?.search === ''
? preload
: Promise.resolve({ data: { ocs: { data: { users: {
newUser: { id: 'new-user', displayname: 'New User' },
} } } } })
}
return Promise.resolve({ data: { ocs: { data: { groups: [] } } } })
})

const state = createRealPolicyWorkbenchState()
state.openSetting('signature_flow')
state.startEditor({ scope: 'user' })
state.searchAvailableTargets('new-user')
await vi.waitFor(() => expect(state.availableTargets.map((target) => target.id)).toEqual(['new-user']))
expect(state.loadingTargets).toBe(false)

resolvePreload({ data: { ocs: { data: { users: {
oldUser: { id: 'old-user', displayname: 'Old User' },
} } } } })
await Promise.resolve()
await Promise.resolve()
expect(state.availableTargets.map((target) => target.id)).toEqual(['new-user'])
})

it('loads group targets using cloud/groups for group-admin without exception fallback', async () => {
currentUserState.isAdmin = false

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
<NcSelectUsers
:model-value="selectedTargetOptions"
:options="availableTargets"
:filterable="false"
:append-to-body="false"
:aria-label="targetScopeLabel"
:placeholder="targetScopeSearchPlaceholder"
:loading="loadingTargets"
Expand Down Expand Up @@ -145,9 +147,9 @@
(e: 'cancel'): void
}>()

// TRANSLATORS Secondary button label in the policy rule editor that returns to the previous step where the user chooses the rule type.

Check warning on line 150 in src/views/Settings/PolicyWorkbench/Catalog/components/PolicyRuleEditorPanel.vue

View workflow job for this annotation

GitHub Actions / NPM lint

Boolean prop should only be defaulted to false
const backButtonLabel = t('libresign', '← Back')

Check warning on line 151 in src/views/Settings/PolicyWorkbench/Catalog/components/PolicyRuleEditorPanel.vue

View workflow job for this annotation

GitHub Actions / NPM lint

Boolean prop should only be defaulted to false
// TRANSLATORS Primary button label in edit mode of the policy rule editor. It saves changes to the current rule.

Check warning on line 152 in src/views/Settings/PolicyWorkbench/Catalog/components/PolicyRuleEditorPanel.vue

View workflow job for this annotation

GitHub Actions / NPM lint

Boolean prop should only be defaulted to false
const saveChangesButtonLabel = t('libresign', 'Save changes')
// TRANSLATORS Primary button label in create mode of the policy rule editor. It creates a new policy rule.
const createRuleButtonLabel = t('libresign', 'Create rule')
Expand Down
24 changes: 19 additions & 5 deletions src/views/Settings/PolicyWorkbench/useRealPolicyWorkbench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,12 @@ export function createRealPolicyWorkbenchState() {
const groups = ref<PolicyTargetOption[]>([])
const users = ref<PolicyTargetOption[]>([])
const canManageGroups = ref<boolean | null>(null)
const loadingTargets = ref(false)
const loadingGroups = ref(false)
const loadingUsers = ref(false)
const loadingTargets = computed(() => editorDraft.value?.scope === 'group'
? loadingGroups.value
: editorDraft.value?.scope === 'user' && loadingUsers.value)
const targetRequestVersion = { group: 0, user: 0 }
const rulesLoading = ref(false)
const hydratePersistedRulesRequestId = ref(0)
const editorInitialSnapshot = ref('')
Expand Down Expand Up @@ -1132,28 +1137,37 @@ export function createRealPolicyWorkbenchState() {
}

async function loadTargets(scope: 'group' | 'user', query = '', includeAll = false) {
loadingTargets.value = true
const requestId = ++targetRequestVersion[scope]
const loading = scope === 'group' ? loadingGroups : loadingUsers
loading.value = true
try {
if (scope === 'group') {
const fetchedGroups = includeAll && query === ''
? await fetchAllTargets('group')
: await fetchGroups(query)
groups.value = mergeSelectedTargets('group', fetchedGroups)
if (requestId === targetRequestVersion.group) {
groups.value = mergeSelectedTargets('group', fetchedGroups)
}
return
}

const fetchedUsers = includeAll && query === ''
? await fetchAllTargets('user')
: await fetchUsers(query)
users.value = mergeSelectedTargets('user', fetchedUsers)
if (requestId === targetRequestVersion.user) {
users.value = mergeSelectedTargets('user', fetchedUsers)
}
} catch (error) {
logger.debug('Could not load policy workbench targets', {
error,
scope,
query,
})
} finally {
loadingTargets.value = false
// Only the newest request can end the loading state for this scope.
if (requestId === targetRequestVersion[scope]) {
loading.value = false
}
}
}

Expand Down
Loading
Loading