-
Notifications
You must be signed in to change notification settings - Fork 46
ENH: meta command - Add Permissions + fix version read on encrypted PDFs #189
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
Open
iamrishu11
wants to merge
7
commits into
py-pdf:main
Choose a base branch
from
iamrishu11:feat/meta-permissions
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
9e7fde4
meta: add Permissions + fix version read on encrypted; tidy Encrypted…
iamrishu11 07d2f15
TST: for the pr #189
iamrishu11 010496e
PI: removed extra table
iamrishu11 dbc29eb
DOC: for new feature and bug
iamrishu11 7d461f7
Update CHANGELOG.md
iamrishu11 b443e83
TST: made the unittest more robust
iamrishu11 26bc83c
TST: fixed file path issue
iamrishu11 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| """ | ||
| Unit tests for metadata module. | ||
| Runs the meta CLI over every PDF in sample-files and checks permissions + header. | ||
| """ | ||
|
|
||
| import json | ||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
|
|
||
| from .conftest import RESOURCES_ROOT, run_cli # provided by repo | ||
|
|
||
| SAMPLE_FILES = RESOURCES_ROOT / "sample-files" | ||
| pytestmark = pytest.mark.skipif( | ||
| not SAMPLE_FILES.exists(), | ||
| reason="sample-files submodule not present", | ||
| ) | ||
|
|
||
| PDFS = sorted(SAMPLE_FILES.rglob("*.pdf"), key=lambda p: p.as_posix()) | ||
|
|
||
|
|
||
| def _expected_permissions_from_pdf(pdf_path: Path) -> str: | ||
| """Compute expected permissions using pypdf, independent of the CLI.""" | ||
| try: | ||
| from pypdf import PdfReader | ||
| try: | ||
| from pypdf.constants import UserAccessPermissions as UAP | ||
| except Exception: | ||
| UAP = None | ||
| except Exception: | ||
| # If pypdf isn't available for some reason, don't fail the test | ||
| return "unknown" | ||
|
|
||
| try: | ||
| reader = PdfReader(str(pdf_path)) | ||
| except Exception: | ||
| return "unknown" | ||
|
|
||
| uap = getattr(reader, "user_access_permissions", None) | ||
| if uap is None: | ||
| return "n/a (unencrypted)" | ||
|
|
||
| # Same labels as pdfly.metadata._format_permissions | ||
| label_map = { | ||
| "PRINT": "print", | ||
| "PRINT_TO_REPRESENTATION": "print-high", | ||
| "MODIFY": "modify", | ||
| "EXTRACT": "extract", | ||
| "ADD_OR_MODIFY": "annotate", | ||
| "FILL_FORM_FIELDS": "fill-forms", | ||
| "EXTRACT_TEXT_AND_GRAPHICS": "accessibility-copy", | ||
| "ASSEMBLE_DOC": "assemble", | ||
| } | ||
|
|
||
| # Prefer to_dict() if available | ||
| to_dict = getattr(uap, "to_dict", None) | ||
| if callable(to_dict): | ||
| try: | ||
| flags = to_dict() | ||
| items = [label_map.get(k, k.lower()) for k, v in flags.items() if v and k in label_map] | ||
| return ", ".join(items) if items else "none (all denied)" | ||
| except Exception: | ||
| pass | ||
|
|
||
| # Fallback: bitmask checks | ||
| if UAP is not None: | ||
| try: | ||
| mask = int(uap) | ||
| checks = [ | ||
| (UAP.PRINT, "print"), | ||
| (UAP.PRINT_TO_REPRESENTATION, "print-high"), | ||
| (UAP.MODIFY, "modify"), | ||
| (UAP.EXTRACT, "extract"), | ||
| (UAP.ADD_OR_MODIFY, "annotate"), | ||
| (UAP.FILL_FORM_FIELDS, "fill-forms"), | ||
| (UAP.EXTRACT_TEXT_AND_GRAPHICS, "accessibility-copy"), | ||
| (UAP.ASSEMBLE_DOC, "assemble"), | ||
| ] | ||
| items = [label for flag, label in checks if (mask & int(flag)) != 0] | ||
| return ", ".join(items) if items else "none (all denied)" | ||
| except Exception: | ||
| pass | ||
|
|
||
| return "unknown" | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "input_pdf", | ||
| PDFS, | ||
| ids=lambda p: p.relative_to(SAMPLE_FILES).as_posix(), | ||
| ) | ||
| def test_meta_command_on_all_sample_pdfs(input_pdf, capsys): | ||
| # Run the CLI | ||
| exit_code = run_cli(["meta", str(input_pdf), "--output", "json"]) | ||
| assert exit_code == 0 | ||
|
|
||
| captured = capsys.readouterr() | ||
| metadata = json.loads(captured.out) | ||
|
|
||
| # Basic invariants / shape | ||
| assert "pdf_file_version" in metadata | ||
| assert metadata["pdf_file_version"].startswith("%PDF-") | ||
| assert "permissions" in metadata | ||
|
|
||
| # Compare permissions to what pypdf says | ||
| actual = metadata["permissions"] | ||
| expected = _expected_permissions_from_pdf(input_pdf) | ||
|
|
||
| if expected in {"n/a (unencrypted)", "none (all denied)", "unknown"}: | ||
| assert actual == expected | ||
| else: | ||
| act_set = {p.strip() for p in actual.split(",") if p.strip()} | ||
| exp_set = {p.strip() for p in expected.split(",") if p.strip()} | ||
| assert act_set == exp_set | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.