Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Issue #995: unlock a restricted document with its permissions password (#1127)

Ridwan5df8f3b33add
diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml
index bd6cd6192..aeeabce2c 100644
--- a/ATTRIBUTION.toml
+++ b/ATTRIBUTION.toml
@@ -19,7 +19,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "e14fad9deb20599267c75e53b3657913f04b349b8e453ee6ee364b5fbb3b6386"
+sha256 = "e6a4d0363f5c146aa030e11d039da5ce62bcf92bbbb6c19d36a14a166d899daa"
[[asset]]
path = "crates/ui-egui/src/i18n/zh-hant.tsv"
@@ -30,7 +30,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "6b236b954c6808da38585ffa4403d5c4654bd254d596c4d0c82963611f9ed74a"
+sha256 = "2f807f925c462447b2c31edac51cd02e0fa3f4a65211db6e9545d9259d8401e1"
[[asset]]
path = "crates/ui-egui/src/i18n/cs.tsv"
@@ -52,7 +52,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "3da0ebbb21fd15393184a8f3ae824b6776e52c3318b0623430ae7a3d56f2234a"
+sha256 = "66f180b1b297afa69030d5bac14d645f5e1faa2ef22f6d19dc0d3e8f78c47162"
[[asset]]
path = "crates/ui-egui/src/i18n/es.tsv"
@@ -63,7 +63,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "e7f44217b71746ce6a0b9349a61752594508208e5aa1633417a492cba73b3f8d"
+sha256 = "892d64bb142fd3b0cba1212ff38669388c5fd4631f7ade07fede78bf9bf38abd"
[[asset]]
path = "crates/ui-egui/src/i18n/fr.tsv"
@@ -74,7 +74,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "8de3262b73b7b581e9db7d3c03305675431f4f9e3845eef04f4fd43ac65201ff"
+sha256 = "a061b5ae287696bee00be6897a79e01c2a00e244ada2cc7471b8bbf839ee8da1"
[[asset]]
path = "crates/ui-egui/src/i18n/de.tsv"
@@ -85,7 +85,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "9860be07e4cef530e85e97d0f160201e1f1f510af3aaefb322aa1c8a9c81af6b"
+sha256 = "d82f65eb81ff866ee637a113dba6ff2929e5ee89abfcac233e44983aa231dd62"
[[asset]]
path = "crates/ui-egui/src/i18n/te.tsv"
@@ -96,7 +96,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Telugu UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "1ee6f975773e1cc628b8552d5e079d9e465e4935c781c95488355ae1b2a6cd96"
+sha256 = "c93373a64b31c7df333d45dd6d734f0a77f6a2daf64a2827c225034eecff997d"
[[asset]]
path = "crates/ui-egui/src/i18n/it.tsv"
@@ -107,7 +107,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "d0110ca54b7de2667939d5e3e9f235364e317a2eb3b5046f7c934fcb686c3980"
+sha256 = "996dbfee4fe322eef73f1e7e419d5bb57289508d05bd77d0a9d0316c9659985e"
[[asset]]
path = "crates/ui-egui/src/i18n/pl.tsv"
@@ -118,7 +118,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Polish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "86f7835d14675695f30fc5aa1037d2a949db25f4635df4a9d8f78e2a1b89fe97"
+sha256 = "be960bdf9b6eeac2d95db91325076ee79c9b2efdcc4e459c7400e7ddb05fab3a"
[[asset]]
path = "crates/ui-egui/src/i18n/ru.tsv"
@@ -129,7 +129,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "fbb4b86a4de843f9f3a66a1b23423694e5615f0581ccb8ef309d567f34d573a4"
+sha256 = "0492e7f97f8ca9d73bfe66e6f115a8323cb0c8548680b2d30a36025d820682f1"
[[asset]]
path = "crates/ui-egui/src/i18n/hu.tsv"
@@ -140,7 +140,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "590e5b3b943f529bbdfb3ee36bd11de053f9ada40b3ec0fc3528ad552b1c7a7a"
+sha256 = "1c8219612b4acd797ea6beffdb04486a0120adcaa88ab327de1a4a165bf4386a"
[[asset]]
path = "crates/ui-egui/src/i18n/bg.tsv"
@@ -151,7 +151,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "112f2cadebcadad7cd80d99fdad0d9ed92ce88f6aaedb5c4388b91eb86e5afb7"
+sha256 = "53acc28351fb74296d9d01b863ff2e20ef93d990ba5f5ee3c00ba8370b9c7a13"
[[asset]]
path = "crates/ui-egui/src/i18n/ja.tsv"
@@ -162,7 +162,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "c7ab8fdfa62aacf315f1b75007ef04bf6aca31401f9d33cb28ffb8f47dede5ed"
+sha256 = "253e22babcf4c3d03fa39b520c99be0aba14c785893472994f91aac0fa457533"
[[asset]]
path = "crates/ui-egui/src/i18n/uk.tsv"
@@ -173,7 +173,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "f4b9277ffc916dd12ff2c7982c0a54e205a797cbecdaa3e44120644598330094"
+sha256 = "08a9d93236c4ad47abb8df65042eeb2aa39935ddc40a53d32d00ab58fe5122b0"
[[asset]]
path = "crates/ui-egui/src/i18n/ar.tsv"
@@ -184,7 +184,7 @@ licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "9e57598e8b9ca7b776e85a257b0813435babe175f8c185361e8d016c11a0d521"
+sha256 = "984e965465bc3e197b130d530abe3ec2e42395fbe67ea4a88f5647ae83d67635"
[[asset]]
path = "assets/icons/accessibility.svg"
diff --git a/ROADMAP.md b/ROADMAP.md
index 59a3e0fd8..7e12431d1 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -139,6 +139,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
Newest first: the date, what moved, and the new overall estimate.
+- **2026-10-11 (#995, #1077, permissions password after opening):** A PDF with only a permissions password opens without asking, restricted, and nothing let the user enter that password afterwards: the notice and the hint pointed at reopening with it. Now the security notice and Properties ▸ Security offer Unlock…, and Change settings / Remove security on a restricted document ask for the permissions password first and then carry on (as Acrobat does). The open password is refused there. `Session::unlock` upgrades the open document in place (owner and user passwords unlock the same file key, so nothing is re-read), unlocks the undo and redo states and reopens saves as owner; it is not an edit and doesn't mark the document unsaved. New command `protect.unlock`; the new strings are in all 15 full catalogs. Tests cover crypt, cos, engine (undo, redo, save, separate open password) and the UI. Still missing: an automation tool for it. Estimates unchanged.
- **2026-10-11 (M14, #307 Plan 3):** Engine open and full refresh use one page/content traversal to populate marks and added content. The independent public scans remain available; the combined scanner borrows direct objects and holds referenced objects through `Arc<Object>` instead of cloning scan-only `/Contents` arrays or `/PCAdded` dictionaries. Differential tests cover an indirect `/PCAdded` dictionary as well as ordering, malformed/direct/indirect/repeated entries and `/UserUnit`. Exact `bbbe600`→final release CLI measurements used 10 alternating pairs: wall-time medians were 183.645→174.440 ms on 10,000 marker-free pages (10/10 wins), 33.587→32.752 ms on 1,500 mixed pages (8/10), and 24.331→20.133 ms on the 100,000-entry array stress fixture (10/10). The stress fixture's maximum-RSS median fell 28,655,616→19,038,208 B; peak-footprint medians were 14,747,136→14,673,408 B. From P0, the follow-up stress run was 20.886→20.201 ms (10/10), with RSS 23,953,408→19,087,360 B and peak footprint 14,706,144→14,697,952 B. `doc_open` stdout hashes matched every pair. The ancillary `organize` binding preserves the prior `prune_legacy` update condition. Estimates unchanged.
- **2026-10-11 (M4, Organize overview):** Opening Organize pages from All tools, Home, the tool palette or `ui.set tool=organize` opens the thumbnail grid directly. Checkboxes toggle individual pages without modifier keys; page controls rotate either way or delete one page, while the toolbar acts on the selection. Portrait and landscape previews retain their aspect ratio. UI and control regressions cover entry, selection, single-page versus batch actions, undo, permissions and retaining the last page. Milestone and effort estimates unchanged.
diff --git a/crates/cos/src/document.rs b/crates/cos/src/document.rs
index afbbbbd8b..6938f82b1 100644
--- a/crates/cos/src/document.rs
+++ b/crates/cos/src/document.rs
@@ -357,10 +357,7 @@ impl Document {
return Ok(());
};
let params = crate::security::encrypt_dict(self, &dict);
- let id0 = match self.trailer.get(b"ID") {
- Some(Object::Array(a)) => a.first().and_then(|s| s.as_string()).map(|s| s.bytes.clone()).unwrap_or_default(),
- _ => Vec::new(),
- };
+ let id0 = self.first_id();
let handler = pdfcraft_crypt::SecurityHandler::open(params, &id0, password).map_err(|e| match e {
pdfcraft_crypt::CryptError::WrongPassword if password.is_none() => CosError::NeedsPassword,
pdfcraft_crypt::CryptError::WrongPassword => CosError::WrongPassword,
@@ -374,6 +371,31 @@ impl Document {
Ok(())
}
+ /// The first file identifier, part of the encryption key (empty when there is none).
+ fn first_id(&self) -> Vec<u8> {
+ match self.trailer.get(b"ID") {
+ Some(Object::Array(a)) => a.first().and_then(|s| s.as_string()).map(|s| s.bytes.clone()).unwrap_or_default(),
+ _ => Vec::new(),
+ }
+ }
+
+ /// Lift the restrictions of a document opened with its user password by entering the
+ /// owner (permissions) password (§7.6.4). Fails with `WrongPassword` for any other
+ /// password. Does nothing when the document is unencrypted or already opened as owner.
+ /// Both passwords unlock the same file key, so nothing read so far is decoded again.
+ pub fn unlock(&mut self, password: &str) -> Result<(), CosError> {
+ let Some(current) = self.security.as_deref() else { return Ok(()) };
+ if current.auth() == pdfcraft_crypt::Auth::Owner {
+ return Ok(());
+ }
+ let owner = current.authenticate_owner(&self.first_id(), password).map_err(|e| match e {
+ pdfcraft_crypt::CryptError::WrongPassword => CosError::WrongPassword,
+ other => CosError::Security(other.to_string()),
+ })?;
+ self.security = Some(Arc::new(owner));
+ Ok(())
+ }
+
/// The security handler, when the document is encrypted.
pub fn security(&self) -> Option<&pdfcraft_crypt::SecurityHandler> {
self.security.as_deref()
diff --git a/crates/cos/tests/encryption.rs b/crates/cos/tests/encryption.rs
index 8f4ee124c..6868a6dc2 100644
--- a/crates/cos/tests/encryption.rs
+++ b/crates/cos/tests/encryption.rs
@@ -102,6 +102,36 @@ fn empty_user_password_opens_but_reports_restrictions() {
assert!(Document::open(Arc::new(fixture())).unwrap().permissions().is_none(), "unencrypted: no restrictions");
}
+#[test]
+fn the_permissions_password_unlocks_an_open_document() {
+ for alg in ALL {
+ // Only a permissions password: opens without asking, restricted (#995).
+ let mut doc = Document::open(Arc::new(protect(alg, "", "perms", 0b0100))).unwrap();
+ // Read something before unlocking: it must stay readable afterwards.
+ assert_eq!(content(&doc), SECRET, "{alg:?}");
+ assert_eq!(doc.unlock("").unwrap_err(), CosError::WrongPassword, "{alg:?}");
+ assert_eq!(doc.unlock("nope").unwrap_err(), CosError::WrongPassword, "{alg:?}");
+ assert!(!doc.permissions().unwrap().modify(), "{alg:?}: still restricted");
+ doc.unlock("perms").unwrap();
+ assert_eq!(doc.security().unwrap().auth(), Auth::Owner, "{alg:?}");
+ assert!(doc.permissions().unwrap().modify(), "{alg:?}");
+ assert_eq!(content(&doc), SECRET, "{alg:?}");
+ assert_eq!(title(&doc).as_deref(), Some("Quarterly numbers"), "{alg:?}");
+ // Unlocked, security can be removed.
+ doc.remove_encryption();
+ let plain = write_full(&doc, &SaveOptions::default()).unwrap();
+ assert!(Document::open(Arc::new(plain)).unwrap().security().is_none(), "{alg:?}");
+ }
+ // Opened with a separate open password: that password doesn't unlock.
+ let mut doc = Document::open_with_password(Arc::new(protect(Algorithm::Aes256, "open", "perms", 0b0100)), Some("open")).unwrap();
+ assert_eq!(doc.unlock("open").unwrap_err(), CosError::WrongPassword);
+ doc.unlock("perms").unwrap();
+ assert!(doc.permissions().unwrap().modify());
+ // Nothing to unlock: unencrypted, or already the owner.
+ Document::open(Arc::new(fixture())).unwrap().unlock("anything").unwrap();
+ doc.unlock("anything").unwrap();
+}
+
#[test]
fn incremental_edits_of_encrypted_documents_stay_encrypted() {
for alg in ALL {
diff --git a/crates/crypt/src/lib.rs b/crates/crypt/src/lib.rs
index 9c2c1dab1..b93fd8255 100644
--- a/crates/crypt/src/lib.rs
+++ b/crates/crypt/src/lib.rs
@@ -180,6 +180,18 @@ impl SecurityHandler {
Ok(Self { dict, key, auth, recovered_user })
}
+ /// Upgrade to owner access with the owner (permissions) password, as when a restricted
+ /// document is unlocked after opening. The user password, or any other, is `WrongPassword`.
+ /// Both passwords unlock the same file key, so what was decrypted so far stays valid; a
+ /// different key is refused too.
+ pub fn authenticate_owner(&self, id0: &[u8], password: &str) -> Result<Self, CryptError> {
+ let owner = Self::open(self.dict.clone(), id0, Some(password))?;
+ if owner.auth != Auth::Owner || owner.key != self.key {
+ return Err(CryptError::WrongPassword);
+ }
+ Ok(owner)
+ }
+
pub fn auth(&self) -> Auth {
self.auth
}
diff --git a/crates/crypt/src/tests.rs b/crates/crypt/src/tests.rs
index dc3a1964b..e940af509 100644
--- a/crates/crypt/src/tests.rs
+++ b/crates/crypt/src/tests.rs
@@ -69,6 +69,29 @@ fn created_encryption_authenticates_owner_and_user() {
}
}
+#[test]
+fn the_owner_password_upgrades_a_user_session() {
+ for alg in ALL {
+ let d = new(alg, "", "secret", 0b0100).dict().clone();
+ let user = SecurityHandler::open(d, ID, None).unwrap();
+ assert!(!user.permissions().modify(), "{alg:?}");
+ // The (empty) user password and wrong ones don't unlock anything.
+ assert_eq!(user.authenticate_owner(ID, "").unwrap_err(), CryptError::WrongPassword, "{alg:?}");
+ assert_eq!(user.authenticate_owner(ID, "nope").unwrap_err(), CryptError::WrongPassword, "{alg:?}");
+ let owner = user.authenticate_owner(ID, "secret").unwrap();
+ assert_eq!(owner.auth(), Auth::Owner, "{alg:?}");
+ assert_eq!(owner.file_key(), user.file_key(), "{alg:?}");
+ assert!(owner.permissions().modify(), "{alg:?}");
+ }
+ // A separate open password is not the permissions password.
+ for alg in ALL {
+ let d = new(alg, "open", "perms", 0b0100).dict().clone();
+ let user = SecurityHandler::open(d, ID, Some("open")).unwrap();
+ assert_eq!(user.authenticate_owner(ID, "open").unwrap_err(), CryptError::WrongPassword, "{alg:?}");
+ assert_eq!(user.authenticate_owner(ID, "perms").unwrap().auth(), Auth::Owner, "{alg:?}");
+ }
+}
+
#[test]
fn empty_user_password_opens_without_asking() {
for alg in ALL {
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 782110cee..b02911de1 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -36,10 +36,14 @@ pub enum Needs {
HasRedactions,
/// The document has page marks of this kind and allows changes.
Marks(crate::MarkKind),
- /// The document's security may be changed (owner, or nothing restricted).
+ /// The document's security may be changed (owner, or nothing restricted), or would be
+ /// once its permissions password is entered.
Security,
- /// The document is protected and its security may be removed.
+ /// The document is protected and its security may be removed (perhaps after entering
+ /// its permissions password).
ProtectedSecurity,
+ /// The document's restrictions can be lifted with its permissions password.
+ Unlock,
/// There is something to undo.
Undo,
/// There is something to redo.
@@ -330,6 +334,7 @@ pub const COMMANDS: &[CommandSpec] = &[
c("edit.background.remove", "Remove background", None, None, Marks(crate::MarkKind::Background), "palette"),
c("protect.password", "Protect using password…", FILE, None, Security, "lock"),
c("protect.remove", "Remove security", FILE, None, ProtectedSecurity, "lock-open"),
+ c("protect.unlock", "Enter permissions password…", None, None, Unlock, "lock-open"),
c("protect.properties", "Security properties…", FILE, None, Document, "shield-check"),
c("page.organize", "Organize pages", PAGES, None, Document, "layout-grid"),
c("bookmark.add", "New bookmark", PAGES, Some(Shortcut::cmd("B")), Assembly, "bookmark-plus"),
@@ -380,8 +385,9 @@ pub fn is_enabled(spec: &CommandSpec, session: &Session, active: Option<DocId>)
HasComments => doc.is_some_and(|d| d.allows_modification() && !d.info.annotations.is_empty()),
HasFields => doc.is_some_and(|d| d.allows_modification() && !d.form.is_empty()),
HasRedactions => doc.is_some_and(|d| d.allows_modification() && d.redaction_marks() > 0),
- Security => doc.is_some_and(|d| d.allows_security_change()),
- ProtectedSecurity => doc.is_some_and(|d| d.allows_security_change() && d.security_summary().is_some()),
+ Security => doc.is_some_and(|d| d.allows_security_change() || d.can_unlock()),
+ ProtectedSecurity => doc.is_some_and(|d| (d.allows_security_change() || d.can_unlock()) && d.security_summary().is_some()),
+ Unlock => doc.is_some_and(|d| d.can_unlock()),
Undo => doc.is_some_and(|d| d.can_undo().is_some()),
Redo => doc.is_some_and(|d| d.can_redo().is_some()),
}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 8b53f0c34..bbf7bbeb8 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -472,6 +472,12 @@ impl Document {
self.editable() && self.permissions().is_none_or(|p| unrestricted(&p))
}
+ /// A password restricts the document and it wasn't opened with the owner password: entering
+ /// that password ([`Session::unlock`]) lifts the restrictions.
+ pub fn can_unlock(&self) -> bool {
+ self.editable() && self.permissions().is_some_and(|p| !unrestricted(&p))
+ }
+
/// A summary of the document's security for Document Properties ▸ Security, including
/// protection applied in this session (written by the next save).
pub fn security_summary(&self) -> Option<SecuritySummary> {
@@ -2016,6 +2022,8 @@ pub enum EditError {
Measure(#[from] measure::MeasureError),
#[error("{0}")]
Protection(String),
+ #[error("the password is incorrect")]
+ WrongPassword,
#[error("{0}")]
Form(#[from] pdfcraft_forms::FormError),
#[error(transparent)]
@@ -2789,6 +2797,39 @@ impl Session {
Self::refresh(doc)
}
+ /// Enter the permissions (owner) password of a document opened with its user password,
+ /// lifting its restrictions for this session (Acrobat asks for it before changing security).
+ /// Not an edit: nothing is marked unsaved and there is no undo step. Undo and redo states
+ /// are unlocked as well, and saving keeps the rights. Unencrypted documents and documents
+ /// opened by the owner need nothing.
+ pub fn unlock(&mut self, id: DocId, password: &str) -> Result<(), EditError> {
+ let doc = self.doc_mut(id)?;
+ let editor = doc.editor.as_mut().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?;
+ if editor.cos.permissions().is_none_or(|p| p.owner) {
+ return Ok(());
+ }
+ editor.cos.unlock(password).map_err(|e| match e {
+ pdfcraft_cos::CosError::WrongPassword => EditError::WrongPassword,
+ other => EditError::Protection(other.to_string()),
+ })?;
+ // Saving a state that keeps the security it was opened with reopens it with the same
+ // passwords, so it reopens as owner.
+ let reopen_as_owner = |cos: &pdfcraft_cos::Document, keys: &mut Keys| {
+ if !cos.encryption_changed() {
+ keys.reopen = Some(password.to_owned());
+ }
+ };
+ reopen_as_owner(&editor.cos, &mut editor.keys);
+ // Other states with the same restricted access are unlocked too; states opened with
+ // other passwords (protection changed and saved since) stay as they are.
+ for (_, cos, keys, _) in editor.undo.iter_mut().chain(editor.redo.iter_mut()) {
+ if cos.permissions().is_some_and(|p| !p.owner) && cos.unlock(password).is_ok() {
+ reopen_as_owner(cos, keys);
+ }
+ }
+ Ok(())
+ }
+
/// File ▸ Revert: back to the last saved version (or the file as opened). Undo history is
/// cleared, as in Acrobat.
pub fn revert(&mut self, id: DocId) -> Result<(), EditError> {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index a74845dac..7ae4592ca 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -707,6 +707,52 @@ fn copy_restricted_documents_refuse_extraction_unless_opened_by_the_owner() {
assert!(s.get(plain).unwrap().check_copying().is_ok() && extracting.iter().all(|c| enabled(&s, plain, c)));
}
+#[test]
+fn the_permissions_password_unlocks_an_open_document() {
+ // Only a permissions password (#995, #1077): opens without asking. Changes are allowed,
+ // security changes aren't.
+ let bytes = protected("", "owner", 0b1100);
+ let mut s = Session::new();
+ let id = s.open("r.pdf", None, bytes, None).unwrap();
+ s.apply(id, Edit::SetInfo { key: "Title".into(), value: "Before".into() }).unwrap();
+ assert!(!s.get(id).unwrap().allows_security_change());
+ assert!(matches!(s.apply(id, Edit::RemoveProtection), Err(EditError::NotPermitted(_))));
+ for wrong in ["", "nope"] {
+ assert_eq!(s.unlock(id, wrong), Err(EditError::WrongPassword), "{wrong:?}");
+ }
+ assert!(!s.get(id).unwrap().allows_security_change());
+ s.unlock(id, "owner").unwrap();
+ let d = s.get(id).unwrap();
+ assert!(d.allows_security_change() && d.security_summary().unwrap().owner);
+ assert!(d.dirty, "unlocking leaves the unsaved edit alone");
+ assert_eq!(d.can_undo(), Some("Change Title"), "and adds no undo step");
+ // Undo and redo don't bring the restrictions back.
+ s.undo(id).unwrap();
+ assert!(s.get(id).unwrap().allows_security_change(), "after undo");
+ s.redo(id).unwrap();
+ assert!(s.get(id).unwrap().allows_security_change(), "after redo");
+ // Neither does saving.
+ let saved = s.save_bytes(id).unwrap();
+ s.mark_saved(id, saved, None).unwrap();
+ assert!(s.get(id).unwrap().allows_security_change(), "after saving");
+ s.apply(id, Edit::RemoveProtection).unwrap();
+ let plain = s.save_bytes(id).unwrap();
+ assert!(pdfcraft_cos::Document::open(plain).unwrap().security().is_none(), "security removed");
+}
+
+#[test]
+fn unlocking_needs_the_permissions_password_not_the_open_password() {
+ let mut s = Session::new();
+ let id = s.open("r.pdf", None, protected("open", "perms", 0b0100), Some("open")).unwrap();
+ assert_eq!(s.unlock(id, "open"), Err(EditError::WrongPassword));
+ s.unlock(id, "perms").unwrap();
+ assert!(s.get(id).unwrap().allows_security_change());
+ // Nothing to unlock: opened by the owner already, or not encrypted.
+ s.unlock(id, "anything").unwrap();
+ let plain = s.open("p.pdf", None, Arc::new(fixture(1)), None).unwrap();
+ s.unlock(plain, "anything").unwrap();
+}
+
#[test]
fn combining_protected_files_is_refused_clearly() {
let s = Session::new();
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 29c22e563..c99f3d60a 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1957,6 +1957,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {
Some(Notice::Reload) => {}
Some(Notice::Repairs) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Advanced)),
Some(Notice::Security) => app.dialog = Some(crate::Dialog::Properties(crate::PropsTab::Security)),
+ Some(Notice::Unlock) => app.unlock_prompt = Some(crate::UnlockPrompt::new(doc, None)),
Some(Notice::Signatures) => app.right = Some(RightPanel::Signatures),
Some(Notice::FieldHighlights(on)) => app.view_defaults.highlight_fields = on,
None => {}
@@ -3275,6 +3276,8 @@ enum Notice {
Repairs,
/// Highlight fields was turned on or off.
FieldHighlights(bool),
+ /// Unlock… (enter the permissions password).
+ Unlock,
}
/// The notice bar above the pages: the signature status first (Acrobat's signature bar), then
@@ -3324,6 +3327,7 @@ fn notices(
return None;
}
let mut open_security = false;
+ let mut unlock = false;
let mut open_repairs = false;
let mut toggled = None;
let msg = if secured {
@@ -3381,6 +3385,9 @@ fn notices(
if secured && crate::widgets::pill_button(ui, tl!("Security settings"), false).clicked() {
open_security = true;
}
+ if secured && doc.can_unlock() && crate::widgets::pill_button(ui, tl!("Unlock…"), true).clicked() {
+ unlock = true;
+ }
if repaired && !secured && info.fields.is_empty() && crate::widgets::pill_button(ui, tl!("Details"), false).clicked() {
open_repairs = true;
}
@@ -3388,6 +3395,9 @@ fn notices(
if open_repairs {
return Some(Notice::Repairs);
}
+ if unlock {
+ return Some(Notice::Unlock);
+ }
open_security.then_some(Notice::Security).or(toggled)
}
diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs
index 32113ace9..4ccca99e6 100644
--- a/crates/ui-egui/src/commands.rs
+++ b/crates/ui-egui/src/commands.rs
@@ -123,13 +123,15 @@ impl PdfCraftApp {
};
crate::i18n::fmt(tl!("This document has no {kind} to change"), &[("kind", kind)])
}
+ // Restricted documents ask for their permissions password instead, so only an
+ // unprotected or a read-only document gets here.
commands::Needs::Security | commands::Needs::ProtectedSecurity if self.active.is_some() => {
- if self.active_ids().and_then(|(_, id)| self.session.get(id)).is_some_and(|d| d.allows_security_change()) {
- tl!("This document isn't password-protected").to_string()
- } else {
- tl!("Only the document's owner can change its security (open it with the permissions password)").to_string()
+ match self.active_ids().and_then(|(_, id)| self.session.get(id)) {
+ Some(d) if !d.allows_security_change() => crate::i18n::fmt(tl!("{name} is read-only"), &[("name", &d.name)]),
+ _ => tl!("This document isn't password-protected").to_string(),
}
}
+ commands::Needs::Unlock if self.active.is_some() => tl!("This document has no restrictions to lift").to_string(),
commands::Needs::Assembly | commands::Needs::Modification | commands::Needs::Annotate if self.active.is_some() => {
tl!("The document's security settings don't allow this change").to_string()
}
@@ -173,6 +175,12 @@ impl PdfCraftApp {
"file.revert" => self.dialog = Some(Dialog::Revert),
"file.properties" => self.dialog = Some(Dialog::Properties(PropsTab::Description)),
"protect.properties" => self.dialog = Some(Dialog::Properties(PropsTab::Security)),
+ // A restricted document's security changes once its permissions password is entered.
+ "protect.password" | "protect.remove" if self.active_ids().and_then(|(_, id)| self.session.get(id)).is_some_and(|d| d.can_unlock()) => {
+ let then = if id == "protect.password" { "protect.password" } else { "protect.remove" };
+ self.request_unlock(Some(then));
+ }
+ "protect.unlock" => self.request_unlock(None),
"protect.password" => {
self.protect_draft = Default::default();
self.dialog = Some(Dialog::Protect);
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 1da3a2157..6baa62c1c 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -10,6 +10,12 @@ use crate::{CloseRequest, Dialog, PdfCraftApp, PropsTab, panels::human_size, wid
const INFO_KEYS: [&str; 4] = ["Title", "Author", "Subject", "Keywords"];
pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {
+ dialogs(app, ctx);
+ // Last, so it sits above Document Properties when Security's Unlock… asked for it.
+ unlock(app, ctx);
+}
+
+fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
password(app, ctx);
save_prompt(app, ctx);
link_prompt(app, ctx);
@@ -271,8 +277,12 @@ pub fn show(app: &mut PdfCraftApp, ctx: &egui::Context) {
tl!("User password").to_string()
},
);
- if doc.allows_security_change() {
+ // A restricted document asks for its permissions password first.
+ if doc.allows_security_change() || doc.can_unlock() {
ui.horizontal(|ui| {
+ if doc.can_unlock() && ui.button(tl!("Unlock…")).clicked() {
+ link_command = Some("protect.unlock");
+ }
if ui.button(tl!("Change settings…")).clicked() {
link_command = Some("protect.password");
}
@@ -1518,47 +1528,83 @@ fn yes(b: bool) -> String {
tl!(if b { "Yes" } else { "No" }).to_string()
}
-/// Password prompt for encrypted documents (Acrobat: "Password" dialog on open).
-fn password(app: &mut PdfCraftApp, ctx: &egui::Context) {
- let Some(prompt) = app.password_prompt.as_mut() else { return };
+/// What a password box was answered with.
+enum PasswordAnswer {
+ Submit,
+ Cancel,
+}
+
+/// A password box: a lock, a title, a message, the masked field, an error and two buttons.
+fn password_modal(
+ ctx: &egui::Context,
+ id: &str,
+ title: &str,
+ message: String,
+ input: &mut String,
+ error: Option<&str>,
+ ok: &str,
+) -> Option<PasswordAnswer> {
let t = Tokens::get(ctx);
- let mut submit = false;
- let mut cancel = false;
- let modal = egui::Modal::new(egui::Id::new("password")).show(ctx, |ui| {
+ let mut answer = None;
+ let modal = egui::Modal::new(egui::Id::new(id)).show(ctx, |ui| {
ui.set_width(400.0);
ui.horizontal(|ui| {
ui.add(crate::icons::image("lock", 22.0, t.accent));
- ui.label(egui::RichText::new(tl!("Password required")).font(theme::semibold(17.0)));
+ ui.label(egui::RichText::new(title).font(theme::semibold(17.0)));
});
ui.add_space(6.0);
- ui.add(egui::Label::new(crate::i18n::fmt(tl!("“{name}” is protected. Enter a password to open it."), &[("name", &prompt.name)])).wrap());
+ ui.add(egui::Label::new(message).wrap());
ui.add_space(8.0);
- let r = ui.add(egui::TextEdit::singleline(&mut prompt.input).password(true).hint_text(tl!("Password")).desired_width(f32::INFINITY));
+ let r = ui.add(egui::TextEdit::singleline(input).password(true).hint_text(tl!("Password")).desired_width(f32::INFINITY));
// Enter submits. The field keeps focus (we request it every frame), so check the key
// while it is focused as well as on the frame focus is lost.
if (r.has_focus() || r.lost_focus()) && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
- submit = true;
+ answer = Some(PasswordAnswer::Submit);
}
r.request_focus();
- if let Some(e) = &prompt.error {
+ if let Some(e) = error {
ui.add_space(4.0);
// Known error text is translated; anything else passes through.
ui.label(egui::RichText::new(tl!(e)).color(egui::Color32::from_rgb(0xD1, 0x3B, 0x3B)));
}
ui.add_space(12.0);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
- if widgets::pill_button(ui, tl!("Open"), true).clicked() {
- submit = true;
+ if widgets::pill_button(ui, ok, true).clicked() {
+ answer = Some(PasswordAnswer::Submit);
}
if widgets::pill_button(ui, tl!("Cancel"), false).clicked() {
- cancel = true;
+ answer = Some(PasswordAnswer::Cancel);
}
});
});
- if submit {
- let pw = prompt.input.clone();
- app.submit_password(Some(pw));
- } else if cancel || modal.should_close() {
- app.submit_password(None);
+ answer.or(modal.should_close().then_some(PasswordAnswer::Cancel))
+}
+
+/// Password prompt for encrypted documents (Acrobat: "Password" dialog on open).
+fn password(app: &mut PdfCraftApp, ctx: &egui::Context) {
+ let Some(prompt) = app.password_prompt.as_mut() else { return };
+ let message = crate::i18n::fmt(tl!("“{name}” is protected. Enter a password to open it."), &[("name", &prompt.name)]);
+ match password_modal(ctx, "password", tl!("Password required"), message, &mut prompt.input, prompt.error.as_deref(), tl!("Open")) {
+ Some(PasswordAnswer::Submit) => {
+ let pw = prompt.input.clone();
+ app.submit_password(Some(pw));
+ }
+ Some(PasswordAnswer::Cancel) => app.submit_password(None),
+ None => {}
+ }
+}
+
+/// Permissions password prompt: lifts the restrictions of an open document (#995).
+fn unlock(app: &mut PdfCraftApp, ctx: &egui::Context) {
+ let Some(prompt) = app.unlock_prompt.as_mut() else { return };
+ let message =
+ crate::i18n::fmt(tl!("“{name}” has security restrictions. Enter its permissions password to lift them."), &[("name", &prompt.name)]);
+ match password_modal(ctx, "unlock", tl!("Permissions password"), message, &mut prompt.input, prompt.error.as_deref(), tl!("Unlock")) {
+ Some(PasswordAnswer::Submit) => {
+ let pw = prompt.input.clone();
+ app.submit_unlock(Some(pw));
+ }
+ Some(PasswordAnswer::Cancel) => app.submit_unlock(None),
+ None => {}
}
}
diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv
index 0d731aa28..b8a789b19 100644
--- a/crates/ui-egui/src/i18n/ar.tsv
+++ b/crates/ui-egui/src/i18n/ar.tsv
@@ -1713,7 +1713,12 @@
watermark علامة مائية
background خلفية
This document isn't password-protected هذا المستند غير محمي بكلمة مرور
- Only the document's owner can change its security (open it with the permissions password) مالك المستند وحده يستطيع تغيير أمانه (افتحه بكلمة مرور الأذونات)
+ Enter permissions password… أدخل كلمة مرور الأذونات…
+ Permissions password كلمة مرور الأذونات
+ “{name}” has security restrictions. Enter its permissions password to lift them. «{name}» عليه قيود أمان. أدخل كلمة مرور الأذونات الخاصة به لرفعها.
+ Restrictions lifted رُفعت القيود
+ Couldn't unlock {name}: {e} تعذّر إلغاء قفل {name}: {e}
+ This document has no restrictions to lift لا توجد في هذا المستند قيود لرفعها
The document's security settings don't allow this change إعدادات أمان المستند لا تسمح بهذا التغيير
The document's security settings don't allow copying text and images إعدادات أمان المستند لا تسمح بنسخ النصوص والصور
Open a document first افتح مستندًا أولًا
diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv
index 170c53119..03d1dc4ec 100644
--- a/crates/ui-egui/src/i18n/bg.tsv
+++ b/crates/ui-egui/src/i18n/bg.tsv
@@ -1676,7 +1676,12 @@
watermark воден знак
background фон
This document isn't password-protected Този документ не е защитен с парола
- Only the document's owner can change its security (open it with the permissions password) Само собственикът на документа може да промени защитата му (отворете го с паролата за разрешения)
+ Enter permissions password… Въведете паролата за разрешения…
+ Permissions password Парола за разрешения
+ “{name}” has security restrictions. Enter its permissions password to lift them. „{name}“ има ограничения за защита. Въведете паролата за разрешения, за да ги премахнете.
+ Restrictions lifted Ограниченията са премахнати
+ Couldn't unlock {name}: {e} {name} не може да се отключи: {e}
+ This document has no restrictions to lift Този документ няма ограничения за премахване
The document's security settings don't allow this change Настройките за защита на документа не позволяват тази промяна
The document's security settings don't allow copying text and images Настройките за защита на документа не позволяват копиране на текст и изображения
Open a document first Първо отворете документ
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 9c0156a13..60a2ce613 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -1648,7 +1648,12 @@
watermark Wasserzeichen
background Hintergrund
This document isn't password-protected Dieses Dokument ist nicht passwortgeschützt
- Only the document's owner can change its security (open it with the permissions password) Nur der Eigentümer des Dokuments kann die Sicherheit ändern (öffne es mit dem Berechtigungspasswort)
+ Enter permissions password… Berechtigungspasswort eingeben…
+ Permissions password Berechtigungspasswort
+ “{name}” has security restrictions. Enter its permissions password to lift them. „{name}“ hat Sicherheitseinschränkungen. Gib das Berechtigungspasswort ein, um sie aufzuheben.
+ Restrictions lifted Einschränkungen aufgehoben
+ Couldn't unlock {name}: {e} {name} konnte nicht entsperrt werden: {e}
+ This document has no restrictions to lift Dieses Dokument hat keine Einschränkungen, die aufgehoben werden können
The document's security settings don't allow this change Die Sicherheitseinstellungen des Dokuments erlauben diese Änderung nicht
The document's security settings don't allow copying text and images Die Sicherheitseinstellungen des Dokuments erlauben kein Kopieren von Text und Bildern
Open a document first Öffne zuerst ein Dokument
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 2b387f584..02d96bb66 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -1717,7 +1717,12 @@
watermark marca de agua
background fondo
This document isn't password-protected Este documento no está protegido con contraseña
- Only the document's owner can change its security (open it with the permissions password) Solo el propietario del documento puede cambiar su seguridad (ábrelo con la contraseña de permisos)
+ Enter permissions password… Introducir contraseña de permisos…
+ Permissions password Contraseña de permisos
+ “{name}” has security restrictions. Enter its permissions password to lift them. «{name}» tiene restricciones de seguridad. Introduce su contraseña de permisos para quitarlas.
+ Restrictions lifted Restricciones quitadas
+ Couldn't unlock {name}: {e} No se pudo desbloquear {name}: {e}
+ This document has no restrictions to lift Este documento no tiene restricciones que quitar
The document's security settings don't allow this change La configuración de seguridad del documento no permite este cambio
The document's security settings don't allow copying text and images La configuración de seguridad del documento no permite copiar texto ni imágenes
Open a document first Abre primero un documento
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index d77e7a2f8..70ca6a140 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -1643,7 +1643,12 @@
watermark filigrane
background arrière-plan
This document isn't password-protected Ce document n'est pas protégé par mot de passe
- Only the document's owner can change its security (open it with the permissions password) Seul le propriétaire du document peut modifier sa protection (ouvrez-le avec le mot de passe d'autorisations)
+ Enter permissions password… Saisir le mot de passe d'autorisations…
+ Permissions password Mot de passe d'autorisations
+ “{name}” has security restrictions. Enter its permissions password to lift them. «{name}» comporte des restrictions de sécurité. Saisissez son mot de passe d'autorisations pour les lever.
+ Restrictions lifted Restrictions levées
+ Couldn't unlock {name}: {e} Impossible de déverrouiller {name} : {e}
+ This document has no restrictions to lift Ce document n'a aucune restriction à lever
The document's security settings don't allow this change Les paramètres de protection du document n'autorisent pas cette modification
The document's security settings don't allow copying text and images Les paramètres de protection du document n'autorisent pas la copie de texte et d'images
Open a document first Ouvrez d'abord un document
diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv
index fb9398dce..845bfdf9f 100644
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@ -1633,7 +1633,12 @@
watermark vízjel
background háttér
This document isn't password-protected Ez a dokumentum nincs jelszóval védve
- Only the document's owner can change its security (open it with the permissions password) Csak a dokumentum tulajdonosa módosíthatja a biztonságát (nyisd meg a jogosultsági jelszóval)
+ Enter permissions password… Jogosultsági jelszó megadása…
+ Permissions password Jogosultsági jelszó
+ “{name}” has security restrictions. Enter its permissions password to lift them. „{name}” biztonsági korlátozásokat tartalmaz. Add meg a jogosultsági jelszavát a feloldásukhoz.
+ Restrictions lifted Korlátozások feloldva
+ Couldn't unlock {name}: {e} {name} feloldása nem sikerült: {e}
+ This document has no restrictions to lift Ebben a dokumentumban nincs feloldható korlátozás
The document's security settings don't allow this change A dokumentum biztonsági beállításai nem engedik ezt a módosítást
The document's security settings don't allow copying text and images A dokumentum biztonsági beállításai nem engedik a szöveg és a képek másolását
Open a document first Előbb nyiss meg egy dokumentumot
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index dfe54c34a..c62af0f3c 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -1718,7 +1718,12 @@
watermark filigrana
background sfondo
This document isn't password-protected Questo documento non è protetto da password
- Only the document's owner can change its security (open it with the permissions password) Solo il proprietario del documento può modificarne la protezione (aprilo con la password delle autorizzazioni)
+ Enter permissions password… Inserisci password delle autorizzazioni…
+ Permissions password Password delle autorizzazioni
+ “{name}” has security restrictions. Enter its permissions password to lift them. “{name}” ha restrizioni di sicurezza. Inserisci la password delle autorizzazioni per rimuoverle.
+ Restrictions lifted Restrizioni rimosse
+ Couldn't unlock {name}: {e} Impossibile sbloccare {name}: {e}
+ This document has no restrictions to lift Questo documento non ha restrizioni da rimuovere
The document's security settings don't allow this change Le impostazioni di sicurezza del documento non consentono questa modifica
The document's security settings don't allow copying text and images Le impostazioni di sicurezza del documento non consentono di copiare testo e immagini
Open a document first Apri prima un documento
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index e65c4615c..e2b5fcdba 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -1724,7 +1724,12 @@
watermark 透かし
background 背景
This document isn't password-protected この文書はパスワード保護されていません
- Only the document's owner can change its security (open it with the permissions password) 文書の所有者のみセキュリティを変更できます(権限パスワードで開いてください)
+ Enter permissions password… 権限パスワードを入力…
+ Permissions password 権限パスワード
+ “{name}” has security restrictions. Enter its permissions password to lift them. 「{name}」にはセキュリティの制限があります。制限を解除するには権限パスワードを入力してください。
+ Restrictions lifted 制限を解除しました
+ Couldn't unlock {name}: {e} {name} のロックを解除できませんでした: {e}
+ This document has no restrictions to lift この文書には解除する制限がありません
The document's security settings don't allow this change 文書のセキュリティ設定により、この変更は許可されていません
The document's security settings don't allow copying text and images 文書のセキュリティ設定により、テキストと画像のコピーは許可されていません
Open a document first 先に文書を開いてください
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 542ef9175..093f931d9 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -1709,7 +1709,12 @@
watermark znak wodny
background tło
This document isn't password-protected Ten dokument nie jest chroniony hasłem
- Only the document's owner can change its security (open it with the permissions password) Tylko właściciel dokumentu może zmienić zabezpieczenia (otwórz go przy użyciu hasła uprawnień)
+ Enter permissions password… Wpisz hasło uprawnień…
+ Permissions password Hasło uprawnień
+ “{name}” has security restrictions. Enter its permissions password to lift them. Plik „{name}” ma ograniczenia zabezpieczeń. Wpisz jego hasło uprawnień, aby je znieść.
+ Restrictions lifted Ograniczenia zniesione
+ Couldn't unlock {name}: {e} Nie udało się odblokować pliku {name}: {e}
+ This document has no restrictions to lift Ten dokument nie ma ograniczeń do zniesienia
The document's security settings don't allow this change Ustawienia zabezpieczeń dokumentu nie zezwalają na tę zmianę
Open a document first Najpierw otwórz dokument
Security will be removed when you save Zabezpieczenia zostaną usunięte przy zapisie
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index c8e78428b..bedd0cf4c 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -1546,7 +1546,12 @@
watermark marca-d'água
background plano de fundo
This document isn't password-protected Este documento não está protegido por senha
- Only the document's owner can change its security (open it with the permissions password) Somente o proprietário do documento pode alterar sua segurança (abra-o com a senha de permissões)
+ Enter permissions password… Digitar senha de permissões…
+ Permissions password Senha de permissões
+ “{name}” has security restrictions. Enter its permissions password to lift them. “{name}” tem restrições de segurança. Digite a senha de permissões para removê-las.
+ Restrictions lifted Restrições removidas
+ Couldn't unlock {name}: {e} Não foi possível desbloquear {name}: {e}
+ This document has no restrictions to lift Este documento não tem restrições a remover
The document's security settings don't allow this change As configurações de segurança do documento não permitem esta alteração
The document's security settings don't allow copying text and images As configurações de segurança do documento não permitem copiar texto e imagens
Open a document first Abra um documento primeiro
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index ac5566eaa..eedd8c972 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -1714,7 +1714,12 @@
watermark водяной знак
background фон
This document isn't password-protected Этот документ не защищён паролем
- Only the document's owner can change its security (open it with the permissions password) Только владелец документа может изменить его безопасность (откройте его с паролем разрешений)
+ Enter permissions password… Ввести пароль разрешений…
+ Permissions password Пароль разрешений
+ “{name}” has security restrictions. Enter its permissions password to lift them. У «{name}» есть ограничения безопасности. Введите пароль разрешений, чтобы снять их.
+ Restrictions lifted Ограничения сняты
+ Couldn't unlock {name}: {e} Не удалось разблокировать «{name}»: {e}
+ This document has no restrictions to lift У этого документа нет ограничений, которые можно снять
The document's security settings don't allow this change Настройки безопасности документа не разрешают это изменение
The document's security settings don't allow copying text and images Настройки безопасности документа не разрешают копировать текст и изображения
Open a document first Сначала откройте документ
diff --git a/crates/ui-egui/src/i18n/te.tsv b/crates/ui-egui/src/i18n/te.tsv
index e15fb7f32..0392e9124 100644
--- a/crates/ui-egui/src/i18n/te.tsv
+++ b/crates/ui-egui/src/i18n/te.tsv
@@ -1636,7 +1636,12 @@ action wizard Start ప్రారంభించు
watermark వాటర్‌మార్క్
background నేపథ్యం
This document isn't password-protected ఈ పత్రం పాస్‌వర్డ్‌తో రక్షించబడలేదు
- Only the document's owner can change its security (open it with the permissions password) పత్రం యజమాని మాత్రమే దాని భద్రతను మార్చగలరు (అనుమతుల పాస్‌వర్డ్‌తో దాన్ని తెరవండి)
+ Enter permissions password… అనుమతుల పాస్‌వర్డ్‌ను నమోదు చేయి…
+ Permissions password అనుమతుల పాస్‌వర్డ్
+ “{name}” has security restrictions. Enter its permissions password to lift them. “{name}”కు భద్రతా పరిమితులు ఉన్నాయి. వాటిని తొలగించడానికి దాని అనుమతుల పాస్‌వర్డ్‌ను నమోదు చేయండి.
+ Restrictions lifted పరిమితులు తొలగించబడ్డాయి
+ Couldn't unlock {name}: {e} {name}ను అన్‌లాక్ చేయలేకపోయాము: {e}
+ This document has no restrictions to lift ఈ పత్రంలో తొలగించాల్సిన పరిమితులు లేవు
The document's security settings don't allow this change పత్రం భద్రతా సెట్టింగ్‌లు ఈ మార్పును అనుమతించవు
The document's security settings don't allow copying text and images పత్రం భద్రతా సెట్టింగ్‌లు టెక్స్ట్, చిత్రాలను కాపీ చేయడాన్ని అనుమతించవు
Open a document first ముందుగా ఒక పత్రాన్ని తెరవండి
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index a641d81a7..0f61932f6 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -1711,7 +1711,12 @@
watermark водяний знак
background тло
This document isn't password-protected Цей документ не захищено паролем
- Only the document's owner can change its security (open it with the permissions password) Лише власник документа може змінювати захист (відкрийте з паролем дозволів)
+ Enter permissions password… Ввести пароль дозволів…
+ Permissions password Пароль дозволів
+ “{name}” has security restrictions. Enter its permissions password to lift them. «{name}» має обмеження захисту. Введіть пароль дозволів, щоб зняти їх.
+ Restrictions lifted Обмеження знято
+ Couldn't unlock {name}: {e} Не вдалося розблокувати {name}: {e}
+ This document has no restrictions to lift Цей документ не має обмежень, які можна зняти
The document's security settings don't allow this change Налаштування захисту документа не дозволяють цю зміну
The document's security settings don't allow copying text and images Налаштування захисту документа не дозволяють копіювати текст і зображення
Open a document first Спочатку відкрийте документ
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 7c053e64e..f3a713228 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -1683,7 +1683,12 @@
watermark 水印
background 背景
This document isn't password-protected 本文档未受密码保护
- Only the document's owner can change its security (open it with the permissions password) 只有文档所有者才能更改安全性(请使用权限密码打开)
+ Enter permissions password… 输入权限密码…
+ Permissions password 权限密码
+ “{name}” has security restrictions. Enter its permissions password to lift them. “{name}”有安全限制。请输入其权限密码以解除限制。
+ Restrictions lifted 已解除限制
+ Couldn't unlock {name}: {e} 无法解锁 {name}:{e}
+ This document has no restrictions to lift 此文档没有可解除的限制
The document's security settings don't allow this change 文档安全设置不允许此更改
The document's security settings don't allow copying text and images 文档安全设置不允许复制文本和图像
Open a document first 请先打开文档
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index d1e8f3b5e..d0645dcf9 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -1630,7 +1630,12 @@
watermark 水印
background 背景
This document isn't password-protected 本文件未受密碼保護
- Only the document's owner can change its security (open it with the permissions password) 只有文件所有者才能更改安全性(請使用許可權密碼開啟)
+ Enter permissions password… 輸入許可權密碼…
+ Permissions password 許可權密碼
+ “{name}” has security restrictions. Enter its permissions password to lift them. “{name}”有安全限制。請輸入其許可權密碼以解除限制。
+ Restrictions lifted 已解除限制
+ Couldn't unlock {name}: {e} 無法解鎖 {name}:{e}
+ This document has no restrictions to lift 此文件沒有可解除的限制
The document's security settings don't allow this change 文件安全設定不允許此更改
The document's security settings don't allow copying text and images 文件安全設定不允許複製文字和圖片
Open a document first 請先開啟文件
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 3ec5dac3e..31ff1c184 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -393,6 +393,23 @@ pub struct PasswordPrompt {
then: Option<&'static str>,
}
+/// Asks for the permissions password of an open document whose security restricts it, which
+/// lifts the restrictions (#995). Acrobat asks for it when such a document's security is changed.
+pub struct UnlockPrompt {
+ pub doc: DocId,
+ pub name: String,
+ pub input: String,
+ pub error: Option<String>,
+ /// The command to run once unlocked (Protect using password, Remove security), if any.
+ pub then: Option<&'static str>,
+}
+
+impl UnlockPrompt {
+ pub(crate) fn new(doc: &pdfcraft_engine::Document, then: Option<&'static str>) -> Self {
+ Self { doc: doc.id, name: doc.name.clone(), input: String::new(), error: None, then }
+ }
+}
+
#[derive(serde::Serialize, serde::Deserialize)]
pub struct RecentFile {
pub name: String,
@@ -487,6 +504,7 @@ pub struct PdfCraftApp {
/// Whether the macOS title bar is drawn by us (traffic lights over our tab strip).
pub integrated_titlebar: bool,
pub password_prompt: Option<PasswordPrompt>,
+ pub unlock_prompt: Option<UnlockPrompt>,
pub full_screen: bool,
/// Files delivered asynchronously (web drag-and-drop, web file picker).
pub inbox: Inbox,
@@ -791,6 +809,7 @@ impl PdfCraftApp {
toast: None,
integrated_titlebar: false,
password_prompt: None,
+ unlock_prompt: None,
full_screen: false,
inbox: Default::default(),
startup_inbox: Default::default(),
@@ -1207,6 +1226,33 @@ impl PdfCraftApp {
}
}
+ /// Ask for the active document's permissions password, then run `then` (if any).
+ pub(crate) fn request_unlock(&mut self, then: Option<&'static str>) {
+ let Some(doc) = self.active_ids().and_then(|(_, id)| self.session.get(id)) else { return };
+ self.unlock_prompt = Some(UnlockPrompt::new(doc, then));
+ }
+
+ /// Answer the permissions password prompt (`None` cancels).
+ pub fn submit_unlock(&mut self, password: Option<String>) {
+ let Some(mut p) = self.unlock_prompt.take() else { return };
+ let Some(pw) = password else { return };
+ match self.session.unlock(p.doc, &pw) {
+ // Carry on with what asked for the password, if its document is still the one shown.
+ Ok(()) => match p.then {
+ Some(command) if self.active_ids().is_some_and(|(_, id)| id == p.doc) => {
+ self.execute(command);
+ }
+ _ => self.notify_tr("Restrictions lifted"),
+ },
+ Err(pdfcraft_engine::EditError::WrongPassword) => {
+ p.input.clear();
+ p.error = Some("Incorrect password. Try again.".to_string());
+ self.unlock_prompt = Some(p);
+ }
+ Err(e) => self.notify_fmt("Couldn't unlock {name}: {e}", &[("name", &p.name), ("e", &e.to_string())]),
+ }
+ }
+
/// Open a file from a recent list: focus the tab already showing it, else open it (File ▸
/// Open Recent and the Home view's list share this).
pub fn open_recent(&mut self, path: &str) {
@@ -1299,7 +1345,12 @@ impl PdfCraftApp {
/// A dialog or prompt is open over the window: the keyboard is its own, and nothing may act
/// on the document underneath it.
pub(crate) fn modal_open(&self) -> bool {
- self.dialog.is_some() || self.close_request.is_some() || self.password_prompt.is_some() || self.pending_link.is_some() || self.updates.open
+ self.dialog.is_some()
+ || self.close_request.is_some()
+ || self.password_prompt.is_some()
+ || self.unlock_prompt.is_some()
+ || self.pending_link.is_some()
+ || self.updates.open
}
/// Enable the UI control channel on `ctx` (opt-in; see [`control`]). Returns a client that
diff --git a/crates/ui-egui/tests/commands.rs b/crates/ui-egui/tests/commands.rs
index 48a18eb42..5a9c443c8 100644
--- a/crates/ui-egui/tests/commands.rs
+++ b/crates/ui-egui/tests/commands.rs
@@ -75,6 +75,19 @@ fn every_registered_command_is_implemented() {
app.set_option("language", "en").unwrap();
if spec.id.starts_with("form.") || spec.id == "comment.flatten" {
app.open_bytes("form.pdf", None, include_bytes!("data/form.pdf").to_vec()).unwrap();
+ } else if spec.id == "protect.unlock" {
+ // Only a permissions password: opens restricted, and can be unlocked.
+ let mut doc = pdfcraft_cos::Document::open(std::sync::Arc::new(fixture(3))).unwrap();
+ doc.set_encryption(&pdfcraft_cos::NewEncryption {
+ algorithm: pdfcraft_cos::Algorithm::Aes256,
+ user_password: "",
+ owner_password: "owner",
+ permissions: 0b0100,
+ encrypt_metadata: true,
+ seed: [5; 32],
+ })
+ .unwrap();
+ app.open_bytes("restricted.pdf", None, pdfcraft_cos::write_full(&doc, &Default::default()).unwrap()).unwrap();
} else {
app.open_bytes("doc.pdf", None, fixture(3)).unwrap();
}
diff --git a/crates/ui-egui/tests/editing.rs b/crates/ui-egui/tests/editing.rs
index 17990d2fb..4acc49902 100644
--- a/crates/ui-egui/tests/editing.rs
+++ b/crates/ui-egui/tests/editing.rs
@@ -1716,6 +1716,61 @@ fn the_security_notice_wraps_beside_its_buttons_and_lines_up_with_them() {
}
}
+/// #995, #1077: a file with only a permissions password opens without asking, restricted. Its
+/// notice offers Unlock…, which takes the permissions password and lifts the restrictions.
+#[test]
+fn the_security_notice_unlocks_with_the_permissions_password() {
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("locked.pdf", None, protected("", "owner", 0b0100)).unwrap();
+ app
+ });
+ h.run_steps(4);
+ h.get_by_label_contains("This document is secured");
+ h.get_by_label("Unlock…").click();
+ h.run_steps(2);
+ h.get_by_label_contains("Enter its permissions password");
+ type_password(&mut h, "wrong");
+ h.get_by_label("Incorrect password. Try again.");
+ type_password(&mut h, "owner");
+ assert!(h.state().unlock_prompt.is_none());
+ assert!(h.query_by_label_contains("This document is secured").is_none(), "the restrictions are lifted");
+ h.state_mut().set_option("dialog", "properties").unwrap();
+ h.run_steps(2);
+ h.get_by_label("Security").click();
+ h.run_steps(3);
+ h.get_by_label("Owner password (no restrictions apply)");
+ assert!(!h.state().session.get(h.state().active_ids().unwrap().1).unwrap().dirty, "unlocking is not an edit");
+}
+
+/// Changing a restricted document's security asks for its permissions password first (Acrobat
+/// does too), then carries on.
+#[test]
+fn remove_security_asks_for_the_permissions_password_first() {
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("locked.pdf", None, protected("", "owner", 0b0100)).unwrap();
+ app
+ });
+ h.run_steps(4);
+ assert!(h.state_mut().execute("protect.remove"));
+ h.run_steps(2);
+ assert!(h.state().unlock_prompt.is_some(), "asks for the password");
+ // Cancelling changes nothing.
+ h.key_press(Key::Escape);
+ h.run_steps(2);
+ assert!(h.state().unlock_prompt.is_none());
+ let id = h.state().active_ids().unwrap().1;
+ assert!(!h.state().session.get(id).unwrap().dirty);
+ assert!(h.state_mut().execute("protect.remove"));
+ h.run_steps(2);
+ type_password(&mut h, "owner");
+ let doc = h.state().session.get(id).unwrap();
+ assert!(doc.dirty && doc.security_summary().is_none(), "security is removed (written by the next save)");
+}
+
#[test]
fn restricted_documents_show_a_notice_and_block_page_changes() {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 051878ce8..eaa7c713a 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -188,10 +188,10 @@ area = "A"
tier = "P0"
milestone = "M1"
status = "shipped"
-commands = []
+commands = ["protect.unlock"]
tools = ["doc_open"]
-evidence = ["crates/engine/src/tests.rs::restricted_documents_refuse_changes_unless_opened_by_the_owner", "crates/engine/src/tests.rs::owner_password_of_older_revisions_opens_the_viewer_too", "crates/crypt/src/tests.rs::owner_authentication_recovers_the_user_password"]
-notes = ""
+evidence = ["crates/engine/src/tests.rs::restricted_documents_refuse_changes_unless_opened_by_the_owner", "crates/engine/src/tests.rs::owner_password_of_older_revisions_opens_the_viewer_too", "crates/crypt/src/tests.rs::owner_authentication_recovers_the_user_password", "crates/engine/src/tests.rs::the_permissions_password_unlocks_an_open_document", "crates/ui-egui/tests/editing.rs::the_security_notice_unlocks_with_the_permissions_password", "crates/ui-egui/tests/editing.rs::remove_security_asks_for_the_permissions_password_first"]
+notes = "at open (the password prompt takes either password), or after opening a restricted file that needed no password (#995, #1077): Unlock… on the security notice and in Properties ▸ Security, and changing security asks for it first. Not yet: an automation tool to unlock an open document (reopen with doc_open and the password instead)"
[[feature]]
id = "core.permissions-enforced"