fscryptography 0.1.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.
@@ -0,0 +1,116 @@
1
+ """Tink-backed codec for encrypted filesystem name components."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import binascii
7
+ import re
8
+ from typing import Protocol
9
+
10
+ from ..errors import AuthenticationError, BackendError, FormatError, NameConstraintError
11
+ from .validation import NameProfile, validate_name
12
+
13
+ MARKER = "~1"
14
+ AAD = b"fscryptography:filename:v1"
15
+ TINK_AES256_GCM_OVERHEAD = 33
16
+ _BASE64URL = re.compile(r"[A-Za-z0-9_-]+", re.ASCII)
17
+
18
+
19
+ class AeadPrimitive(Protocol):
20
+ def encrypt(self, plaintext: bytes, associated_data: bytes) -> bytes: ...
21
+ def decrypt(self, ciphertext: bytes, associated_data: bytes) -> bytes: ...
22
+
23
+
24
+ def _encode_ciphertext(ciphertext: bytes) -> str:
25
+ return base64.urlsafe_b64encode(ciphertext).rstrip(b"=").decode("ascii")
26
+
27
+
28
+ def _decode_ciphertext(value: str) -> bytes:
29
+ if not isinstance(value, str):
30
+ raise TypeError("encoded_name must be str")
31
+ if not value.startswith(MARKER):
32
+ raise FormatError("encrypted name marker is missing")
33
+ body = value[len(MARKER):]
34
+ if not body or _BASE64URL.fullmatch(body) is None:
35
+ raise FormatError("encrypted name is not canonical Base64URL")
36
+ try:
37
+ raw = base64.b64decode(
38
+ body + "=" * ((4 - len(body) % 4) % 4),
39
+ altchars=b"-_",
40
+ validate=True,
41
+ )
42
+ except (binascii.Error, ValueError) as exc:
43
+ raise FormatError("encrypted name is not valid Base64URL") from exc
44
+ if _encode_ciphertext(raw) != body:
45
+ raise FormatError("encrypted name is not canonical Base64URL")
46
+ # A TINK-prefixed AES256_GCM ciphertext needs 5 prefix + 12 nonce + 16 tag.
47
+ if len(raw) < TINK_AES256_GCM_OVERHEAD:
48
+ raise FormatError("encrypted name ciphertext is truncated")
49
+ return raw
50
+
51
+
52
+ def is_canonical_candidate(value: str) -> bool:
53
+ """Return whether value has the complete canonical textual envelope."""
54
+ if not isinstance(value, str) or not value.startswith(MARKER):
55
+ return False
56
+ try:
57
+ _decode_ciphertext(value)
58
+ except (FormatError, TypeError):
59
+ return False
60
+ return True
61
+
62
+
63
+ def encrypt_name(
64
+ name: str,
65
+ primitive: AeadPrimitive,
66
+ *,
67
+ profile: NameProfile = NameProfile.GNU_LINUX,
68
+ max_component_bytes: int | None = 255,
69
+ ) -> str:
70
+ """Encrypt a plaintext component, refusing active-key double encryption."""
71
+ plaintext = validate_name(name, profile=profile)
72
+ if is_canonical_candidate(name):
73
+ try:
74
+ primitive.decrypt(_decode_ciphertext(name), AAD)
75
+ except Exception:
76
+ # A syntactically valid candidate that does not authenticate remains
77
+ # a possible plaintext name. Do not disclose why authentication failed.
78
+ pass
79
+ else:
80
+ raise NameConstraintError("name is already encrypted with the active key")
81
+
82
+ try:
83
+ ciphertext = primitive.encrypt(plaintext, AAD)
84
+ except Exception as exc:
85
+ raise BackendError("filename encryption backend failed") from exc
86
+
87
+ if not isinstance(ciphertext, bytes):
88
+ raise BackendError("filename encryption backend returned an invalid value")
89
+ encoded = MARKER + _encode_ciphertext(ciphertext)
90
+ encoded_size = len(encoded.encode("ascii"))
91
+ if max_component_bytes is not None and encoded_size > max_component_bytes:
92
+ raise NameConstraintError("encrypted name exceeds the destination component limit")
93
+ return encoded
94
+
95
+
96
+ def decrypt_name(
97
+ encoded_name: str,
98
+ primitive: AeadPrimitive,
99
+ *,
100
+ profile: NameProfile = NameProfile.GNU_LINUX,
101
+ max_component_bytes: int | None = 255,
102
+ ) -> str:
103
+ """Authenticate and decode a single encrypted component."""
104
+ ciphertext = _decode_ciphertext(encoded_name)
105
+ try:
106
+ plaintext = primitive.decrypt(ciphertext, AAD)
107
+ except Exception as exc:
108
+ raise AuthenticationError("encrypted name authentication failed") from exc
109
+ if not isinstance(plaintext, bytes):
110
+ raise BackendError("filename decryption backend returned an invalid value")
111
+ try:
112
+ name = plaintext.decode("utf-8", errors="strict")
113
+ except UnicodeDecodeError as exc:
114
+ raise FormatError("authenticated filename is not valid UTF-8") from exc
115
+ validate_name(name, profile=profile, max_component_bytes=max_component_bytes)
116
+ return name
@@ -0,0 +1,28 @@
1
+ """Google Tink adapter for filename AEAD keysets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tink
6
+ from tink import aead, secret_key_access
7
+
8
+ from ..errors import BackendError
9
+
10
+
11
+ def load_name_primitive(serialized_keyset: bytes) -> aead.Aead:
12
+ """Restore a Tink Aead primitive from a serialized protobuf keyset.
13
+
14
+ The caller is responsible for obtaining the names keyset from the
15
+ authenticated MasterKey container. This function never generates keys.
16
+ """
17
+ if not isinstance(serialized_keyset, bytes):
18
+ raise TypeError("serialized_keyset must be bytes")
19
+ if not serialized_keyset:
20
+ raise ValueError("serialized_keyset must not be empty")
21
+ try:
22
+ aead.register()
23
+ handle = tink.proto_keyset_format.parse(
24
+ serialized_keyset, secret_key_access.TOKEN
25
+ )
26
+ return handle.primitive(aead.Aead)
27
+ except Exception as exc:
28
+ raise BackendError("unable to load filename AEAD keyset") from exc
@@ -0,0 +1,84 @@
1
+ """Filesystem name validation independent from path traversal or mutation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import Enum
6
+
7
+ from ..errors import NameConstraintError
8
+
9
+
10
+ class NameProfile(str, Enum):
11
+ """Name constraints applied to a single filesystem component."""
12
+
13
+ WINDOWS = "windows"
14
+ GNU_LINUX = "gnu-linux"
15
+
16
+
17
+ _WINDOWS_FORBIDDEN = frozenset('<>:"/\\|?*')
18
+ _WINDOWS_RESERVED = frozenset(
19
+ {"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "CLOCK$"}
20
+ )
21
+ _SUPERSCRIPT_DIGITS = "¹²³"
22
+
23
+
24
+ def _as_component_bytes(name: str) -> bytes:
25
+ if not isinstance(name, str):
26
+ raise TypeError("name must be str")
27
+ try:
28
+ encoded = name.encode("utf-8", errors="strict")
29
+ except UnicodeEncodeError as exc:
30
+ raise NameConstraintError("name is not valid UTF-8") from exc
31
+ if not name:
32
+ raise NameConstraintError("name component must not be empty")
33
+ if name in {".", ".."}:
34
+ raise NameConstraintError("dot path components are not valid resource names")
35
+ if "\x00" in name or "/" in name:
36
+ raise NameConstraintError("name must be a single path component")
37
+ return encoded
38
+
39
+
40
+ def _is_reserved_windows_device(name: str) -> bool:
41
+ stem = name.split(".", 1)[0].upper()
42
+ if stem in _WINDOWS_RESERVED:
43
+ return True
44
+ if len(stem) == 4 and stem[:3] in {"COM", "LPT"}:
45
+ return stem[3] in "123456789" or stem[3] in _SUPERSCRIPT_DIGITS
46
+ return False
47
+
48
+
49
+ def validate_name(
50
+ name: str,
51
+ *,
52
+ profile: NameProfile = NameProfile.GNU_LINUX,
53
+ max_component_bytes: int | None = None,
54
+ ) -> bytes:
55
+ """Validate one plaintext component and return its strict UTF-8 bytes.
56
+
57
+ The caller supplies the effective destination component limit when known.
58
+ No Unicode normalization or case folding is performed.
59
+ """
60
+ encoded = _as_component_bytes(name)
61
+ try:
62
+ selected = NameProfile(profile)
63
+ except ValueError as exc:
64
+ raise ValueError(f"unsupported name profile: {profile!r}") from exc
65
+
66
+ if selected is NameProfile.WINDOWS:
67
+ if any(char in _WINDOWS_FORBIDDEN for char in name):
68
+ raise NameConstraintError("name contains a character forbidden by Windows")
69
+ if any(ord(char) < 0x20 for char in name):
70
+ raise NameConstraintError("name contains a Windows control character")
71
+ if name.endswith((".", " ")):
72
+ raise NameConstraintError("Windows names must not end in dot or space")
73
+ if _is_reserved_windows_device(name):
74
+ raise NameConstraintError("name is a reserved Windows device name")
75
+
76
+ if max_component_bytes is not None:
77
+ if isinstance(max_component_bytes, bool) or not isinstance(max_component_bytes, int):
78
+ raise TypeError("max_component_bytes must be an integer or None")
79
+ if max_component_bytes <= 0:
80
+ raise ValueError("max_component_bytes must be positive")
81
+ if len(encoded) > max_component_bytes:
82
+ raise NameConstraintError("name exceeds the destination component limit")
83
+
84
+ return encoded
File without changes
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.4
2
+ Name: fscryptography
3
+ Version: 0.1.0
4
+ Summary: Filesystem-oriented authenticated encryption for files and names
5
+ License-Expression: LicenseRef-Proprietary
6
+ Project-URL: Homepage, https://github.com/specter327/fscryptography
7
+ Project-URL: Repository, https://github.com/specter327/fscryptography
8
+ Project-URL: Documentation, https://github.com/specter327/fscryptography/tree/main/docs
9
+ Project-URL: Issues, https://github.com/specter327/fscryptography/issues
10
+ Project-URL: Changelog, https://github.com/specter327/fscryptography/releases
11
+ Keywords: cryptography,filesystem,file-encryption,authenticated-encryption,tink,argon2id
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Topic :: Security :: Cryptography
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Operating System :: Microsoft :: Windows
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: tink<2,>=1.16.1
26
+ Requires-Dist: argon2-cffi<26,>=23.1
27
+ Requires-Dist: cryptography<47,>=42
28
+ Provides-Extra: test
29
+ Requires-Dist: pytest<9,>=8; extra == "test"
30
+ Provides-Extra: dev
31
+ Requires-Dist: build<2,>=1.2; extra == "dev"
32
+ Requires-Dist: pytest<9,>=8; extra == "dev"
33
+ Requires-Dist: twine<7,>=5; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # fscryptography
37
+
38
+ **fscryptography** (*filesystem-cryptography*) es una librería Python para cifrar y descifrar archivos y nombres de archivos y directorios directamente sobre rutas del sistema de archivos.
39
+
40
+ Proporciona una API de alto nivel basada en rutas, cifrado autenticado y procesamiento segmentado para archivos grandes. No depende de herramientas de exploración de recursos ni de aplicaciones concretas.
41
+
42
+ ## Instalación
43
+
44
+ Requiere Python 3.11 o posterior.
45
+
46
+ ```bash
47
+ python -m pip install fscryptography
48
+ ```
49
+
50
+ ## Inicio rápido
51
+
52
+ ```python
53
+ from pathlib import Path
54
+
55
+ import fscryptography
56
+
57
+ # Genera una clave maestra aleatoria codificada en Base64.
58
+ master_key = fscryptography.generate()
59
+
60
+ # Guarda la clave de forma segura fuera del directorio que se cifra.
61
+ # Quien obtenga la clave podrá descifrar los recursos protegidos.
62
+
63
+ with fscryptography.Manager(key=master_key) as manager:
64
+ manager.file.encrypt(Path("document.txt"))
65
+ manager.file.decrypt(Path("document.fscrypt"))
66
+ ```
67
+
68
+ Para proteger el contenedor de clave maestra con contraseña:
69
+
70
+ ```python
71
+ master_key = fscryptography.generate(password="correct horse battery staple")
72
+
73
+ with fscryptography.Manager(
74
+ key=master_key,
75
+ password="correct horse battery staple",
76
+ ) as manager:
77
+ manager.file.encrypt("confidential.pdf", encrypt_name=True)
78
+ ```
79
+
80
+ La contraseña se consume al abrir el contenedor y no se conserva en el gestor. No debe confundirse la contraseña con una copia de seguridad de la clave: conserva la cadena Base64 de la MasterKey en un lugar seguro.
81
+
82
+ ## API principal
83
+
84
+ ```python
85
+ import fscryptography
86
+
87
+ master_key = fscryptography.generate()
88
+ # O bien: fscryptography.generate(password="...")
89
+
90
+ manager = fscryptography.Manager(key=master_key)
91
+ # Para una MasterKey protegida: Manager(key=master_key, password="...")
92
+
93
+ manager.file.encrypt("report.txt")
94
+ manager.file.encrypt("archive.tar.gz", new_extension=".locked")
95
+ manager.file.encrypt("private.txt", encrypt_name=True)
96
+ manager.file.decrypt("report.fscrypt")
97
+
98
+ manager.dir.encrypt("private-directory")
99
+ manager.dir.decrypt("~1...")
100
+
101
+ records = manager.inspect_recovery("/path/to/parent") # Inspección de solo lectura
102
+ exported_key = manager.export_key()
103
+ manager.close()
104
+ ```
105
+
106
+ Las operaciones de directorio transforman exclusivamente el nombre del directorio: **no recorren ni cifran su contenido**. La librería no ofrece una API pública de cifrado genérico de bytes o streams.
107
+
108
+ ## Diseño criptográfico
109
+
110
+ - Google Tink para Streaming AEAD de contenido (`AES256_GCM_HKDF_1MB`) y AEAD de nombres (`AES256_GCM`).
111
+ - Argon2id y AES-256-GCM para proteger una MasterKey cuando se especifica contraseña.
112
+ - Keysets independientes para contenido y nombres.
113
+ - Formatos versionados y metadata de archivo autenticada.
114
+ - Operaciones de filesystem diseñadas para evitar sobrescrituras accidentales y preservar información de transacciones interrumpidas.
115
+
116
+ ## Compatibilidad y límites
117
+
118
+ - Python 3.11+.
119
+ - GNU/Linux y Windows.
120
+ - En GNU/Linux se utilizan operaciones relativas a descriptores de directorio y publicación no-replace cuando el sistema las soporta.
121
+ - En Windows existen diferencias documentadas: no se ofrece el mismo anclaje de directorio ni la misma garantía de cuarentena del origen.
122
+ - No se garantiza protección frente a procesos hostiles que operen bajo el mismo UID/usuario.
123
+ - Las semánticas de durabilidad y renombrado de sistemas de archivos alternativos o de red no están validadas exhaustivamente.
124
+
125
+ La inspección del journal es explícita y de solo lectura. No hay recuperación destructiva ni limpieza automática de transacciones completadas.
126
+
127
+ ## Seguridad
128
+
129
+ Esta librería manipula claves criptográficas y archivos del usuario. Revisa el [modelo de seguridad](docs/security-model.md), la [política de gestión de claves](docs/key-management.md), la [compatibilidad de plataformas](docs/platform-compatibility.md) y la [documentación técnica](docs/index.md) antes de integrarla en un flujo sensible.
130
+
131
+ La protección criptográfica no sustituye las copias de seguridad, el control de acceso del sistema operativo ni una política de gestión y rotación de claves. La implementación y sus pruebas automatizadas no equivalen a una auditoría criptográfica independiente.
132
+
133
+ ## Licencia y derechos de uso
134
+
135
+ Este proyecto es software propietario y se distribuye bajo una política de **todos los derechos reservados**. No se concede una licencia pública para usar, copiar, modificar o redistribuir el software. Cualquier autorización requiere permiso previo y expreso por escrito del titular de los derechos.
136
+
137
+ Consulta el archivo [LICENSE](LICENSE). La disponibilidad del código fuente en GitHub o de un paquete en PyPI no implica la concesión de derechos adicionales.
138
+
139
+ ## Desarrollo
140
+
141
+ Instala las dependencias de desarrollo:
142
+
143
+ ```bash
144
+ python -m pip install -e ".[dev]"
145
+ ```
146
+
147
+ Ejecuta las pruebas:
148
+
149
+ ```bash
150
+ python -m pytest
151
+ ```
152
+
153
+ Construye y valida los artefactos de distribución:
154
+
155
+ ```bash
156
+ python -m build
157
+ python -m twine check dist/*
158
+ ```
159
+
160
+ El proyecto utiliza un diseño `src/` y publica un wheel y un source distribution (sdist). La publicación a PyPI se automatiza mediante GitHub Actions y Trusted Publishing (OIDC); no requiere almacenar un token PyPI de larga duración en los secretos del repositorio.
161
+
162
+ ## Estado
163
+
164
+ Versión inicial de distribución: **0.1.0**. El proyecto continúa en fase alpha. Consulta [GitHub Releases](https://github.com/specter327/fscryptography/releases) para conocer las versiones publicadas y sus notas.
165
+
166
+ ## Documentación
167
+
168
+ La documentación normativa y técnica está en [docs/](docs/index.md). El [contrato de API](docs/api-reference.md) describe las operaciones, retornos y excepciones.
@@ -0,0 +1,18 @@
1
+ fscryptography/__init__.py,sha256=q4QgTZ6cc53ARGunIn2w-Yy3T24GeyRDhCPTUO2SlmI,912
2
+ fscryptography/_directory.py,sha256=bimTeeF5l36b5tmi1A2Usp6hoV_U3pomaj7NeHX30Iw,3927
3
+ fscryptography/_filesystem.py,sha256=VffjI7JxmdK9e1quB-6M6e_QqbKpg_sMpB2P14dYi_0,26344
4
+ fscryptography/_journal.py,sha256=HgJz6TNTL6kVGSinHbW8gtbD8Ny5-7_LfSqO2hwyQVE,24577
5
+ fscryptography/_master_key.py,sha256=VAddAU-dXJmKBhKSG-3ULma4UDw07eSZ_1mGyOA3Ies,11265
6
+ fscryptography/crypto.py,sha256=5nCF2VNfK8DZQ1EtChr1H65Fc2JoGDyeH7_aoO9jE1k,2948
7
+ fscryptography/errors.py,sha256=9aJ3kSNMFPu4SYFc62F3CubhpT811x0p8BsiWRxb-OQ,1485
8
+ fscryptography/file_format.py,sha256=3Du702Yx5v1glFAW2ukdgLr1f__45ncAW5w3TxCKZvE,7022
9
+ fscryptography/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ fscryptography/names/__init__.py,sha256=GbXpv6Vt4ADiHXwCIl4uKUcFAQIt4bs1vBCzvBiVjW4,411
11
+ fscryptography/names/codec.py,sha256=ICoS05GA0FlFl32lV2RpWvHr5wki4oh_hzOpWvVdiJo,4282
12
+ fscryptography/names/tink_backend.py,sha256=0eqXqMzGV-UiX44rs6Ascqd0njav8XCZ-XOyNC0xp5M,966
13
+ fscryptography/names/validation.py,sha256=whhYAZWvv1UiCtR7zi4HwKiw2yYSIjnUvnp0XtL1v8c,3039
14
+ fscryptography-0.1.0.dist-info/licenses/LICENSE,sha256=W2QDlv0dthg5KLXEwRxB3--IWuTjy9KATaiaS0ni7fw,1220
15
+ fscryptography-0.1.0.dist-info/METADATA,sha256=7Vs0QLVuu-Y_a2bN88LP7VKO7oG2nNk9mqz6Gsnen9U,7206
16
+ fscryptography-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
17
+ fscryptography-0.1.0.dist-info/top_level.txt,sha256=mtgdm_YPtJFA6LJ_EY___iYe23RhMkoUlcs6P4NC5sI,15
18
+ fscryptography-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,25 @@
1
+ Copyright (c) 2026 Specter327. All rights reserved.
2
+
3
+ PROPRIETARY SOFTWARE — ALL RIGHTS RESERVED
4
+
5
+ This software, including its source code, documentation, and associated
6
+ materials (the "Software"), is proprietary and is protected by applicable
7
+ copyright and other intellectual property laws.
8
+
9
+ No license or other permission is granted, expressly or by implication, to
10
+ any person to use, reproduce, modify, adapt, translate, publish, distribute,
11
+ sublicense, sell, rent, publicly display, publicly perform, or create
12
+ derivative works of the Software, in whole or in part.
13
+
14
+ Access to, viewing of, or possession of a copy of the Software does not
15
+ constitute permission to exercise any of the rights listed above. Any use,
16
+ copying, modification, or distribution requires the prior express written
17
+ authorization of the copyright holder, unless such activity is permitted
18
+ under applicable mandatory law.
19
+
20
+ To request a separate license or written authorization, contact the
21
+ copyright holder through the repository's official communication channels.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", TO THE MAXIMUM EXTENT PERMITTED BY
24
+ APPLICABLE LAW. THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES AND
25
+ LIABILITY TO THE EXTENT PERMITTED BY LAW.
@@ -0,0 +1 @@
1
+ fscryptography