kp-sync 0.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kp_sync/__init__.py +5 -0
- kp_sync/__main__.py +8 -0
- kp_sync/access_op.py +146 -0
- kp_sync/access_ops.py +480 -0
- kp_sync/backups.py +86 -0
- kp_sync/baseline.py +804 -0
- kp_sync/classify.py +103 -0
- kp_sync/cleanup.py +177 -0
- kp_sync/cli.py +1123 -0
- kp_sync/cloud_contact.py +175 -0
- kp_sync/completion.py +119 -0
- kp_sync/config.py +1105 -0
- kp_sync/content.py +62 -0
- kp_sync/credentials.py +349 -0
- kp_sync/daemon/__init__.py +3 -0
- kp_sync/daemon/apps.py +658 -0
- kp_sync/daemon/client.py +388 -0
- kp_sync/daemon/dbus.py +332 -0
- kp_sync/daemon/inhibit.py +137 -0
- kp_sync/daemon/leases.py +203 -0
- kp_sync/daemon/protocol.py +305 -0
- kp_sync/daemon/rescue.py +755 -0
- kp_sync/daemon/server.py +2116 -0
- kp_sync/daemon/systemd.py +251 -0
- kp_sync/daemon/triggers.py +204 -0
- kp_sync/drive_retire.py +288 -0
- kp_sync/drive_setup.py +344 -0
- kp_sync/drive_sync.py +107 -0
- kp_sync/drives.py +349 -0
- kp_sync/endpoints/__init__.py +27 -0
- kp_sync/endpoints/access.py +26 -0
- kp_sync/endpoints/base.py +307 -0
- kp_sync/endpoints/command.py +172 -0
- kp_sync/endpoints/file.py +524 -0
- kp_sync/endpoints/rclone.py +1060 -0
- kp_sync/endpoints/session.py +37 -0
- kp_sync/engine.py +4887 -0
- kp_sync/history.py +375 -0
- kp_sync/history_command.py +154 -0
- kp_sync/idle.py +100 -0
- kp_sync/integration.py +1646 -0
- kp_sync/kdbx.py +127 -0
- kp_sync/keepassxc.py +280 -0
- kp_sync/lock.py +76 -0
- kp_sync/log.py +189 -0
- kp_sync/merge.py +2042 -0
- kp_sync/paths.py +153 -0
- kp_sync/pending.py +158 -0
- kp_sync/rclone_credentials.py +263 -0
- kp_sync/rclone_rcd.py +553 -0
- kp_sync/reach.py +448 -0
- kp_sync/repair.py +185 -0
- kp_sync/services.py +645 -0
- kp_sync/sessions/__init__.py +3 -0
- kp_sync/sessions/authkeys.py +425 -0
- kp_sync/sessions/diagnostic.py +191 -0
- kp_sync/sessions/records.py +457 -0
- kp_sync/sessions/session.py +792 -0
- kp_sync/sessions/sftp_serve.py +270 -0
- kp_sync/state.py +685 -0
- kp_sync/udevmon.py +94 -0
- kp_sync/ui/__init__.py +10 -0
- kp_sync/ui/base.py +106 -0
- kp_sync/ui/factory.py +51 -0
- kp_sync/ui/fake.py +66 -0
- kp_sync/ui/gui.py +417 -0
- kp_sync/ui/none.py +32 -0
- kp_sync/ui/progress.py +111 -0
- kp_sync/ui/tty.py +139 -0
- kp_sync/verify.py +196 -0
- kp_sync-0.6.0.data/data/share/man/man1/kp-sync.1 +975 -0
- kp_sync-0.6.0.data/data/share/man/man5/kp-sync-config.5 +899 -0
- kp_sync-0.6.0.dist-info/METADATA +333 -0
- kp_sync-0.6.0.dist-info/RECORD +78 -0
- kp_sync-0.6.0.dist-info/WHEEL +5 -0
- kp_sync-0.6.0.dist-info/entry_points.txt +2 -0
- kp_sync-0.6.0.dist-info/licenses/LICENSE +674 -0
- kp_sync-0.6.0.dist-info/top_level.txt +1 -0
kp_sync/__init__.py
ADDED
kp_sync/__main__.py
ADDED
kp_sync/access_op.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
# Copyright (C) 2026 Juan Domingo Martín
|
|
3
|
+
"""Bridge kp-access file-operation requests to the kp-sync daemon."""
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TextIO
|
|
9
|
+
|
|
10
|
+
from kp_sync.access_ops import (
|
|
11
|
+
AccessOperationError,
|
|
12
|
+
access_paths,
|
|
13
|
+
create_upload,
|
|
14
|
+
discard_upload,
|
|
15
|
+
validate_operation,
|
|
16
|
+
)
|
|
17
|
+
from kp_sync.daemon.client import Client
|
|
18
|
+
from kp_sync.log import info
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def run_access_op(
|
|
22
|
+
config,
|
|
23
|
+
*,
|
|
24
|
+
environ=None,
|
|
25
|
+
stdin=None,
|
|
26
|
+
stdout=None,
|
|
27
|
+
client=None,
|
|
28
|
+
) -> int:
|
|
29
|
+
"""Validate one kp-access request, forward it, and stream GET data.
|
|
30
|
+
|
|
31
|
+
kp-access environment variables describe the request. PUT is staged
|
|
32
|
+
before the daemon request; GET goes to ``stdout`` after approval.
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
Zero after the requested operation completes.
|
|
36
|
+
|
|
37
|
+
Raises:
|
|
38
|
+
AccessOperationError: If the request or staging path is invalid,
|
|
39
|
+
or staged data cannot be read.
|
|
40
|
+
ClientError: If the daemon rejects or fails the request.
|
|
41
|
+
"""
|
|
42
|
+
env = os.environ if environ is None else environ
|
|
43
|
+
input_stream = sys.stdin.buffer if stdin is None else stdin
|
|
44
|
+
output_stream = sys.stdout.buffer if stdout is None else stdout
|
|
45
|
+
operation = env.get("OPERATION", "")
|
|
46
|
+
owner_database_path = env.get("DB_PATH", "")
|
|
47
|
+
run_directory = (
|
|
48
|
+
client.directory if client is not None else _run_directory(config)
|
|
49
|
+
)
|
|
50
|
+
staging, staged_database, configured_database_path = access_paths(
|
|
51
|
+
config,
|
|
52
|
+
run_directory,
|
|
53
|
+
)
|
|
54
|
+
if (
|
|
55
|
+
not owner_database_path
|
|
56
|
+
or not Path(owner_database_path).expanduser().is_absolute()
|
|
57
|
+
or Path(owner_database_path).expanduser() != staged_database
|
|
58
|
+
):
|
|
59
|
+
raise AccessOperationError(
|
|
60
|
+
"DB_PATH does not match the configured access staging database"
|
|
61
|
+
)
|
|
62
|
+
file_path = env.get("FILE_PATH", "")
|
|
63
|
+
destination = env.get("DESTINATION", "")
|
|
64
|
+
peer_address = env.get("PEER_ADDRESS", "")
|
|
65
|
+
identified_user = env.get("IDENTIFIED_USER", "")
|
|
66
|
+
|
|
67
|
+
upload_id = None
|
|
68
|
+
if operation in {"PUT", "DELETE", "MOVE"} and not identified_user:
|
|
69
|
+
raise AccessOperationError(
|
|
70
|
+
"file operation requires an authenticated user"
|
|
71
|
+
)
|
|
72
|
+
if operation in {"GET", "PUT", "DELETE", "MOVE"}:
|
|
73
|
+
validate_operation(
|
|
74
|
+
config, run_directory, operation, file_path, destination
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
fields: dict[str, str] = {
|
|
78
|
+
"operation": operation,
|
|
79
|
+
"db_path": configured_database_path,
|
|
80
|
+
}
|
|
81
|
+
if file_path:
|
|
82
|
+
fields["file_path"] = file_path
|
|
83
|
+
if destination:
|
|
84
|
+
fields["destination"] = destination
|
|
85
|
+
if peer_address:
|
|
86
|
+
fields["peer_address"] = peer_address
|
|
87
|
+
if identified_user:
|
|
88
|
+
fields["identified_user"] = identified_user
|
|
89
|
+
|
|
90
|
+
if operation == "PUT":
|
|
91
|
+
payload = input_stream.read()
|
|
92
|
+
if not isinstance(payload, bytes):
|
|
93
|
+
raise AccessOperationError("PUT input must be binary")
|
|
94
|
+
upload_id = create_upload(
|
|
95
|
+
config,
|
|
96
|
+
run_directory,
|
|
97
|
+
payload,
|
|
98
|
+
)
|
|
99
|
+
fields["upload_id"] = upload_id
|
|
100
|
+
try:
|
|
101
|
+
requester = client or Client(config)
|
|
102
|
+
requester.request(
|
|
103
|
+
"access-op",
|
|
104
|
+
wait=True,
|
|
105
|
+
ui=config.ui["mode"],
|
|
106
|
+
**fields,
|
|
107
|
+
)
|
|
108
|
+
except BaseException:
|
|
109
|
+
if upload_id is not None:
|
|
110
|
+
discard_upload(
|
|
111
|
+
config,
|
|
112
|
+
run_directory,
|
|
113
|
+
upload_id,
|
|
114
|
+
)
|
|
115
|
+
raise
|
|
116
|
+
|
|
117
|
+
if operation == "GET":
|
|
118
|
+
path, _ = validate_operation(
|
|
119
|
+
config,
|
|
120
|
+
run_directory,
|
|
121
|
+
"GET",
|
|
122
|
+
file_path,
|
|
123
|
+
)
|
|
124
|
+
assert path is not None
|
|
125
|
+
try:
|
|
126
|
+
with path.open("rb") as source:
|
|
127
|
+
while chunk := source.read(1024 * 1024):
|
|
128
|
+
output_stream.write(chunk)
|
|
129
|
+
except OSError as exc:
|
|
130
|
+
raise AccessOperationError(
|
|
131
|
+
f"cannot read staged database: {exc}"
|
|
132
|
+
) from exc
|
|
133
|
+
else:
|
|
134
|
+
info(f"kp-access {operation} completed")
|
|
135
|
+
return 0
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _run_directory(config):
|
|
139
|
+
from kp_sync.paths import ensure_run_dir
|
|
140
|
+
|
|
141
|
+
return ensure_run_dir(config.profile)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def main(config) -> int:
|
|
145
|
+
"""Run the access bridge using process environment and streams."""
|
|
146
|
+
return run_access_op(config)
|
kp_sync/access_ops.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
# Copyright (C) 2026 Juan Domingo Martín
|
|
3
|
+
"""Validate and apply kp-access operations on the staged database."""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import secrets
|
|
9
|
+
import shutil
|
|
10
|
+
import stat
|
|
11
|
+
from pathlib import Path, PurePosixPath
|
|
12
|
+
|
|
13
|
+
from kp_sync.backups import backup_file
|
|
14
|
+
from kp_sync.endpoints.base import EndpointFingerprint
|
|
15
|
+
from kp_sync.kdbx import KdbxError, inspect_kdbx
|
|
16
|
+
from kp_sync.lock import file_lock
|
|
17
|
+
from kp_sync.paths import atomic_write, ensure_private_directory
|
|
18
|
+
|
|
19
|
+
ACCESS_IDENTITY = "session:kp-access"
|
|
20
|
+
ACCESS_IDENTITY_PREFIX = "session:kp-access:"
|
|
21
|
+
ACCESS_LEASE = "access:kp-access"
|
|
22
|
+
ACCESS_TTL_SECONDS = 60
|
|
23
|
+
_UPLOAD_ID = re.compile(r"[0-9a-f]{32}\Z")
|
|
24
|
+
_OPERATIONS = {"GET", "PUT", "DELETE", "MOVE", "BEGIN", "END"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AccessOperationError(RuntimeError):
|
|
28
|
+
"""Raised when an access operation violates its staging contract."""
|
|
29
|
+
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def access_paths(
|
|
34
|
+
config, run_directory: str | os.PathLike[str]
|
|
35
|
+
) -> tuple[Path, Path, str]:
|
|
36
|
+
"""Resolve and secure runtime staging and database paths.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
config: Loaded kp-sync configuration with an ``[access]`` table.
|
|
40
|
+
run_directory: Private runtime directory for this profile.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
Staging directory, local database path, and virtual path.
|
|
44
|
+
|
|
45
|
+
Raises:
|
|
46
|
+
AccessOperationError: If paths are missing, unsafe, or outside
|
|
47
|
+
the profile runtime directory.
|
|
48
|
+
"""
|
|
49
|
+
run_dir = Path(run_directory).resolve()
|
|
50
|
+
database_path = config.access.get("db_path")
|
|
51
|
+
if not isinstance(database_path, str):
|
|
52
|
+
raise AccessOperationError("[access].db_path must be configured")
|
|
53
|
+
virtual = _virtual_path(database_path)
|
|
54
|
+
if len(virtual.parts) < 2:
|
|
55
|
+
raise AccessOperationError("[access].db_path must include a directory")
|
|
56
|
+
|
|
57
|
+
configured_staging = config.access.get("staging_dir")
|
|
58
|
+
staging = (
|
|
59
|
+
Path(configured_staging).expanduser()
|
|
60
|
+
if configured_staging
|
|
61
|
+
else Path("staging")
|
|
62
|
+
)
|
|
63
|
+
if not staging.is_absolute():
|
|
64
|
+
staging = run_dir / staging
|
|
65
|
+
try:
|
|
66
|
+
relative_staging = staging.relative_to(run_dir)
|
|
67
|
+
except ValueError as exc:
|
|
68
|
+
raise AccessOperationError(
|
|
69
|
+
"[access].staging_dir must stay inside the "
|
|
70
|
+
"profile runtime directory"
|
|
71
|
+
) from exc
|
|
72
|
+
current = run_dir
|
|
73
|
+
for part in relative_staging.parts:
|
|
74
|
+
if part in {"", ".", ".."}:
|
|
75
|
+
raise AccessOperationError(
|
|
76
|
+
"[access].staging_dir must be a normalized runtime path"
|
|
77
|
+
)
|
|
78
|
+
current = current / part
|
|
79
|
+
if current.is_symlink():
|
|
80
|
+
raise AccessOperationError(
|
|
81
|
+
"[access].staging_dir must not contain symbolic links"
|
|
82
|
+
)
|
|
83
|
+
staging = current
|
|
84
|
+
if staging == run_dir or run_dir not in staging.parents:
|
|
85
|
+
raise AccessOperationError(
|
|
86
|
+
"[access].staging_dir must stay inside the "
|
|
87
|
+
"profile runtime directory"
|
|
88
|
+
)
|
|
89
|
+
ensure_private_directory(run_dir)
|
|
90
|
+
ensure_private_directory(staging)
|
|
91
|
+
return staging, staging / virtual.name, database_path
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def access_identity(
|
|
95
|
+
run_directory: str | os.PathLike[str], *, create: bool = True
|
|
96
|
+
) -> str | None:
|
|
97
|
+
"""Return this lifecycle's unique history identity."""
|
|
98
|
+
run_dir = Path(run_directory)
|
|
99
|
+
path = run_dir / "access-lifecycle.json"
|
|
100
|
+
if os.path.lexists(path):
|
|
101
|
+
try:
|
|
102
|
+
metadata = path.lstat()
|
|
103
|
+
if (
|
|
104
|
+
not stat.S_ISREG(metadata.st_mode)
|
|
105
|
+
or metadata.st_uid != os.getuid()
|
|
106
|
+
or stat.S_IMODE(metadata.st_mode) & 0o077
|
|
107
|
+
):
|
|
108
|
+
raise AccessOperationError(
|
|
109
|
+
"access lifecycle metadata is not private"
|
|
110
|
+
)
|
|
111
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
112
|
+
identity = payload["identity"]
|
|
113
|
+
if not isinstance(identity, str) or not re.fullmatch(
|
|
114
|
+
r"session:kp-access:[0-9a-f]{32}", identity
|
|
115
|
+
):
|
|
116
|
+
raise AccessOperationError(
|
|
117
|
+
"access lifecycle metadata is invalid"
|
|
118
|
+
)
|
|
119
|
+
return identity
|
|
120
|
+
except (
|
|
121
|
+
OSError,
|
|
122
|
+
UnicodeError,
|
|
123
|
+
json.JSONDecodeError,
|
|
124
|
+
KeyError,
|
|
125
|
+
TypeError,
|
|
126
|
+
) as exc:
|
|
127
|
+
raise AccessOperationError(
|
|
128
|
+
f"cannot read access lifecycle metadata: {exc}"
|
|
129
|
+
) from exc
|
|
130
|
+
|
|
131
|
+
if not create:
|
|
132
|
+
return None
|
|
133
|
+
from kp_sync.sessions.records import SessionStore
|
|
134
|
+
from kp_sync.state import HistoryState
|
|
135
|
+
|
|
136
|
+
retired = set(HistoryState.load(run_dir / "state.json").retirements)
|
|
137
|
+
pending = {
|
|
138
|
+
entry_identity
|
|
139
|
+
for entry_identity, _, _ in SessionStore(run_dir).pending_retirements()
|
|
140
|
+
}
|
|
141
|
+
identity = ACCESS_IDENTITY_PREFIX + secrets.token_hex(16)
|
|
142
|
+
while identity in retired or identity in pending:
|
|
143
|
+
identity = ACCESS_IDENTITY_PREFIX + secrets.token_hex(16)
|
|
144
|
+
payload = json.dumps({"identity": identity}, sort_keys=True) + "\n"
|
|
145
|
+
temporary = run_dir / f".access-lifecycle-{secrets.token_hex(8)}.tmp"
|
|
146
|
+
try:
|
|
147
|
+
atomic_write(temporary, payload)
|
|
148
|
+
os.link(temporary, path)
|
|
149
|
+
except FileExistsError:
|
|
150
|
+
return access_identity(run_dir, create=False)
|
|
151
|
+
finally:
|
|
152
|
+
temporary.unlink(missing_ok=True)
|
|
153
|
+
_fsync_directory(run_dir)
|
|
154
|
+
return identity
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def validate_file_path(
|
|
158
|
+
config,
|
|
159
|
+
run_directory: str | os.PathLike[str],
|
|
160
|
+
value: str,
|
|
161
|
+
*,
|
|
162
|
+
database_only: bool = False,
|
|
163
|
+
) -> Path:
|
|
164
|
+
"""Validate a virtual path and map it into the staging directory.
|
|
165
|
+
|
|
166
|
+
Only the database and temporary siblings are allowed. When
|
|
167
|
+
``database_only`` is true, only the database itself is accepted.
|
|
168
|
+
"""
|
|
169
|
+
staging, database, configured_db = access_paths(config, run_directory)
|
|
170
|
+
path = _virtual_path(value)
|
|
171
|
+
root = _virtual_path(configured_db)
|
|
172
|
+
if path.parent != root.parent:
|
|
173
|
+
raise AccessOperationError(
|
|
174
|
+
"file operation path is outside the configured database directory"
|
|
175
|
+
)
|
|
176
|
+
if path.name != root.name and not path.name.startswith(root.name + "."):
|
|
177
|
+
raise AccessOperationError(
|
|
178
|
+
"file operation path is not the database or one of its "
|
|
179
|
+
"temporary names"
|
|
180
|
+
)
|
|
181
|
+
if database_only and path != root:
|
|
182
|
+
raise AccessOperationError(
|
|
183
|
+
"operation is only valid for the database path"
|
|
184
|
+
)
|
|
185
|
+
local = staging / path.name
|
|
186
|
+
_check_stage_file(local, must_exist=False)
|
|
187
|
+
return database if path == root else local
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def validate_operation(
|
|
191
|
+
config,
|
|
192
|
+
run_directory: str | os.PathLike[str],
|
|
193
|
+
operation: str,
|
|
194
|
+
file_path: str = "",
|
|
195
|
+
destination: str = "",
|
|
196
|
+
) -> tuple[Path | None, Path | None]:
|
|
197
|
+
"""Validate an operation's source and optional destination paths.
|
|
198
|
+
|
|
199
|
+
BEGIN and END accept no paths; GET accepts only the database path.
|
|
200
|
+
"""
|
|
201
|
+
if operation not in _OPERATIONS:
|
|
202
|
+
raise AccessOperationError("unsupported kp-access operation")
|
|
203
|
+
if operation in {"BEGIN", "END"}:
|
|
204
|
+
if file_path or destination:
|
|
205
|
+
raise AccessOperationError(
|
|
206
|
+
f"{operation} must not include file paths"
|
|
207
|
+
)
|
|
208
|
+
return None, None
|
|
209
|
+
if operation == "GET":
|
|
210
|
+
return (
|
|
211
|
+
validate_file_path(
|
|
212
|
+
config,
|
|
213
|
+
run_directory,
|
|
214
|
+
file_path,
|
|
215
|
+
database_only=True,
|
|
216
|
+
),
|
|
217
|
+
None,
|
|
218
|
+
)
|
|
219
|
+
source = validate_file_path(config, run_directory, file_path)
|
|
220
|
+
target = None
|
|
221
|
+
if operation == "MOVE":
|
|
222
|
+
if not destination:
|
|
223
|
+
raise AccessOperationError("MOVE requires a destination")
|
|
224
|
+
target = validate_file_path(config, run_directory, destination)
|
|
225
|
+
elif destination:
|
|
226
|
+
raise AccessOperationError(
|
|
227
|
+
f"{operation} must not include a destination"
|
|
228
|
+
)
|
|
229
|
+
return source, target
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def create_upload(config, run_directory, payload: bytes) -> str:
|
|
233
|
+
"""Write a private, fsynced upload and return its ID."""
|
|
234
|
+
with file_lock(
|
|
235
|
+
Path(run_directory) / "access-op.lock",
|
|
236
|
+
config.sync["lock_timeout"],
|
|
237
|
+
):
|
|
238
|
+
return _create_upload(config, run_directory, payload)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _create_upload(config, run_directory, payload: bytes) -> str:
|
|
242
|
+
staging, _, _ = access_paths(config, run_directory)
|
|
243
|
+
identifier = secrets.token_hex(16)
|
|
244
|
+
path = staging / f".kp-sync-upload-{identifier}"
|
|
245
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
|
|
246
|
+
descriptor = os.open(path, flags, 0o600)
|
|
247
|
+
try:
|
|
248
|
+
with os.fdopen(descriptor, "wb") as output:
|
|
249
|
+
output.write(payload)
|
|
250
|
+
output.flush()
|
|
251
|
+
os.fsync(output.fileno())
|
|
252
|
+
except BaseException:
|
|
253
|
+
path.unlink(missing_ok=True)
|
|
254
|
+
raise
|
|
255
|
+
return identifier
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def discard_upload(config, run_directory, identifier: str) -> None:
|
|
259
|
+
"""Remove a pending upload when its identifier is valid."""
|
|
260
|
+
if not isinstance(identifier, str) or not _UPLOAD_ID.fullmatch(identifier):
|
|
261
|
+
return
|
|
262
|
+
staging, _, _ = access_paths(config, run_directory)
|
|
263
|
+
(staging / f".kp-sync-upload-{identifier}").unlink(missing_ok=True)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def apply_file_operation(
|
|
267
|
+
config,
|
|
268
|
+
run_directory,
|
|
269
|
+
*,
|
|
270
|
+
operation: str,
|
|
271
|
+
file_path: str,
|
|
272
|
+
destination: str = "",
|
|
273
|
+
upload_id: str | None = None,
|
|
274
|
+
) -> tuple[bool, Path | None]:
|
|
275
|
+
"""Apply one validated file operation to the staged database.
|
|
276
|
+
|
|
277
|
+
The Boolean indicates whether the database changed. Replacing or
|
|
278
|
+
deleting files first creates backups. Uploads pass KDBX checks.
|
|
279
|
+
"""
|
|
280
|
+
source, target = validate_operation(
|
|
281
|
+
config,
|
|
282
|
+
run_directory,
|
|
283
|
+
operation,
|
|
284
|
+
file_path,
|
|
285
|
+
destination,
|
|
286
|
+
)
|
|
287
|
+
staging, database, _ = access_paths(config, run_directory)
|
|
288
|
+
if operation == "GET":
|
|
289
|
+
return False, source
|
|
290
|
+
if operation == "PUT":
|
|
291
|
+
if upload_id is None or not _UPLOAD_ID.fullmatch(upload_id):
|
|
292
|
+
raise AccessOperationError("PUT requires a valid upload id")
|
|
293
|
+
upload = staging / f".kp-sync-upload-{upload_id}"
|
|
294
|
+
_check_stage_file(upload, must_exist=True)
|
|
295
|
+
assert source is not None
|
|
296
|
+
if source == database:
|
|
297
|
+
_inspect_database(upload)
|
|
298
|
+
_backup_existing(source, run_directory, config)
|
|
299
|
+
os.replace(upload, source)
|
|
300
|
+
_fsync_directory(staging)
|
|
301
|
+
return source == database, source
|
|
302
|
+
if operation == "DELETE":
|
|
303
|
+
assert source is not None
|
|
304
|
+
_check_stage_file(source, must_exist=True)
|
|
305
|
+
_backup_existing(source, run_directory, config)
|
|
306
|
+
source.unlink()
|
|
307
|
+
_fsync_directory(staging)
|
|
308
|
+
return False, source if source == database else None
|
|
309
|
+
if operation == "MOVE":
|
|
310
|
+
assert source is not None and target is not None
|
|
311
|
+
_check_stage_file(source, must_exist=True)
|
|
312
|
+
_check_stage_file(target, must_exist=False)
|
|
313
|
+
if target == database:
|
|
314
|
+
_inspect_database(source)
|
|
315
|
+
_backup_existing(target, run_directory, config)
|
|
316
|
+
os.replace(source, target)
|
|
317
|
+
_fsync_directory(staging)
|
|
318
|
+
return target == database, target
|
|
319
|
+
raise AccessOperationError("unsupported file operation")
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def transit_path(run_directory: str | os.PathLike[str]) -> Path:
|
|
323
|
+
"""Return the runtime marker path for an incomplete remote save."""
|
|
324
|
+
return Path(run_directory) / "access-in-transit.json"
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def mark_transit(run_directory, *, now: float) -> None:
|
|
328
|
+
"""Record when a remote save enters its delete/move window."""
|
|
329
|
+
atomic_write(
|
|
330
|
+
transit_path(run_directory),
|
|
331
|
+
json.dumps({"version": 1, "since": now}, sort_keys=True) + "\n",
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def clear_transit(run_directory) -> None:
|
|
336
|
+
"""Remove the remote-save marker, rejecting a symlink."""
|
|
337
|
+
path = transit_path(run_directory)
|
|
338
|
+
if path.is_symlink():
|
|
339
|
+
raise AccessOperationError(
|
|
340
|
+
"refusing to remove an unsafe in-transit marker"
|
|
341
|
+
)
|
|
342
|
+
path.unlink(missing_ok=True)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def in_transit(run_directory, *, now: float) -> bool:
|
|
346
|
+
"""Check whether a transit marker remains valid."""
|
|
347
|
+
path = transit_path(run_directory)
|
|
348
|
+
if not os.path.lexists(path):
|
|
349
|
+
return False
|
|
350
|
+
if path.is_symlink():
|
|
351
|
+
raise AccessOperationError("unsafe in-transit marker")
|
|
352
|
+
metadata = path.stat()
|
|
353
|
+
if (
|
|
354
|
+
not stat.S_ISREG(metadata.st_mode)
|
|
355
|
+
or metadata.st_uid != os.getuid()
|
|
356
|
+
or stat.S_IMODE(metadata.st_mode) & 0o077
|
|
357
|
+
):
|
|
358
|
+
raise AccessOperationError("unsafe in-transit marker")
|
|
359
|
+
try:
|
|
360
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
361
|
+
except (OSError, ValueError) as exc:
|
|
362
|
+
raise AccessOperationError(
|
|
363
|
+
f"cannot read in-transit marker: {exc}"
|
|
364
|
+
) from exc
|
|
365
|
+
if (
|
|
366
|
+
not isinstance(payload, dict)
|
|
367
|
+
or set(payload) != {"version", "since"}
|
|
368
|
+
or payload["version"] != 1
|
|
369
|
+
or type(payload["since"]) not in {int, float}
|
|
370
|
+
or payload["since"] > now
|
|
371
|
+
):
|
|
372
|
+
raise AccessOperationError("invalid in-transit marker")
|
|
373
|
+
if now - payload["since"] < ACCESS_TTL_SECONDS:
|
|
374
|
+
return True
|
|
375
|
+
error_message = (
|
|
376
|
+
"kp-access database upload did not complete within one minute; "
|
|
377
|
+
"the staged copy is treated as missing"
|
|
378
|
+
)
|
|
379
|
+
from kp_sync.log import error
|
|
380
|
+
|
|
381
|
+
error(error_message)
|
|
382
|
+
clear_transit(run_directory)
|
|
383
|
+
return False
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _virtual_path(value: str) -> PurePosixPath:
|
|
387
|
+
if (
|
|
388
|
+
not isinstance(value, str)
|
|
389
|
+
or not value.startswith("/")
|
|
390
|
+
or "\0" in value
|
|
391
|
+
or "\\" in value
|
|
392
|
+
or "//" in value
|
|
393
|
+
):
|
|
394
|
+
raise AccessOperationError("invalid kp-access file path")
|
|
395
|
+
path = PurePosixPath(value)
|
|
396
|
+
if any(part in {"", ".", ".."} for part in path.parts[1:]):
|
|
397
|
+
raise AccessOperationError("invalid kp-access file path")
|
|
398
|
+
return path
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _check_stage_file(path: Path, *, must_exist: bool) -> None:
|
|
402
|
+
if path.parent.is_symlink():
|
|
403
|
+
raise AccessOperationError(
|
|
404
|
+
"staging directory must not be a symbolic link"
|
|
405
|
+
)
|
|
406
|
+
if not path.parent.is_dir():
|
|
407
|
+
raise AccessOperationError("staging directory is unavailable")
|
|
408
|
+
try:
|
|
409
|
+
metadata = path.lstat()
|
|
410
|
+
except FileNotFoundError:
|
|
411
|
+
if must_exist:
|
|
412
|
+
raise AccessOperationError(
|
|
413
|
+
f"staged file does not exist: {path.name}"
|
|
414
|
+
) from None
|
|
415
|
+
return
|
|
416
|
+
if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != os.getuid():
|
|
417
|
+
raise AccessOperationError(
|
|
418
|
+
f"staged path is not a regular user-owned file: {path.name}"
|
|
419
|
+
)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _inspect_database(path: Path) -> None:
|
|
423
|
+
try:
|
|
424
|
+
inspect_kdbx(path)
|
|
425
|
+
except (OSError, KdbxError) as exc:
|
|
426
|
+
raise AccessOperationError(
|
|
427
|
+
f"uploaded database failed KDBX verification: {exc}"
|
|
428
|
+
) from exc
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _backup_existing(path: Path, run_directory, config) -> None:
|
|
432
|
+
_check_stage_file(path, must_exist=False)
|
|
433
|
+
if path.exists():
|
|
434
|
+
backup_file(
|
|
435
|
+
path,
|
|
436
|
+
Path(run_directory) / "backups",
|
|
437
|
+
identity=ACCESS_IDENTITY,
|
|
438
|
+
keep=config.backups["keep"],
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _fsync_directory(path: Path) -> None:
|
|
443
|
+
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
|
|
444
|
+
try:
|
|
445
|
+
os.fsync(descriptor)
|
|
446
|
+
finally:
|
|
447
|
+
os.close(descriptor)
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def atomic_copy(source: Path, target: Path) -> None:
|
|
451
|
+
"""Atomically copy a regular file with private mode and fsync."""
|
|
452
|
+
if source.is_symlink() or not source.is_file():
|
|
453
|
+
raise AccessOperationError("source database is not a regular file")
|
|
454
|
+
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
455
|
+
temporary = target.parent / f".{target.name}.stage-{secrets.token_hex(8)}"
|
|
456
|
+
try:
|
|
457
|
+
with source.open("rb") as incoming, temporary.open("xb") as outgoing:
|
|
458
|
+
os.fchmod(outgoing.fileno(), 0o600)
|
|
459
|
+
shutil.copyfileobj(incoming, outgoing)
|
|
460
|
+
outgoing.flush()
|
|
461
|
+
os.fsync(outgoing.fileno())
|
|
462
|
+
os.replace(temporary, target)
|
|
463
|
+
_fsync_directory(target.parent)
|
|
464
|
+
except BaseException:
|
|
465
|
+
temporary.unlink(missing_ok=True)
|
|
466
|
+
raise
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def database_hash(path: Path) -> str:
|
|
470
|
+
"""Return the staged database's SHA-256 fingerprint.
|
|
471
|
+
|
|
472
|
+
Raises:
|
|
473
|
+
AccessOperationError: If the staged database cannot be read.
|
|
474
|
+
"""
|
|
475
|
+
try:
|
|
476
|
+
return EndpointFingerprint.from_file(path).sha256 or ""
|
|
477
|
+
except OSError as exc:
|
|
478
|
+
raise AccessOperationError(
|
|
479
|
+
f"cannot read staged database: {exc}"
|
|
480
|
+
) from exc
|