Skip to content

Commit ff15a89

Browse files
committed
feat: improve unlock in Vaultwarden backup
1 parent 02de74c commit ff15a89

1 file changed

Lines changed: 28 additions & 23 deletions

File tree

‎scripts/bw_backup.py‎

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -38,22 +38,22 @@ def sha256_file(path, chunk_size=1024 * 1024):
3838
def run(command, env=None, timeout=120):
3939
"""Run a command and return stdout."""
4040

41-
result = subprocess.run(
42-
command,
43-
env=env,
44-
text=True,
45-
capture_output=True,
46-
check=True,
47-
timeout=timeout,
48-
)
49-
50-
if result.returncode != 0:
41+
try:
42+
result = subprocess.run(
43+
command,
44+
env=env,
45+
text=True,
46+
capture_output=True,
47+
check=True,
48+
timeout=timeout,
49+
)
50+
except subprocess.CalledProcessError as exc:
5151
raise RuntimeError(
5252
f"Command failed:\n"
5353
f" {' '.join(map(str, command))}\n\n"
54-
f"stdout:\n{result.stdout}\n"
55-
f"stderr:\n{result.stderr}"
56-
)
54+
f"stdout:\n{exc.stdout}\n"
55+
f"stderr:\n{exc.stderr}"
56+
) from exc
5757

5858
return result.stdout.strip()
5959

@@ -313,16 +313,21 @@ def create_backup(bw, config):
313313

314314
print("🔓 Unlocking vault...")
315315

316-
session = run(
317-
[
318-
str(bw),
319-
"unlock",
320-
"--passwordenv",
321-
"BW_MASTER_PASSWORD",
322-
"--raw",
323-
],
324-
env=env,
325-
)
316+
unlock_command = [
317+
str(bw),
318+
"unlock",
319+
"--passwordenv",
320+
"BW_MASTER_PASSWORD",
321+
"--raw",
322+
]
323+
324+
try:
325+
session = run(unlock_command, env=env)
326+
except RuntimeError:
327+
print("🔐 Local login state is invalid, logging in again...")
328+
run([str(bw), "logout"], env=env)
329+
run([str(bw), "login", "--apikey"], env=env)
330+
session = run(unlock_command, env=env)
326331

327332
if not session:
328333
raise RuntimeError("bw unlock did not return a session.")

0 commit comments

Comments
 (0)