vanishly 4.0.0__tar.gz
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.
- vanishly-4.0.0/PKG-INFO +42 -0
- vanishly-4.0.0/README.md +27 -0
- vanishly-4.0.0/pyproject.toml +28 -0
- vanishly-4.0.0/setup.cfg +4 -0
- vanishly-4.0.0/src/vanishly/__init__.py +12 -0
- vanishly-4.0.0/src/vanishly/cli.py +225 -0
- vanishly-4.0.0/src/vanishly/client.py +281 -0
- vanishly-4.0.0/src/vanishly/crypto.py +94 -0
- vanishly-4.0.0/src/vanishly.egg-info/PKG-INFO +42 -0
- vanishly-4.0.0/src/vanishly.egg-info/SOURCES.txt +14 -0
- vanishly-4.0.0/src/vanishly.egg-info/dependency_links.txt +1 -0
- vanishly-4.0.0/src/vanishly.egg-info/entry_points.txt +2 -0
- vanishly-4.0.0/src/vanishly.egg-info/requires.txt +1 -0
- vanishly-4.0.0/src/vanishly.egg-info/top_level.txt +1 -0
- vanishly-4.0.0/tests/test_cli.py +32 -0
- vanishly-4.0.0/tests/test_vectors.py +66 -0
vanishly-4.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vanishly
|
|
3
|
+
Version: 4.0.0
|
|
4
|
+
Summary: Client for Vanishly: end-to-end encrypted one-time secrets, the whole API and a command line tool
|
|
5
|
+
License-Expression: GPL-3.0-or-later
|
|
6
|
+
Project-URL: Homepage, https://github.com/DennisPohlmann/vanishly
|
|
7
|
+
Project-URL: Documentation, https://github.com/DennisPohlmann/vanishly/blob/main/docs/CLIENTS.md
|
|
8
|
+
Keywords: secrets,one-time,end-to-end encryption,vanishly
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Topic :: Security :: Cryptography
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
Requires-Dist: cryptography>=42
|
|
15
|
+
|
|
16
|
+
# vanishly (Python)
|
|
17
|
+
|
|
18
|
+
Client for [Vanishly](https://github.com/DennisPohlmann/vanishly), one-time
|
|
19
|
+
secrets: the whole API as a library and the command line tool `vanishly`.
|
|
20
|
+
|
|
21
|
+
Full documentation: [docs/CLIENTS.md](https://github.com/DennisPohlmann/vanishly/blob/main/docs/CLIENTS.md). End-to-end encrypted (crypto format v1, the same as the web pages): the secret, the key and the passphrase never reach the server; the key is only in the link's `#` part.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install vanishly
|
|
25
|
+
vanishly share 's3cret' --url https://ots.example.com --ttl 3600
|
|
26
|
+
vanishly share --url https://ots.example.com --ttl 3600 # asks for the secret, prints the link
|
|
27
|
+
vanishly open 'https://ots.example.com/s/<id>#<key>'
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from vanishly import Client
|
|
32
|
+
|
|
33
|
+
c = Client("https://ots.example.com", token=None) # token: vnly_... with sign-in
|
|
34
|
+
res = c.create("s3cret", passphrase="", ttl=3600, views=1)
|
|
35
|
+
print(res["shareUrl"], res["receiptUrl"])
|
|
36
|
+
print(c.open(res["shareUrl"])["secret"])
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Every endpoint has a method (`c.receipt(id)`, `c.burn(id)`, `c.me()`,
|
|
40
|
+
`c.tokens()`, `c.audit()`, ...); `c.request(method, path, body)` calls any
|
|
41
|
+
other. Errors raise `vanishly.ApiError` (`status`, `error`, `message`).
|
|
42
|
+
Needs Python 3.9+ and `cryptography`.
|
vanishly-4.0.0/README.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# vanishly (Python)
|
|
2
|
+
|
|
3
|
+
Client for [Vanishly](https://github.com/DennisPohlmann/vanishly), one-time
|
|
4
|
+
secrets: the whole API as a library and the command line tool `vanishly`.
|
|
5
|
+
|
|
6
|
+
Full documentation: [docs/CLIENTS.md](https://github.com/DennisPohlmann/vanishly/blob/main/docs/CLIENTS.md). End-to-end encrypted (crypto format v1, the same as the web pages): the secret, the key and the passphrase never reach the server; the key is only in the link's `#` part.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install vanishly
|
|
10
|
+
vanishly share 's3cret' --url https://ots.example.com --ttl 3600
|
|
11
|
+
vanishly share --url https://ots.example.com --ttl 3600 # asks for the secret, prints the link
|
|
12
|
+
vanishly open 'https://ots.example.com/s/<id>#<key>'
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from vanishly import Client
|
|
17
|
+
|
|
18
|
+
c = Client("https://ots.example.com", token=None) # token: vnly_... with sign-in
|
|
19
|
+
res = c.create("s3cret", passphrase="", ttl=3600, views=1)
|
|
20
|
+
print(res["shareUrl"], res["receiptUrl"])
|
|
21
|
+
print(c.open(res["shareUrl"])["secret"])
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Every endpoint has a method (`c.receipt(id)`, `c.burn(id)`, `c.me()`,
|
|
25
|
+
`c.tokens()`, `c.audit()`, ...); `c.request(method, path, body)` calls any
|
|
26
|
+
other. Errors raise `vanishly.ApiError` (`status`, `error`, `message`).
|
|
27
|
+
Needs Python 3.9+ and `cryptography`.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "vanishly"
|
|
7
|
+
version = "4.0.0"
|
|
8
|
+
description = "Client for Vanishly: end-to-end encrypted one-time secrets, the whole API and a command line tool"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "GPL-3.0-or-later"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = ["cryptography>=42"]
|
|
13
|
+
keywords = ["secrets", "one-time", "end-to-end encryption", "vanishly"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Topic :: Security :: Cryptography",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://github.com/DennisPohlmann/vanishly"
|
|
22
|
+
Documentation = "https://github.com/DennisPohlmann/vanishly/blob/main/docs/CLIENTS.md"
|
|
23
|
+
|
|
24
|
+
[project.scripts]
|
|
25
|
+
vanishly = "vanishly.cli:main"
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.packages.find]
|
|
28
|
+
where = ["src"]
|
vanishly-4.0.0/setup.cfg
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Vanishly client: end-to-end encrypted one-time secrets (crypto format v1)
|
|
2
|
+
and the whole Vanishly API (/api/v1)."""
|
|
3
|
+
|
|
4
|
+
__version__ = "4.0.0"
|
|
5
|
+
|
|
6
|
+
from .client import ApiError, Client, parse_link # noqa: E402
|
|
7
|
+
from .crypto import DecryptError, decrypt_secret, encrypt_secret, unlock_key, verifier_for # noqa: E402
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"ApiError", "Client", "DecryptError", "parse_link",
|
|
11
|
+
"decrypt_secret", "encrypt_secret", "unlock_key", "verifier_for",
|
|
12
|
+
]
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""vanishly - command line client. End-to-end encrypted by default: the
|
|
2
|
+
secret and the key never reach the server. Same commands as the vanishly
|
|
3
|
+
binary of the Go client."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import getpass
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .client import ApiError, Client, parse_link
|
|
16
|
+
from .crypto import DecryptError
|
|
17
|
+
|
|
18
|
+
_RECEIPT = re.compile(r"^(https?://[^#]+?)/r/([A-Za-z0-9_-]{22})(?:#.*)?$")
|
|
19
|
+
_SECRET = re.compile(r"^(https?://[^#]+?)/s/([A-Za-z0-9_-]{22})(?:#.*)?$")
|
|
20
|
+
|
|
21
|
+
HELP = """examples:
|
|
22
|
+
vanishly share 's3cret' --url https://ots.example.com --ttl 3600 --views 1
|
|
23
|
+
vanishly share --url https://ots.example.com --secret-file secret.txt --ask
|
|
24
|
+
vanishly open 'https://ots.example.com/s/<id>#<key>' --ask
|
|
25
|
+
export VANISHLY_URL=https://ots.example.com
|
|
26
|
+
vanishly share --ttl 3600 --views 1 # asks for the secret
|
|
27
|
+
vanishly share --ttl 3600 < secret.txt
|
|
28
|
+
vanishly status 'https://ots.example.com/r/<receipt id>'
|
|
29
|
+
vanishly api GET /v1/me/secrets --query limit=10
|
|
30
|
+
|
|
31
|
+
environment: VANISHLY_URL, VANISHLY_TOKEN, VANISHLY_SECRET, VANISHLY_PASSPHRASE"""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _parser() -> argparse.ArgumentParser:
|
|
35
|
+
p = argparse.ArgumentParser(prog="vanishly", usage="vanishly <command> [arguments] [flags]",
|
|
36
|
+
description="Vanishly client: one-time secrets, end-to-end encrypted.",
|
|
37
|
+
epilog=HELP, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
38
|
+
|
|
39
|
+
def global_flags(gp, default):
|
|
40
|
+
# default: the real defaults before the command; SUPPRESS after it, so a flag
|
|
41
|
+
# given before the command is kept when the command does not repeat it.
|
|
42
|
+
d = (lambda v: v) if default else (lambda v: argparse.SUPPRESS)
|
|
43
|
+
gp.add_argument("--url", default=d(os.environ.get("VANISHLY_URL")), help="server, e.g. https://ots.example.com (VANISHLY_URL)")
|
|
44
|
+
gp.add_argument("--token", default=d(os.environ.get("VANISHLY_TOKEN")), help="API token vnly_... (VANISHLY_TOKEN)")
|
|
45
|
+
gp.add_argument("--json", action="store_true", default=d(False), help="print the whole answer as JSON")
|
|
46
|
+
gp.add_argument("--run-id", default=d(None), help="X-Run-Id for the audit log")
|
|
47
|
+
gp.add_argument("--audit-comment", default=d(None), help="X-Audit-Comment for the audit log")
|
|
48
|
+
gp.add_argument("--on-behalf-of", default=d(None), help="X-On-Behalf-Of for the audit log")
|
|
49
|
+
|
|
50
|
+
global_flags(p, True)
|
|
51
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
52
|
+
global_flags(common.add_argument_group("global flags"), False)
|
|
53
|
+
p.add_argument("--version", action="version", version=f"vanishly {__version__} (python)")
|
|
54
|
+
subs = p.add_subparsers(dest="cmd", required=True)
|
|
55
|
+
|
|
56
|
+
class _Sub:
|
|
57
|
+
# Every command takes the global flags after it too.
|
|
58
|
+
def add_parser(self, name, **kw):
|
|
59
|
+
return subs.add_parser(name, parents=[common], **kw)
|
|
60
|
+
|
|
61
|
+
sub = _Sub()
|
|
62
|
+
|
|
63
|
+
def passphrase(sp):
|
|
64
|
+
g = sp.add_mutually_exclusive_group()
|
|
65
|
+
g.add_argument("--passphrase", help="the passphrase (visible in the process list: prefer --ask or VANISHLY_PASSPHRASE)")
|
|
66
|
+
g.add_argument("--passphrase-file", help="read the passphrase from this file")
|
|
67
|
+
g.add_argument("--ask", action="store_true", help="ask for the passphrase")
|
|
68
|
+
|
|
69
|
+
s = sub.add_parser("share", help="encrypt here and store a secret; prints the link")
|
|
70
|
+
s.add_argument("secret", nargs="?", default=None, help="the secret (visible in the shell history); without it: --secret-file, VANISHLY_SECRET, else asked for on a terminal (no echo), else standard input; -: typed in or standard input")
|
|
71
|
+
s.add_argument("--secret-file", help="read the secret from this file (without the line ending at the end)")
|
|
72
|
+
passphrase(s)
|
|
73
|
+
s.add_argument("--ttl", type=int, help="seconds until it expires")
|
|
74
|
+
s.add_argument("--views", type=int, help="how often it can be opened")
|
|
75
|
+
s.add_argument("--recipient", action="append", help="who may open it (sign-in), repeatable")
|
|
76
|
+
s.add_argument("--recipient-group", action="append", help="group that may open it, repeatable")
|
|
77
|
+
s.add_argument("--responsible", action="append", help="responsible person, repeatable")
|
|
78
|
+
s.add_argument("--responsible-group", action="append", help="responsible group, repeatable")
|
|
79
|
+
s.add_argument("--comment", help="what the secret is for (AUDIT_COMMENT)")
|
|
80
|
+
s.add_argument("--confirm", action="store_true", help='send "confirmed": true (CONFIRM_CHECKBOX)')
|
|
81
|
+
s.add_argument("--server-side", action="store_true", help="let the server encrypt (POST /v1/share, ENABLE_SERVER_CREATE_API)")
|
|
82
|
+
|
|
83
|
+
o = sub.add_parser("open", help="open a link: takes one view, decrypts here")
|
|
84
|
+
o.add_argument("link")
|
|
85
|
+
passphrase(o)
|
|
86
|
+
o.add_argument("--server-side", action="store_true", help="let the server decrypt (POST /v1/open, ENABLE_SERVER_OPEN_API)")
|
|
87
|
+
|
|
88
|
+
for name, text in (("meta", "state of a secret without using a view"), ("status", "status of a secret for its sender"),
|
|
89
|
+
("burn", "destroy a secret now")):
|
|
90
|
+
c = sub.add_parser(name, help=text)
|
|
91
|
+
c.add_argument("ref", help="the link (secret link for meta, status link for status and burn) or the id")
|
|
92
|
+
|
|
93
|
+
for name, text in (("config", "limits and options of the server"), ("me", "who is signed in"),
|
|
94
|
+
("downloads", "the clients the server offers, with checksums")):
|
|
95
|
+
sub.add_parser(name, help=text)
|
|
96
|
+
|
|
97
|
+
a = sub.add_parser("api", help="any API call, e.g. api GET /v1/tokens")
|
|
98
|
+
a.add_argument("method")
|
|
99
|
+
a.add_argument("path", help="below /api, e.g. /v1/admin/audit")
|
|
100
|
+
a.add_argument("--data", help="JSON body; @file reads it from a file, - from standard input")
|
|
101
|
+
a.add_argument("--query", action="append", default=[], help="key=value, repeatable")
|
|
102
|
+
sub.add_parser("help", help="show this help")
|
|
103
|
+
sub.add_parser("version", help="print the version")
|
|
104
|
+
return p
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _read_passphrase(args) -> str:
|
|
108
|
+
if getattr(args, "passphrase", None):
|
|
109
|
+
return args.passphrase
|
|
110
|
+
if getattr(args, "passphrase_file", None):
|
|
111
|
+
with open(args.passphrase_file, encoding="utf-8") as f:
|
|
112
|
+
return f.read().rstrip("\r\n")
|
|
113
|
+
if getattr(args, "ask", False):
|
|
114
|
+
return getpass.getpass("Passphrase: ")
|
|
115
|
+
return os.environ.get("VANISHLY_PASSPHRASE", "")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _base_and_id(ref: str, pattern: re.Pattern, url: str | None):
|
|
119
|
+
m = pattern.match(ref.strip())
|
|
120
|
+
if m:
|
|
121
|
+
return m.group(1), m.group(2)
|
|
122
|
+
if re.match(r"^[A-Za-z0-9_-]{22}$", ref):
|
|
123
|
+
if not url:
|
|
124
|
+
raise ValueError("an id needs --url (or VANISHLY_URL)")
|
|
125
|
+
return url, ref
|
|
126
|
+
raise ValueError(f"not a link or id: {ref}")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _out(args, data, text=None):
|
|
130
|
+
if args.json or text is None:
|
|
131
|
+
print(json.dumps(data, indent=2, ensure_ascii=False) if not isinstance(data, str) else data)
|
|
132
|
+
else:
|
|
133
|
+
print(text)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def run(argv=None) -> int:
|
|
137
|
+
parser = _parser()
|
|
138
|
+
args = parser.parse_args(argv)
|
|
139
|
+
# Like the Go binary: "vanishly help" and "vanishly version".
|
|
140
|
+
if args.cmd == "help":
|
|
141
|
+
parser.print_help()
|
|
142
|
+
return 0
|
|
143
|
+
if args.cmd == "version":
|
|
144
|
+
print(f"vanishly {__version__} (python)")
|
|
145
|
+
return 0
|
|
146
|
+
client = None
|
|
147
|
+
try:
|
|
148
|
+
def make(url):
|
|
149
|
+
nonlocal client
|
|
150
|
+
if not url:
|
|
151
|
+
raise ValueError("no server: use --url or VANISHLY_URL")
|
|
152
|
+
client = Client(url, args.token, run_id=args.run_id, comment=args.audit_comment, on_behalf_of=args.on_behalf_of)
|
|
153
|
+
return client
|
|
154
|
+
|
|
155
|
+
if args.cmd == "share":
|
|
156
|
+
# The argument, --secret-file, VANISHLY_SECRET, else typed in or standard input.
|
|
157
|
+
if args.secret is not None and args.secret_file:
|
|
158
|
+
raise ValueError("give the secret or --secret-file, not both")
|
|
159
|
+
if args.secret not in (None, "-"):
|
|
160
|
+
secret = args.secret
|
|
161
|
+
elif args.secret is None and args.secret_file:
|
|
162
|
+
# Like --passphrase-file: without the line ending at the end.
|
|
163
|
+
with open(args.secret_file, encoding="utf-8", newline="") as f:
|
|
164
|
+
secret = f.read().rstrip("\r\n")
|
|
165
|
+
elif args.secret is None and os.environ.get("VANISHLY_SECRET"):
|
|
166
|
+
secret = os.environ["VANISHLY_SECRET"]
|
|
167
|
+
else:
|
|
168
|
+
# Typed in on a terminal: no echo, not in the shell history.
|
|
169
|
+
secret = getpass.getpass("Secret: ") if sys.stdin.isatty() else sys.stdin.read()
|
|
170
|
+
if not secret:
|
|
171
|
+
raise ValueError("the secret is empty")
|
|
172
|
+
opts = {"ttl": args.ttl, "views": args.views, "recipients": args.recipient,
|
|
173
|
+
"recipientGroups": args.recipient_group, "responsible": args.responsible,
|
|
174
|
+
"responsibleGroups": args.responsible_group, "comment": args.comment,
|
|
175
|
+
"confirmed": True if args.confirm else None}
|
|
176
|
+
c = make(args.url)
|
|
177
|
+
pw = _read_passphrase(args)
|
|
178
|
+
res = c.share(secret, pw, **opts) if args.server_side else c.create(secret, pw, **opts)
|
|
179
|
+
_out(args, res, res["shareUrl"])
|
|
180
|
+
if not args.json and res.get("receiptUrl"):
|
|
181
|
+
print(f"status: {res['receiptUrl']}", file=sys.stderr)
|
|
182
|
+
elif args.cmd == "open":
|
|
183
|
+
base, _sid, _key = parse_link(args.link)
|
|
184
|
+
c = make(base)
|
|
185
|
+
pw = _read_passphrase(args)
|
|
186
|
+
res = c.open_on_server(args.link, pw) if args.server_side else c.open(args.link, pw)
|
|
187
|
+
_out(args, res, res["secret"])
|
|
188
|
+
elif args.cmd == "meta":
|
|
189
|
+
base, sid = _base_and_id(args.ref, _SECRET, args.url)
|
|
190
|
+
_out(args, make(base).secret_meta(sid))
|
|
191
|
+
elif args.cmd in ("status", "burn"):
|
|
192
|
+
base, rid = _base_and_id(args.ref, _RECEIPT, args.url)
|
|
193
|
+
c = make(base)
|
|
194
|
+
_out(args, c.receipt(rid) if args.cmd == "status" else c.burn(rid))
|
|
195
|
+
elif args.cmd in ("config", "me", "downloads"):
|
|
196
|
+
_out(args, getattr(make(args.url), args.cmd)())
|
|
197
|
+
elif args.cmd == "api":
|
|
198
|
+
body = None
|
|
199
|
+
if args.data:
|
|
200
|
+
raw = sys.stdin.read() if args.data == "-" else open(args.data[1:], encoding="utf-8").read() if args.data.startswith("@") else args.data
|
|
201
|
+
body = json.loads(raw)
|
|
202
|
+
query = dict(q.split("=", 1) for q in args.query)
|
|
203
|
+
res = make(args.url).request(args.method, args.path if args.path.startswith("/") else f"/{args.path}", body, query, raw=True)
|
|
204
|
+
print(res)
|
|
205
|
+
return 0
|
|
206
|
+
except ApiError as err:
|
|
207
|
+
print(f"vanishly: {err.status} {err.error}: {err.message}", file=sys.stderr)
|
|
208
|
+
if err.status == 426 and err.body.get("downloadUrl"):
|
|
209
|
+
print(f"vanishly: download a newer client: {err.body['downloadUrl']}", file=sys.stderr)
|
|
210
|
+
return 1
|
|
211
|
+
except (ValueError, DecryptError, OSError) as err:
|
|
212
|
+
print(f"vanishly: {err}", file=sys.stderr)
|
|
213
|
+
return 2 if isinstance(err, ValueError) else 1
|
|
214
|
+
finally:
|
|
215
|
+
if client and client.recommended_version:
|
|
216
|
+
print(f"vanishly: a newer client is recommended ({client.recommended_version}, this is {__version__}): "
|
|
217
|
+
f"{client.base_url}/downloads", file=sys.stderr)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def main() -> None:
|
|
221
|
+
sys.exit(run())
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
if __name__ == "__main__":
|
|
225
|
+
main()
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""HTTP client for the Vanishly API (/api/v1), standard library only."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .crypto import decrypt_secret, encrypt_secret, unlock_key, verifier_for
|
|
13
|
+
|
|
14
|
+
_LINK = re.compile(r"^(https?://[^#]+?)/s/([A-Za-z0-9_-]{22})#([A-Za-z0-9_-]{43})$")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ApiError(Exception):
|
|
18
|
+
"""An answer other than 2xx: status, error code, message and the whole body."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, status: int, error: str, message: str, body=None):
|
|
21
|
+
super().__init__(f"{status} {error}: {message}")
|
|
22
|
+
self.status = status
|
|
23
|
+
self.error = error
|
|
24
|
+
self.message = message
|
|
25
|
+
self.body = body if body is not None else {}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def parse_link(link: str):
|
|
29
|
+
"""Splits https://host/s/<id>#<key> into (base_url, id, key)."""
|
|
30
|
+
m = _LINK.match(link.strip())
|
|
31
|
+
if not m:
|
|
32
|
+
raise ValueError("not a secret link: https://.../s/<id>#<key>")
|
|
33
|
+
return m.group(1), m.group(2), m.group(3)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _seg(value: str) -> str:
|
|
37
|
+
return urllib.parse.quote(str(value), safe="")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Client:
|
|
41
|
+
"""One Vanishly server. token: a personal API token (vnly_...) or a
|
|
42
|
+
provider token. run_id, comment and on_behalf_of go into the audit log
|
|
43
|
+
(X-Run-Id, X-Audit-Comment, X-On-Behalf-Of)."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, base_url: str, token: str | None = None, *, timeout: float = 30,
|
|
46
|
+
run_id: str | None = None, comment: str | None = None, on_behalf_of: str | None = None,
|
|
47
|
+
client_name: str = "python"):
|
|
48
|
+
if not re.match(r"^https?://", base_url or ""):
|
|
49
|
+
raise ValueError("base_url must start with https:// or http://")
|
|
50
|
+
self.base_url = base_url.rstrip("/")
|
|
51
|
+
self.token = token
|
|
52
|
+
self.timeout = timeout
|
|
53
|
+
self.headers = {
|
|
54
|
+
"User-Agent": f"vanishly-python/{__version__}",
|
|
55
|
+
"Accept": "application/json",
|
|
56
|
+
# CLIENT_MIN_VERSION / CLIENT_RECOMMENDED_VERSION of the server check this.
|
|
57
|
+
"X-Vanishly-Client": f"{client_name}/{__version__}",
|
|
58
|
+
}
|
|
59
|
+
# Set when the server recommends a newer client (X-Vanishly-Client-Recommended).
|
|
60
|
+
self.recommended_version: str | None = None
|
|
61
|
+
if run_id:
|
|
62
|
+
self.headers["X-Run-Id"] = run_id
|
|
63
|
+
if comment:
|
|
64
|
+
self.headers["X-Audit-Comment"] = urllib.parse.quote(comment, safe=" ")
|
|
65
|
+
if on_behalf_of:
|
|
66
|
+
self.headers["X-On-Behalf-Of"] = on_behalf_of
|
|
67
|
+
|
|
68
|
+
# -- transport -------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
def request(self, method: str, path: str, body=None, query: dict | None = None, *, raw: bool = False):
|
|
71
|
+
"""Any API call; path is below /api, e.g. "/v1/config". Returns the
|
|
72
|
+
decoded JSON (or the text with raw=True, e.g. audit CSV)."""
|
|
73
|
+
url = f"{self.base_url}/api{path}"
|
|
74
|
+
q = {k: v for k, v in (query or {}).items() if v is not None and v != ""}
|
|
75
|
+
if q:
|
|
76
|
+
url += "?" + urllib.parse.urlencode(q)
|
|
77
|
+
headers = dict(self.headers)
|
|
78
|
+
if self.token:
|
|
79
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
80
|
+
data = None
|
|
81
|
+
if body is not None:
|
|
82
|
+
data = json.dumps(body).encode("utf-8")
|
|
83
|
+
headers["Content-Type"] = "application/json"
|
|
84
|
+
req = urllib.request.Request(url, data=data, method=method.upper(), headers=headers)
|
|
85
|
+
try:
|
|
86
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
|
87
|
+
self._note(res.headers)
|
|
88
|
+
text = res.read().decode("utf-8")
|
|
89
|
+
except urllib.error.HTTPError as err:
|
|
90
|
+
self._note(err.headers)
|
|
91
|
+
text = err.read().decode("utf-8", "replace")
|
|
92
|
+
try:
|
|
93
|
+
parsed = json.loads(text)
|
|
94
|
+
except ValueError:
|
|
95
|
+
parsed = {}
|
|
96
|
+
if not isinstance(parsed, dict):
|
|
97
|
+
parsed = {}
|
|
98
|
+
raise ApiError(err.code, parsed.get("error", "http_error"), parsed.get("message", err.reason or ""), parsed) from None
|
|
99
|
+
if raw:
|
|
100
|
+
return text
|
|
101
|
+
return json.loads(text) if text else None
|
|
102
|
+
|
|
103
|
+
def _note(self, headers):
|
|
104
|
+
rec = headers.get("X-Vanishly-Client-Recommended") if headers else None
|
|
105
|
+
if rec:
|
|
106
|
+
self.recommended_version = rec
|
|
107
|
+
|
|
108
|
+
# -- end-to-end (the key never leaves this process) --------------------
|
|
109
|
+
|
|
110
|
+
def create(self, secret: str, passphrase: str = "", **options) -> dict:
|
|
111
|
+
"""Encrypts here and stores it (POST /v1/secrets). options: ttl, views,
|
|
112
|
+
confirmed, recipients, recipientGroups, responsible, responsibleGroups,
|
|
113
|
+
comment. Returns the server's answer plus shareUrl and receiptUrl."""
|
|
114
|
+
key, payload = encrypt_secret(secret, passphrase)
|
|
115
|
+
res = self.create_secret({**payload, **_options(options)})
|
|
116
|
+
res["shareUrl"] = f"{self.base_url}{res['secretPath']}#{key}"
|
|
117
|
+
res["receiptUrl"] = f"{self.base_url}{res['receiptPath']}#{key}" if res.get("receiptPath") else None
|
|
118
|
+
return res
|
|
119
|
+
|
|
120
|
+
def open(self, link: str, passphrase: str = "") -> dict:
|
|
121
|
+
"""Opens a link here: takes one view and decrypts locally. Returns
|
|
122
|
+
{"secret", "viewsLeft"}. The link must belong to this client's server."""
|
|
123
|
+
base, sid, key = parse_link(link)
|
|
124
|
+
if base.rstrip("/") != self.base_url:
|
|
125
|
+
raise ValueError(f"the link belongs to {base}, not to {self.base_url}")
|
|
126
|
+
pk = b""
|
|
127
|
+
verifier = None
|
|
128
|
+
if passphrase:
|
|
129
|
+
# Needs salt and iterations first (ENABLE_SECRET_META_API).
|
|
130
|
+
meta = self.secret_meta(sid)
|
|
131
|
+
if meta.get("passphrase"):
|
|
132
|
+
pk = unlock_key(passphrase, meta["salt"], meta["iterations"])
|
|
133
|
+
verifier = verifier_for(pk, meta["salt"])
|
|
134
|
+
payload = self.reveal(sid, verifier)
|
|
135
|
+
return {"secret": decrypt_secret(payload, key, pk), "viewsLeft": payload.get("viewsLeft")}
|
|
136
|
+
|
|
137
|
+
# -- one method per endpoint -------------------------------------------
|
|
138
|
+
|
|
139
|
+
def index(self):
|
|
140
|
+
return self.request("GET", "/v1")
|
|
141
|
+
|
|
142
|
+
def config(self):
|
|
143
|
+
return self.request("GET", "/v1/config")
|
|
144
|
+
|
|
145
|
+
def downloads(self):
|
|
146
|
+
return self.request("GET", "/v1/downloads")
|
|
147
|
+
|
|
148
|
+
def create_secret(self, payload: dict):
|
|
149
|
+
return self.request("POST", "/v1/secrets", payload)
|
|
150
|
+
|
|
151
|
+
def share(self, secret: str, passphrase: str = "", **options):
|
|
152
|
+
"""Server-side encryption (POST /v1/share): the server sees the secret."""
|
|
153
|
+
body = {"secret": secret, **_options(options)}
|
|
154
|
+
if passphrase:
|
|
155
|
+
body["passphrase"] = passphrase
|
|
156
|
+
return self.request("POST", "/v1/share", body)
|
|
157
|
+
|
|
158
|
+
def open_on_server(self, link: str, passphrase: str = ""):
|
|
159
|
+
"""Server-side reveal (POST /v1/open): the server sees key and secret."""
|
|
160
|
+
body = {"link": link}
|
|
161
|
+
if passphrase:
|
|
162
|
+
body["passphrase"] = passphrase
|
|
163
|
+
return self.request("POST", "/v1/open", body)
|
|
164
|
+
|
|
165
|
+
def secret_meta(self, secret_id: str):
|
|
166
|
+
return self.request("GET", f"/v1/secrets/{_seg(secret_id)}")
|
|
167
|
+
|
|
168
|
+
def reveal(self, secret_id: str, verifier: str | None = None):
|
|
169
|
+
return self.request("POST", f"/v1/secrets/{_seg(secret_id)}/reveal", {"verifier": verifier} if verifier else {})
|
|
170
|
+
|
|
171
|
+
def receipt(self, receipt_id: str):
|
|
172
|
+
return self.request("GET", f"/v1/receipts/{_seg(receipt_id)}")
|
|
173
|
+
|
|
174
|
+
def burn(self, receipt_id: str):
|
|
175
|
+
return self.request("POST", f"/v1/receipts/{_seg(receipt_id)}/burn", {})
|
|
176
|
+
|
|
177
|
+
def me(self):
|
|
178
|
+
return self.request("GET", "/v1/me")
|
|
179
|
+
|
|
180
|
+
def my_secrets(self, **query):
|
|
181
|
+
return self.request("GET", "/v1/me/secrets", query=query)
|
|
182
|
+
|
|
183
|
+
def my_secret(self, ref: str):
|
|
184
|
+
return self.request("GET", f"/v1/me/secrets/{_seg(ref)}")
|
|
185
|
+
|
|
186
|
+
def burn_my_secret(self, ref: str):
|
|
187
|
+
return self.request("POST", f"/v1/me/secrets/{_seg(ref)}/burn", {})
|
|
188
|
+
|
|
189
|
+
def groups(self, q: str = ""):
|
|
190
|
+
return self.request("GET", "/v1/groups", query={"q": q})
|
|
191
|
+
|
|
192
|
+
def people(self, q: str = ""):
|
|
193
|
+
return self.request("GET", "/v1/people", query={"q": q})
|
|
194
|
+
|
|
195
|
+
def tokens(self):
|
|
196
|
+
return self.request("GET", "/v1/tokens")
|
|
197
|
+
|
|
198
|
+
def create_token(self, **body):
|
|
199
|
+
return self.request("POST", "/v1/tokens", body)
|
|
200
|
+
|
|
201
|
+
def revoke_token(self, token_id: str):
|
|
202
|
+
return self.request("POST", f"/v1/tokens/{_seg(token_id)}/revoke", {})
|
|
203
|
+
|
|
204
|
+
# admin
|
|
205
|
+
|
|
206
|
+
def admin_status(self):
|
|
207
|
+
return self.request("GET", "/v1/admin/status")
|
|
208
|
+
|
|
209
|
+
def admin_tokens(self):
|
|
210
|
+
return self.request("GET", "/v1/admin/tokens")
|
|
211
|
+
|
|
212
|
+
def admin_revoke_token(self, token_id: str):
|
|
213
|
+
return self.request("POST", f"/v1/admin/tokens/{_seg(token_id)}/revoke", {})
|
|
214
|
+
|
|
215
|
+
def audit(self, **query):
|
|
216
|
+
"""query: type, outcome, actor, recipient, runId, q, from, to, limit,
|
|
217
|
+
format (json, csv, jsonl; csv and jsonl come back as text)."""
|
|
218
|
+
fmt = query.get("format")
|
|
219
|
+
return self.request("GET", "/v1/admin/audit", query=query, raw=fmt in ("csv", "jsonl"))
|
|
220
|
+
|
|
221
|
+
def audit_verify(self):
|
|
222
|
+
return self.request("GET", "/v1/admin/audit/verify")
|
|
223
|
+
|
|
224
|
+
def token_policies(self):
|
|
225
|
+
return self.request("GET", "/v1/admin/token-policies")
|
|
226
|
+
|
|
227
|
+
def set_token_policy(self, **body):
|
|
228
|
+
return self.request("POST", "/v1/admin/token-policies", body)
|
|
229
|
+
|
|
230
|
+
def admin_secrets(self, **query):
|
|
231
|
+
return self.request("GET", "/v1/admin/secrets", query=query)
|
|
232
|
+
|
|
233
|
+
def admin_secret(self, ref: str):
|
|
234
|
+
return self.request("GET", f"/v1/admin/secrets/{_seg(ref)}")
|
|
235
|
+
|
|
236
|
+
def admin_burn(self, ref: str):
|
|
237
|
+
return self.request("POST", f"/v1/admin/secrets/{_seg(ref)}/burn", {})
|
|
238
|
+
|
|
239
|
+
def service_accounts(self):
|
|
240
|
+
return self.request("GET", "/v1/admin/service-accounts")
|
|
241
|
+
|
|
242
|
+
def create_service_account(self, **body):
|
|
243
|
+
return self.request("POST", "/v1/admin/service-accounts", body)
|
|
244
|
+
|
|
245
|
+
def change_service_account(self, name: str, **body):
|
|
246
|
+
return self.request("POST", f"/v1/admin/service-accounts/{_seg(name)}", body)
|
|
247
|
+
|
|
248
|
+
def delete_service_account(self, name: str):
|
|
249
|
+
return self.request("POST", f"/v1/admin/service-accounts/{_seg(name)}/delete", {})
|
|
250
|
+
|
|
251
|
+
def service_account_tokens(self, name: str):
|
|
252
|
+
return self.request("GET", f"/v1/admin/service-accounts/{_seg(name)}/tokens")
|
|
253
|
+
|
|
254
|
+
def issue_service_account_token(self, name: str, **body):
|
|
255
|
+
return self.request("POST", f"/v1/admin/service-accounts/{_seg(name)}/tokens", body)
|
|
256
|
+
|
|
257
|
+
def rotate_service_account_token(self, name: str, token_id: str, **body):
|
|
258
|
+
return self.request("POST", f"/v1/admin/service-accounts/{_seg(name)}/tokens/{_seg(token_id)}/rotate", body)
|
|
259
|
+
|
|
260
|
+
def users(self):
|
|
261
|
+
return self.request("GET", "/v1/admin/users")
|
|
262
|
+
|
|
263
|
+
def create_user(self, **body):
|
|
264
|
+
return self.request("POST", "/v1/admin/users", body)
|
|
265
|
+
|
|
266
|
+
def change_user(self, user: str, **body):
|
|
267
|
+
return self.request("POST", f"/v1/admin/users/{_seg(user)}", body)
|
|
268
|
+
|
|
269
|
+
def reset_user_password(self, user: str, **body):
|
|
270
|
+
return self.request("POST", f"/v1/admin/users/{_seg(user)}/password", body)
|
|
271
|
+
|
|
272
|
+
def delete_user(self, user: str):
|
|
273
|
+
return self.request("POST", f"/v1/admin/users/{_seg(user)}/delete", {})
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _options(options: dict) -> dict:
|
|
277
|
+
allowed = {"ttl", "views", "confirmed", "recipients", "recipientGroups", "responsible", "responsibleGroups", "comment"}
|
|
278
|
+
unknown = set(options) - allowed
|
|
279
|
+
if unknown:
|
|
280
|
+
raise TypeError(f"unknown option(s): {', '.join(sorted(unknown))}")
|
|
281
|
+
return {k: v for k, v in options.items() if v is not None}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Crypto format v1 of Vanishly, the same as public/js/vanishly-crypto.js.
|
|
2
|
+
|
|
3
|
+
key 32 random bytes, only ever in the URL fragment (#...).
|
|
4
|
+
pk without passphrase: empty; with one PBKDF2-SHA256(passphrase, salt, iterations, 32).
|
|
5
|
+
encKey HKDF-SHA256(ikm = key || pk, salt, info "vanishly v1 enc"), AES-256.
|
|
6
|
+
verifier HKDF-SHA256(ikm = pk, salt, info "vanishly v1 auth", 32); the server
|
|
7
|
+
stores only SHA-256(verifier).
|
|
8
|
+
ciphertext AES-256-GCM(encKey, iv 12 bytes, aad "vanishly v1") with the 16-byte tag.
|
|
9
|
+
|
|
10
|
+
All binary values are base64url without padding.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import base64
|
|
16
|
+
import hashlib
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
|
|
20
|
+
from cryptography.hazmat.primitives import hashes
|
|
21
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
22
|
+
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
|
23
|
+
|
|
24
|
+
VERSION = 1
|
|
25
|
+
PBKDF2_ITERATIONS = 600000
|
|
26
|
+
AAD = b"vanishly v1"
|
|
27
|
+
_B64URL = re.compile(r"^[A-Za-z0-9_-]*$")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class DecryptError(Exception):
|
|
31
|
+
"""The key, the passphrase or the ciphertext is wrong."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def to_b64url(data: bytes) -> str:
|
|
35
|
+
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def from_b64url(text: str) -> bytes:
|
|
39
|
+
if not isinstance(text, str) or not _B64URL.match(text) or len(text) % 4 == 1:
|
|
40
|
+
raise ValueError("invalid base64url")
|
|
41
|
+
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _hkdf(ikm: bytes, salt: bytes, info: bytes) -> bytes:
|
|
45
|
+
return HKDF(algorithm=hashes.SHA256(), length=32, salt=salt, info=info).derive(ikm)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def unlock_key(passphrase: str, salt: str, iterations: int) -> bytes:
|
|
49
|
+
"""Stretches a passphrase once (pk); salt is the base64url value of the secret."""
|
|
50
|
+
return hashlib.pbkdf2_hmac("sha256", passphrase.encode("utf-8"), from_b64url(salt), iterations, 32)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def verifier_for(pk: bytes, salt: str) -> str:
|
|
54
|
+
"""The verifier the reveal API checks for a passphrase-protected secret."""
|
|
55
|
+
return to_b64url(_hkdf(pk, from_b64url(salt), b"vanishly v1 auth"))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def encrypt_secret(plaintext: str, passphrase: str = "", *, iterations: int = PBKDF2_ITERATIONS,
|
|
59
|
+
_key: bytes | None = None, _salt: bytes | None = None, _iv: bytes | None = None):
|
|
60
|
+
"""Encrypts a secret. Returns (key, payload): the key goes into the URL
|
|
61
|
+
fragment, the payload to POST /api/v1/secrets. The _key/_salt/_iv
|
|
62
|
+
arguments are only for test vectors."""
|
|
63
|
+
key = _key or os.urandom(32)
|
|
64
|
+
salt = _salt or os.urandom(16)
|
|
65
|
+
iv = _iv or os.urandom(12)
|
|
66
|
+
if len(key) != 32 or len(salt) != 16 or len(iv) != 12:
|
|
67
|
+
raise ValueError("key, salt or iv has the wrong length")
|
|
68
|
+
pk = hashlib.pbkdf2_hmac("sha256", passphrase.encode("utf-8"), salt, iterations, 32) if passphrase else b""
|
|
69
|
+
enc_key = _hkdf(key + pk, salt, b"vanishly v1 enc")
|
|
70
|
+
ct = AESGCM(enc_key).encrypt(iv, plaintext.encode("utf-8"), AAD)
|
|
71
|
+
payload = {
|
|
72
|
+
"v": VERSION,
|
|
73
|
+
"ciphertext": to_b64url(ct),
|
|
74
|
+
"iv": to_b64url(iv),
|
|
75
|
+
"salt": to_b64url(salt),
|
|
76
|
+
"iterations": iterations,
|
|
77
|
+
}
|
|
78
|
+
if pk:
|
|
79
|
+
payload["verifier"] = to_b64url(_hkdf(pk, salt, b"vanishly v1 auth"))
|
|
80
|
+
return to_b64url(key), payload
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def decrypt_secret(payload: dict, key: str, pk: bytes = b"") -> str:
|
|
84
|
+
"""Decrypts what the reveal API returned; pk from unlock_key for a passphrase."""
|
|
85
|
+
try:
|
|
86
|
+
raw_key = from_b64url(key)
|
|
87
|
+
if len(raw_key) != 32:
|
|
88
|
+
raise ValueError("the key must be 32 bytes")
|
|
89
|
+
salt = from_b64url(payload["salt"])
|
|
90
|
+
enc_key = _hkdf(raw_key + pk, salt, b"vanishly v1 enc")
|
|
91
|
+
pt = AESGCM(enc_key).decrypt(from_b64url(payload["iv"]), from_b64url(payload["ciphertext"]), AAD)
|
|
92
|
+
return pt.decode("utf-8")
|
|
93
|
+
except Exception as exc: # InvalidTag, bad base64, bad UTF-8
|
|
94
|
+
raise DecryptError("cannot decrypt: wrong key or passphrase, or damaged data") from exc
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vanishly
|
|
3
|
+
Version: 4.0.0
|
|
4
|
+
Summary: Client for Vanishly: end-to-end encrypted one-time secrets, the whole API and a command line tool
|
|
5
|
+
License-Expression: GPL-3.0-or-later
|
|
6
|
+
Project-URL: Homepage, https://github.com/DennisPohlmann/vanishly
|
|
7
|
+
Project-URL: Documentation, https://github.com/DennisPohlmann/vanishly/blob/main/docs/CLIENTS.md
|
|
8
|
+
Keywords: secrets,one-time,end-to-end encryption,vanishly
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Topic :: Security :: Cryptography
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
Requires-Dist: cryptography>=42
|
|
15
|
+
|
|
16
|
+
# vanishly (Python)
|
|
17
|
+
|
|
18
|
+
Client for [Vanishly](https://github.com/DennisPohlmann/vanishly), one-time
|
|
19
|
+
secrets: the whole API as a library and the command line tool `vanishly`.
|
|
20
|
+
|
|
21
|
+
Full documentation: [docs/CLIENTS.md](https://github.com/DennisPohlmann/vanishly/blob/main/docs/CLIENTS.md). End-to-end encrypted (crypto format v1, the same as the web pages): the secret, the key and the passphrase never reach the server; the key is only in the link's `#` part.
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install vanishly
|
|
25
|
+
vanishly share 's3cret' --url https://ots.example.com --ttl 3600
|
|
26
|
+
vanishly share --url https://ots.example.com --ttl 3600 # asks for the secret, prints the link
|
|
27
|
+
vanishly open 'https://ots.example.com/s/<id>#<key>'
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from vanishly import Client
|
|
32
|
+
|
|
33
|
+
c = Client("https://ots.example.com", token=None) # token: vnly_... with sign-in
|
|
34
|
+
res = c.create("s3cret", passphrase="", ttl=3600, views=1)
|
|
35
|
+
print(res["shareUrl"], res["receiptUrl"])
|
|
36
|
+
print(c.open(res["shareUrl"])["secret"])
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Every endpoint has a method (`c.receipt(id)`, `c.burn(id)`, `c.me()`,
|
|
40
|
+
`c.tokens()`, `c.audit()`, ...); `c.request(method, path, body)` calls any
|
|
41
|
+
other. Errors raise `vanishly.ApiError` (`status`, `error`, `message`).
|
|
42
|
+
Needs Python 3.9+ and `cryptography`.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/vanishly/__init__.py
|
|
4
|
+
src/vanishly/cli.py
|
|
5
|
+
src/vanishly/client.py
|
|
6
|
+
src/vanishly/crypto.py
|
|
7
|
+
src/vanishly.egg-info/PKG-INFO
|
|
8
|
+
src/vanishly.egg-info/SOURCES.txt
|
|
9
|
+
src/vanishly.egg-info/dependency_links.txt
|
|
10
|
+
src/vanishly.egg-info/entry_points.txt
|
|
11
|
+
src/vanishly.egg-info/requires.txt
|
|
12
|
+
src/vanishly.egg-info/top_level.txt
|
|
13
|
+
tests/test_cli.py
|
|
14
|
+
tests/test_vectors.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cryptography>=42
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
vanishly
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import unittest
|
|
3
|
+
from unittest import mock
|
|
4
|
+
|
|
5
|
+
from vanishly.cli import _parser
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class GlobalFlags(unittest.TestCase):
|
|
9
|
+
def test_before_and_after_the_command(self):
|
|
10
|
+
with mock.patch.dict(os.environ, {"VANISHLY_URL": "", "VANISHLY_TOKEN": ""}):
|
|
11
|
+
p = _parser()
|
|
12
|
+
self.assertEqual(p.parse_args(["--url", "U", "config"]).url, "U")
|
|
13
|
+
self.assertEqual(p.parse_args(["config", "--url", "U"]).url, "U")
|
|
14
|
+
n = p.parse_args(["share", "s3cret", "--url", "U", "--token", "T", "--json", "--ttl", "60"])
|
|
15
|
+
self.assertEqual((n.secret, n.url, n.token, n.json, n.ttl), ("s3cret", "U", "T", True, 60))
|
|
16
|
+
|
|
17
|
+
def test_environment_stays_when_not_given(self):
|
|
18
|
+
with mock.patch.dict(os.environ, {"VANISHLY_URL": "E"}):
|
|
19
|
+
self.assertEqual(_parser().parse_args(["me"]).url, "E")
|
|
20
|
+
|
|
21
|
+
def test_help_and_version_commands(self):
|
|
22
|
+
import contextlib, io
|
|
23
|
+
from vanishly.cli import run
|
|
24
|
+
for cmd, text in (("help", "usage: vanishly <command>"), ("version", "(python)")):
|
|
25
|
+
out = io.StringIO()
|
|
26
|
+
with contextlib.redirect_stdout(out):
|
|
27
|
+
self.assertEqual(run([cmd]), 0)
|
|
28
|
+
self.assertIn(text, out.getvalue())
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
if __name__ == "__main__":
|
|
32
|
+
unittest.main()
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import pathlib
|
|
3
|
+
import unittest
|
|
4
|
+
|
|
5
|
+
from vanishly import DecryptError, decrypt_secret, encrypt_secret, unlock_key, verifier_for
|
|
6
|
+
from vanishly.client import parse_link
|
|
7
|
+
from vanishly.crypto import from_b64url, to_b64url
|
|
8
|
+
|
|
9
|
+
VECTORS = json.loads((pathlib.Path(__file__).resolve().parents[2] / "testvectors.json").read_text("utf-8"))["vectors"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Vectors(unittest.TestCase):
|
|
13
|
+
def test_encrypt_matches_javascript(self):
|
|
14
|
+
for v in VECTORS:
|
|
15
|
+
with self.subTest(v["name"]):
|
|
16
|
+
key, payload = encrypt_secret(v["plaintext"], v["passphrase"], iterations=v["iterations"],
|
|
17
|
+
_key=from_b64url(v["key"]), _salt=from_b64url(v["salt"]), _iv=from_b64url(v["iv"]))
|
|
18
|
+
self.assertEqual(key, v["key"])
|
|
19
|
+
self.assertEqual(payload["ciphertext"], v["ciphertext"])
|
|
20
|
+
self.assertEqual(payload.get("verifier"), v["verifier"])
|
|
21
|
+
|
|
22
|
+
def test_decrypt_javascript_vectors(self):
|
|
23
|
+
for v in VECTORS:
|
|
24
|
+
with self.subTest(v["name"]):
|
|
25
|
+
pk = unlock_key(v["passphrase"], v["salt"], v["iterations"]) if v["passphrase"] else b""
|
|
26
|
+
if v["passphrase"]:
|
|
27
|
+
self.assertEqual(verifier_for(pk, v["salt"]), v["verifier"])
|
|
28
|
+
self.assertEqual(decrypt_secret(v, v["key"], pk), v["plaintext"])
|
|
29
|
+
|
|
30
|
+
def test_wrong_key_or_passphrase_or_tampering(self):
|
|
31
|
+
v = next(x for x in VECTORS if x["passphrase"])
|
|
32
|
+
pk = unlock_key(v["passphrase"], v["salt"], v["iterations"])
|
|
33
|
+
with self.assertRaises(DecryptError):
|
|
34
|
+
decrypt_secret(v, v["key"]) # passphrase missing
|
|
35
|
+
with self.assertRaises(DecryptError):
|
|
36
|
+
decrypt_secret(v, "A" * 43, pk)
|
|
37
|
+
ct = bytearray(from_b64url(v["ciphertext"]))
|
|
38
|
+
ct[0] ^= 1
|
|
39
|
+
with self.assertRaises(DecryptError):
|
|
40
|
+
decrypt_secret({**v, "ciphertext": to_b64url(bytes(ct))}, v["key"], pk)
|
|
41
|
+
|
|
42
|
+
def test_round_trip_random(self):
|
|
43
|
+
key, payload = encrypt_secret("hällo 🔐", "pw")
|
|
44
|
+
self.assertEqual(len(key), 43)
|
|
45
|
+
self.assertEqual(payload["iterations"], 600000)
|
|
46
|
+
pk = unlock_key("pw", payload["salt"], payload["iterations"])
|
|
47
|
+
self.assertEqual(decrypt_secret(payload, key, pk), "hällo 🔐")
|
|
48
|
+
|
|
49
|
+
def test_parse_link(self):
|
|
50
|
+
sid, key = "A" * 22, "b" * 43
|
|
51
|
+
self.assertEqual(parse_link(f"https://x.example/s/{sid}#{key}"), ("https://x.example", sid, key))
|
|
52
|
+
self.assertEqual(parse_link(f"https://x.example/ots/s/{sid}#{key}")[0], "https://x.example/ots")
|
|
53
|
+
for bad in ("https://x.example/s/short#key", f"ftp://x/s/{sid}#{key}", f"https://x/s/{sid}"):
|
|
54
|
+
with self.assertRaises(ValueError):
|
|
55
|
+
parse_link(bad)
|
|
56
|
+
|
|
57
|
+
def test_base64url(self):
|
|
58
|
+
for n in range(40):
|
|
59
|
+
self.assertEqual(from_b64url(to_b64url(bytes(range(n)))), bytes(range(n)))
|
|
60
|
+
for bad in ("a+b/", "abcde", "a=="):
|
|
61
|
+
with self.assertRaises(ValueError):
|
|
62
|
+
from_b64url(bad)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
if __name__ == "__main__":
|
|
66
|
+
unittest.main()
|