main
  1"""Tests for the Passage Raffi script filter and copy action."""
  2
  3from __future__ import annotations
  4
  5import base64
  6import json
  7import os
  8import subprocess
  9import tempfile
 10import unittest
 11from pathlib import Path
 12
 13SCRIPTS = Path(__file__).parents[1] / "scripts"
 14FILTER = SCRIPTS / "passage-raffi"
 15COPY = SCRIPTS / "passage-raffi-copy"
 16
 17
 18class PassageRaffiTests(unittest.TestCase):
 19    def make_store(self, directory: Path) -> Path:
 20        store = directory / "passage"
 21        (store / "web").mkdir(parents=True)
 22        (store / "web" / "github.age").touch()
 23        (store / "mail.age").touch()
 24        (store / ".git").mkdir()
 25        (store / ".git" / "ignored.age").touch()
 26        return store
 27
 28    def run_filter(self, store: Path, query: str = "") -> dict[str, object]:
 29        completed = subprocess.run(
 30            [str(FILTER), query],
 31            check=True,
 32            capture_output=True,
 33            text=True,
 34            env={**os.environ, "PASSAGE_DIR": str(store)},
 35        )
 36        return json.loads(completed.stdout)
 37
 38    def test_lists_age_entries_without_exposing_paths_in_action_values(self) -> None:
 39        with tempfile.TemporaryDirectory() as temporary_directory:
 40            result = self.run_filter(self.make_store(Path(temporary_directory)))
 41
 42        self.assertEqual(
 43            [item["title"] for item in result["items"]], ["mail", "web/github"]
 44        )
 45        self.assertEqual(
 46            [item["subtitle"] for item in result["items"]],
 47            ["Copy password from Passage", "Copy password from Passage"],
 48        )
 49        self.assertTrue(all(item["valid"] for item in result["items"]))
 50        self.assertTrue(all("/" not in item["arg"] for item in result["items"]))
 51
 52    def test_filters_entry_names(self) -> None:
 53        with tempfile.TemporaryDirectory() as temporary_directory:
 54            result = self.run_filter(self.make_store(Path(temporary_directory)), "git")
 55
 56        self.assertEqual([item["title"] for item in result["items"]], ["web/github"])
 57
 58    def test_defaults_to_the_xdg_data_passage_store(self) -> None:
 59        with tempfile.TemporaryDirectory() as temporary_directory:
 60            home = Path(temporary_directory)
 61            self.make_store(home / ".local" / "share")
 62            environment = {**os.environ, "HOME": str(home)}
 63            environment.pop("PASSAGE_DIR", None)
 64            environment.pop("XDG_DATA_HOME", None)
 65            completed = subprocess.run(
 66                [str(FILTER)],
 67                check=True,
 68                capture_output=True,
 69                text=True,
 70                env=environment,
 71            )
 72
 73        result = json.loads(completed.stdout)
 74        self.assertEqual(
 75            [item["title"] for item in result["items"]], ["mail", "web/github"]
 76        )
 77
 78    def test_copy_decodes_the_selected_entry_and_uses_passage_clipboard(self) -> None:
 79        with tempfile.TemporaryDirectory() as temporary_directory:
 80            temporary_path = Path(temporary_directory)
 81            store = self.make_store(temporary_path)
 82            bin_directory = temporary_path / "bin"
 83            bin_directory.mkdir()
 84            arguments = temporary_path / "passage-arguments"
 85            notification = temporary_path / "notification-arguments"
 86            passage = bin_directory / "passage"
 87            passage.write_text(
 88                f'#!/bin/sh\nprintf "%s\\n" "$@" > "{arguments}"\n', encoding="utf-8"
 89            )
 90            passage.chmod(0o755)
 91            notify_send = bin_directory / "notify-send"
 92            notify_send.write_text(
 93                f'#!/bin/sh\nprintf "%s\\n" "$@" > "{notification}"\n', encoding="utf-8"
 94            )
 95            notify_send.chmod(0o755)
 96            encoded = base64.urlsafe_b64encode(b"web/github").decode().rstrip("=")
 97
 98            subprocess.run(
 99                [str(COPY), encoded],
100                check=True,
101                env={
102                    **os.environ,
103                    "PASSAGE_DIR": str(store),
104                    "PATH": f"{bin_directory}:{os.environ['PATH']}",
105                },
106            )
107
108            self.assertEqual(
109                arguments.read_text(encoding="utf-8").splitlines(),
110                ["show", "--clip", "--", "web/github"],
111            )
112            self.assertEqual(
113                notification.read_text(encoding="utf-8").splitlines(),
114                ["Passage", "Password copied to clipboard"],
115            )
116
117    def test_copy_rejects_an_entry_outside_the_store(self) -> None:
118        with tempfile.TemporaryDirectory() as temporary_directory:
119            temporary_path = Path(temporary_directory)
120            store = self.make_store(temporary_path)
121            encoded = base64.urlsafe_b64encode(b"../outside").decode().rstrip("=")
122            completed = subprocess.run(
123                [str(COPY), encoded],
124                check=False,
125                capture_output=True,
126                text=True,
127                env={**os.environ, "PASSAGE_DIR": str(store)},
128            )
129
130        self.assertNotEqual(completed.returncode, 0)
131        self.assertIn("invalid Passage entry", completed.stderr)
132
133
134if __name__ == "__main__":
135    unittest.main()