diff --git a/README.md b/README.md index 03e6d36..b280636 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,13 @@ Signals are written as int16 with a calibration that reproduces every Zarr sample exactly. The [H5 export guide](https://github.com/bdsp-core/bdsp-python/blob/main/docs/bids-zarr/H5_EXPORT.md) lists what the split format does not carry. +## The bdsp.io website API and the `bdsp` command + +The package also includes a client for the bdsp.io API (`bdsp.web`) and the `bdsp` command: `bdsp login` +(with a personal token from Settings → API on bdsp.io), `bdsp ls` (the releases you can read), `bdsp files`, +`bdsp where` (where a release's data are, with an `aws s3 ls` line for S3) and `bdsp get`. It uses only Python's +standard library. See [docs/bdsp-io-client.md](docs/bdsp-io-client.md). + ## Further help The [getting started guide](https://github.com/bdsp-core/bdsp-python/blob/main/docs/README.md) covers signals, annotations, features, diff --git a/docs/bdsp-io-client.md b/docs/bdsp-io-client.md new file mode 100644 index 0000000..695816a --- /dev/null +++ b/docs/bdsp-io-client.md @@ -0,0 +1,39 @@ +# The bdsp.io API client and the `bdsp` command + +For the bdsp.io API v2 (3.2). It uses only Python's standard library (3.9 or later). + +## Start + +1. On bdsp.io, open **Settings → API** and create a token. It's shown once. +2. `pip install bdsp` (this package), then `bdsp login` and paste the token. It's checked, then saved in + `~/.config/bdsp/token`, readable by you only. Or set `BDSP_TOKEN`. + +## Commands + +| Command | What it does | +|---|---| +| `bdsp me` | your account: credentialed or not, signed agreements, the token's expiry | +| `bdsp ls` | releases you can read (`--all` for every release, with access; `--modality EEG`, `-q title`) | +| `bdsp files SLUG VERSION [PATH]` | one folder of a release you can read | +| `bdsp where SLUG VERSION` | where its data are: S3 for your account (with an `aws s3 ls` line), GitHub, the website | +| `bdsp get SLUG VERSION PATH [-o OUT] [-r]` | download a file, or a folder with `-r`, from the website's copy | + +Large datasets live in S3, not on the website. Use `bdsp where` and the AWS CLI for those, after setting up cloud +access (Settings → Cloud). + +The API allows 120 requests a minute per account. The tool waits when it's told to slow down. `get -r` makes one +request per file, so a folder of thousands of small files takes a while. + +## In Python + +```python +from bdsp.web import Client +client = Client() +for release in client.releases(accessible=True): + print(release['slug'], release['version'], release['title']) +print(client.location('hsp', '3.0')) +``` + +## Tests + +`PYTHONPATH=src python -m unittest discover -s tests`. They run against a small fake of the API, with no network. diff --git a/pyproject.toml b/pyproject.toml index 9ec1bc6..fb2678e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,8 +4,8 @@ build-backend = "hatchling.build" [project] name = "bdsp" -version = "0.5.0" -description = "Python reader for standardized BDSP sleep/PSG Zarr recordings, with a local H5 writer." +version = "0.6.0" +description = "Python reader for standardized BDSP sleep/PSG Zarr recordings, with a local H5 writer, and the bdsp.io API client and command-line tool." readme = "README.md" requires-python = ">=3.11" license = "Apache-2.0" @@ -43,6 +43,8 @@ validation = [ [project.scripts] bdsp-zarr-to-h5 = "bdsp.zarr_to_h5:main" +# the bdsp.io website API client (bdsp.web): bdsp login / me / ls / files / where / get +bdsp = "bdsp.web.cli:main" [project.urls] Homepage = "https://bdsp.io/" diff --git a/src/bdsp/__init__.py b/src/bdsp/__init__.py index 84593b9..276ff0f 100644 --- a/src/bdsp/__init__.py +++ b/src/bdsp/__init__.py @@ -16,4 +16,4 @@ "read_h5", ] -__version__ = "0.5.0" +__version__ = "0.6.0" diff --git a/src/bdsp/web/__init__.py b/src/bdsp/web/__init__.py new file mode 100644 index 0000000..09ff6ee --- /dev/null +++ b/src/bdsp/web/__init__.py @@ -0,0 +1,7 @@ +"""Client for the bdsp.io website API (v2): what you can read, its files, and where its data are. + +Standard library only. The `bdsp` command (bdsp.web.cli) wraps it. See docs/bdsp-io-client.md. +""" +from bdsp.web.client import ApiError, Client + +__all__ = ['ApiError', 'Client'] diff --git a/src/bdsp/web/cli.py b/src/bdsp/web/cli.py new file mode 100644 index 0000000..d3a980f --- /dev/null +++ b/src/bdsp/web/cli.py @@ -0,0 +1,167 @@ +"""bdsp: the bdsp.io command-line tool. + + bdsp login store your API token (from bdsp.io, Settings → API) + bdsp me your account and signed agreements + bdsp ls [--all] [--modality EEG] releases you can read (--all: every release, with access) + bdsp files SLUG VERSION [PATH] a folder of a release you can read + bdsp where SLUG VERSION where its data are (S3 locations for your account, GitHub, the website) + bdsp get SLUG VERSION PATH [-o OUT] [-r] + download a file, or a folder with -r (from the website's copy) +""" +import argparse +import getpass +import os +import sys + +from bdsp.web.client import ApiError, Client, redirects_elsewhere, save_token + + +def _print_table(rows, columns): + widths = [max([len(str(c))] + [len(str(r.get(c, ''))) for r in rows]) for c in columns] + print(' '.join(c.upper().ljust(w) for c, w in zip(columns, widths))) + for row in rows: + print(' '.join(str(row.get(c, '')).ljust(w) for c, w in zip(columns, widths))) + + +def _components(api_path): + """An API path ('a/b/c.edf') as its names. Refuses anything that could point outside the target folder: empty + names, '.', '..', a leading '/', and backslashes or ':' (a separator or a drive on Windows).""" + parts = api_path.split('/') + if not api_path or any(p in ('', '.', '..') or '\\' in p or ':' in p or '\x00' in p for p in parts): + raise ApiError(400, f'Refusing an unsafe path from the server: {api_path!r}') + return parts + + +def _safe_target(root, relative_parts): + """root/relative_parts, creating folders as needed and refusing any step that is (or becomes) a link, so an + existing link inside the target folder can't send a write elsewhere.""" + path = root + for part in relative_parts[:-1]: + path = os.path.join(path, part) + if redirects_elsewhere(path): + raise ApiError(400, f'Refusing to write through a link: {path}') + os.makedirs(path, exist_ok=True) + if redirects_elsewhere(path) or not os.path.isdir(path): + raise ApiError(400, f'Refusing to write through a link: {path}') + target = os.path.join(path, relative_parts[-1]) + if redirects_elsewhere(target): + raise ApiError(400, f'Refusing to write through a link: {target}') + return target + + +def cmd_login(args): + token = (sys.stdin.readline() if not sys.stdin.isatty() else getpass.getpass('API token: ')).strip() + if not token.startswith('bdsp_'): + raise ApiError(400, 'That does not look like a bdsp.io API token (they start with "bdsp_").') + account = Client(token=token, url=args.url).me() # check it before saving + print(f'Signed in as {account["username"]}; token saved to {save_token(token)}') + + +def cmd_me(args): + account = Client(url=args.url).me() + print(f'{account["username"]} credentialed: {"yes" if account["credentialed"] else "no"} ' + f'token expires: {account["token_expires"][:10]}') + for agreement in account['signed_agreements']: + print(f' signed: {agreement["release"]} {agreement["signed"][:10]}') + + +def cmd_ls(args): + rows = list(Client(url=args.url).releases(accessible=not args.all, latest=args.latest, q=args.q, + modality=args.modality, recording_type=args.recording_type)) + for row in rows: + row['readable'] = 'yes' if row['can_read'] else 'no' + _print_table(rows, ['slug', 'version', 'access', 'readable', 'title'] if args.all + else ['slug', 'version', 'access', 'title']) + + +def cmd_files(args): + rows = list(Client(url=args.url).files(args.slug, args.version, args.path or '')) + for row in rows: + row['size'] = '' if row['type'] == 'folder' else row.get('bytes') + _print_table(rows, ['type', 'size', 'path']) + + +def cmd_where(args): + body = Client(url=args.url).location(args.slug, args.version) + for entry in body['locations']: + print(f'{entry["platform"]}: {entry["s3_uri"]}') + if entry.get('note'): + print(f' note: {entry["note"]}') + print(f' try: aws s3 ls {entry["s3_uri"]}') + if body.get('github'): + print(f'github: {body["github"]}') + if not body['aws_account_on_file']: + print(f'No AWS account on file for you yet: {body["how_to_get_access"]}') + print(f'website files: bdsp files {args.slug} {args.version}') + + +def cmd_get(args): + client = Client(url=args.url) + if not args.recursive: + name = _components(args.path.strip('/'))[-1] + out = args.output or name + print(f'{args.path} -> {client.download(args.slug, args.version, args.path, out)}') + return + top = args.path.strip('/') + top_parts = _components(top) if top else [] + root = os.path.abspath(args.output or (top_parts[-1] if top_parts else f'{args.slug}-{args.version}')) + if redirects_elsewhere(root): + raise ApiError(400, f'Refusing to write through a link: {root}') + os.makedirs(root, exist_ok=True) + pending = [top] + while pending: + folder = pending.pop() + for entry in client.files(args.slug, args.version, folder): + parts = _components(entry['path']) + if parts[:len(top_parts)] != top_parts or len(parts) <= len(top_parts): + raise ApiError(400, f'Refusing a path outside {top or "the release"}: {entry["path"]!r}') + if entry['type'] == 'folder': + pending.append(entry['path']) + continue + target = _safe_target(root, parts[len(top_parts):]) + if os.path.isfile(target) and os.path.getsize(target) == entry.get('bytes'): + print(f'{entry["path"]}: already here') + continue + client.download(args.slug, args.version, entry['path'], target) + print(f'{entry["path"]} -> {target}') + + +def main(argv=None): + parser = argparse.ArgumentParser(prog='bdsp', description='The bdsp.io command-line tool (API v2).') + parser.add_argument('--url', help='the site (default https://bdsp.io, or BDSP_URL)') + commands = parser.add_subparsers(dest='command', required=True) + commands.add_parser('login', help='store your API token').set_defaults(run=cmd_login) + commands.add_parser('me', help='your account').set_defaults(run=cmd_me) + ls = commands.add_parser('ls', help='releases you can read') + ls.add_argument('--all', action='store_true', help='every release, with whether you can read it') + ls.add_argument('--latest', action='store_true', help='latest versions only') + ls.add_argument('-q', help='title contains') + ls.add_argument('--modality') + ls.add_argument('--recording-type', dest='recording_type') + ls.set_defaults(run=cmd_ls) + for name, run, extra in (('files', cmd_files, True), ('where', cmd_where, False)): + sub = commands.add_parser(name) + sub.add_argument('slug') + sub.add_argument('version') + if extra: + sub.add_argument('path', nargs='?', default='') + sub.set_defaults(run=run) + get = commands.add_parser('get', help='download a file, or a folder with -r') + get.add_argument('slug') + get.add_argument('version') + get.add_argument('path') + get.add_argument('-o', '--output') + get.add_argument('-r', '--recursive', action='store_true') + get.set_defaults(run=cmd_get) + args = parser.parse_args(argv) + try: + args.run(args) + except ApiError as error: + print(f'bdsp: {error.message}' + (f' (HTTP {error.status})' if error.status not in (400, 401) else ''), + file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/src/bdsp/web/client.py b/src/bdsp/web/client.py new file mode 100644 index 0000000..8832642 --- /dev/null +++ b/src/bdsp/web/client.py @@ -0,0 +1,241 @@ +"""The bdsp.io API v2, with a personal token (Settings → API on bdsp.io). Standard library only. + + from bdsp.web import Client + client = Client() # the token from BDSP_TOKEN or ~/.config/bdsp/token + for release in client.releases(accessible=True): + print(release['slug'], release['version'], release['title']) + client.download('hsp', '3.0', 'RECORDS', 'RECORDS') +""" +import email.utils +import json +import os +import shutil +import stat +import tempfile +import time +import urllib.error +import urllib.parse +import urllib.request + +DEFAULT_URL = 'https://bdsp.io' +USER_AGENT = 'bdsp-python/0.6.0 (bdsp.web)' +MAX_WAIT_SECONDS = 60 +LOCAL_HOSTS = ('localhost', '127.0.0.1', '::1') + + +def token_path(): + base = os.environ.get('XDG_CONFIG_HOME') or os.path.join(os.path.expanduser('~'), '.config') + return os.path.join(base, 'bdsp', 'token') + + +def save_token(token): + """Store the token for later runs, readable by its owner only: written to a new owner-only file beside it, + then moved into place, so an older file's permissions or a link there never matter.""" + path = token_path() + folder = os.path.dirname(path) + os.makedirs(folder, mode=0o700, exist_ok=True) + descriptor, temporary = tempfile.mkstemp(dir=folder, prefix='.token-') # created 0600, exclusively + try: + with os.fdopen(descriptor, 'w') as f: + f.write(token.strip() + '\n') + os.chmod(temporary, stat.S_IRUSR | stat.S_IWUSR) + os.replace(temporary, path) + except BaseException: + _remove_quietly(temporary) + raise + return path + + +def load_token(): + token = os.environ.get('BDSP_TOKEN', '').strip() + if token: + return token + try: + with open(token_path()) as f: + return f.read().strip() + except FileNotFoundError: + return '' + + +def redirects_elsewhere(path): + """Whether `path` is a link of any kind: a symbolic link, or on Windows a junction or other reparse point (which + os.path.islink misses on Python 3.9). A path that doesn't exist yet doesn't.""" + try: + info = os.lstat(path) + except FileNotFoundError: + return False + return stat.S_ISLNK(info.st_mode) or bool(getattr(info, 'st_file_attributes', 0) & 0x400) # REPARSE_POINT + + +def _remove_quietly(path): + try: + os.unlink(path) + except FileNotFoundError: + pass + + +class ApiError(Exception): + def __init__(self, status, message): + super().__init__(f'{status}: {message}') + self.status, self.message = status, message + + +class _NoRedirects(urllib.request.HTTPRedirectHandler): + """The API never redirects; following one would send the token to wherever it points.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise ApiError(code, f'Refusing to follow a redirect to {newurl} (it would carry your token)') + + +def _origin(url): + parts = urllib.parse.urlsplit(url) + try: + port = parts.port + except ValueError: + raise ApiError(400, f'Invalid address: {url}') from None + if port == 0: + raise ApiError(400, f'Invalid port in {url}') + return parts.scheme, parts.hostname, port if port is not None else {'https': 443, 'http': 80}.get(parts.scheme) + + +def _error_message(error): + """The server's reason: DRF's 'detail', or field errors such as {'path': ['Invalid path…']}.""" + try: + body = json.loads(error.read().decode() or 'null') + except (ValueError, UnicodeDecodeError): + return error.reason + if isinstance(body, dict): + if body.get('detail'): + return str(body['detail']) + fields = ['{}: {}'.format(k, ' '.join(map(str, v)) if isinstance(v, list) else v) for k, v in body.items()] + return '; '.join(fields) or error.reason + if isinstance(body, list): + return ' '.join(map(str, body)) or error.reason + return error.reason + + +def _retry_after(value): + """Seconds to wait from a Retry-After header: a number, or an HTTP date. None if it can't be read.""" + if not value: + return None + try: + return max(0, int(value)) + except ValueError: + pass + try: + when = email.utils.parsedate_to_datetime(value) + except (TypeError, ValueError): + return None + return max(0, int(when.timestamp() - time.time()) + 1) + + +class Client: + """One account's view of bdsp.io. Waits and retries when the server says to slow down (429, Retry-After).""" + + def __init__(self, token=None, url=None, max_retries=3): + self.token = token or load_token() + if not self.token: + raise ApiError(401, 'No token. Create one on bdsp.io (Settings → API), then run: bdsp login') + self.url = (url or os.environ.get('BDSP_URL') or DEFAULT_URL).rstrip('/') + scheme, host, _ = _origin(self.url) + if scheme != 'https' and not (scheme == 'http' and (host in LOCAL_HOSTS + or os.environ.get('BDSP_ALLOW_HTTP') == '1')): + raise ApiError(400, f'{self.url} is not HTTPS; the token would travel unencrypted ' + '(set BDSP_ALLOW_HTTP=1 only for a local test server)') + self.max_retries = max_retries + self._opener = urllib.request.build_opener(_NoRedirects) + + def _open_url(self, url): + if _origin(url) != _origin(self.url): + raise ApiError(400, f'Refusing to send the token to another site: {url}') + request = urllib.request.Request(url, headers={ + 'Authorization': f'Bearer {self.token}', 'Accept': 'application/json', 'User-Agent': USER_AGENT}) + for attempt in range(self.max_retries + 1): + try: + return self._opener.open(request, timeout=60) + except urllib.error.HTTPError as error: + with error: + if error.code == 429: + wait = _retry_after(error.headers.get('Retry-After')) + wait = 5 if wait is None else wait + if wait <= MAX_WAIT_SECONDS and attempt < self.max_retries: + time.sleep(wait) + continue + raise ApiError(429, f'Too many requests; the server asks to wait {wait} s') from None + message = _error_message(error) + raise ApiError(error.code, message) from None + + def _open(self, path, params=None): + query = urllib.parse.urlencode({k: v for k, v in (params or {}).items() if v not in (None, '')}) + return self._open_url(self.url + path + ('?' + query if query else '')) + + def _get_url(self, url): + with self._open_url(url) as response: + return json.loads(response.read().decode()) + + def _get(self, path, params=None): + with self._open(path, params) as response: + return json.loads(response.read().decode()) + + def _pages(self, path, params, key=None): + """Every item of a paginated list, following the server's own `next` link (same site only).""" + query = urllib.parse.urlencode({k: v for k, v in (params or {}).items() if v not in (None, '')}) + page_url = self.url + path + ('?' + query if query else '') + while True: + body = self._get_url(page_url) + results = body['results'] + yield from (results[key] if key else results) + if not body.get('next'): + return + page_url = urllib.parse.urljoin(page_url, body['next']) # relative to the page it came from + + @staticmethod + def _release(slug, version): + return f'/api/v2/releases/{urllib.parse.quote(slug, safe="")}/{urllib.parse.quote(version, safe="")}' + + def me(self): + """The account: name, credentialed or not, signed agreements, the token's expiry.""" + return self._get('/api/v2/me/') + + def releases(self, accessible=False, latest=False, q=None, modality=None, recording_type=None): + """Published releases, each with `can_read` for this account.""" + return self._pages('/api/v2/releases/', {'accessible': '1' if accessible else None, + 'latest': '1' if latest else None, 'q': q, 'modality': modality, + 'recording_type': recording_type, 'page_size': 500}) + + def files(self, slug, version, path=''): + """One folder of a readable release: its folders, then its files (name, path, bytes, modified).""" + return self._pages(self._release(slug, version) + '/files/', {'path': path, 'page_size': 1000}, 'entries') + + def location(self, slug, version): + """Where a readable release keeps its data: S3 locations for this account, GitHub, the website's files.""" + return self._get(self._release(slug, version) + '/location/') + + def download(self, slug, version, path, destination): + """Save one file of a readable release to `destination`. It's written to a new, randomly named file beside + it and moved into place only when every advertised byte has arrived; a link at `destination` is refused.""" + destination = os.path.abspath(destination) + if redirects_elsewhere(destination): + raise ApiError(400, f'Refusing to write through a link: {destination}') + folder = os.path.dirname(destination) + descriptor, temporary = tempfile.mkstemp(dir=folder, prefix='.bdsp-', suffix='.part') + try: + with os.fdopen(descriptor, 'wb') as out, \ + self._open(self._release(slug, version) + '/download/', {'path': path}) as response: + if response.status != 200: # a full-file request; a 206 (or anything else) is not the file + raise ApiError(502, f'Unexpected response {response.status} for {path}') + expected = response.headers.get('Content-Length') + received = 0 + while True: + chunk = response.read(1024 * 1024) + if not chunk: + break + out.write(chunk) + received += len(chunk) + if expected is not None and received != int(expected): + raise ApiError(502, f'The download of {path} stopped early ({received} of {expected} bytes)') + os.replace(temporary, destination) + except BaseException: + _remove_quietly(temporary) + raise + return destination diff --git a/tests/test_web_client.py b/tests/test_web_client.py new file mode 100644 index 0000000..f16419b --- /dev/null +++ b/tests/test_web_client.py @@ -0,0 +1,310 @@ +"""Tests for the bdsp client and CLI against a small fake of the v2 API (standard library only). + + cd clients/python && PYTHONPATH=src python -m unittest discover -s tests +""" +import io +import json +import os +import stat +import tempfile +import threading +import unittest +from contextlib import redirect_stdout, redirect_stderr +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest import mock +from urllib.parse import parse_qs, urlparse + +from bdsp.web import ApiError, Client +from bdsp.web import cli, client as client_module + +TOKEN = 'bdsp_test_token' +FILES = {'RECORDS': b'a\nb\n', 'waves/100.dat': b'x' * 3000, 'waves/deep/1.dat': b'y'} + + +class FakeApi(BaseHTTPRequestHandler): + throttled_once = False + escape = False + + def log_message(self, *args): + pass + + def reply(self, status, body, headers=()): + data = body if isinstance(body, bytes) else json.dumps(body).encode() + self.send_response(status) + for name, value in headers: + self.send_header(name, value) + self.send_header('Content-Length', str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + if self.headers.get('Authorization') != f'Bearer {TOKEN}': + return self.reply(401, {'detail': 'Invalid, expired or revoked token.'}) + url = urlparse(self.path) + query = {k: v[0] for k, v in parse_qs(url.query).items()} + page = int(query.get('page', 1)) + if url.path == '/api/v2/me/': + if not FakeApi.throttled_once: + FakeApi.throttled_once = True + return self.reply(429, {'detail': 'slow down'}, [('Retry-After', '0')]) + return self.reply(200, {'username': 'george', 'credentialed': True, 'signed_agreements': [], + 'token_expires': '2027-02-26T00:00:00+00:00'}) + if url.path == '/api/v2/releases/': + items = [{'slug': f'ds{n}', 'version': '1.0', 'title': f'Dataset {n}', 'access': 'open', + 'can_read': True} for n in range((page - 1) * 2, page * 2)] + host = self.headers.get('Host') + nxt = f'http://{host}/api/v2/releases/?page={page + 1}&page_size=2' if page < 2 else None + return self.reply(200, {'next': nxt, 'results': items}) + if url.path == '/api/v2/releases/demo/1.0/files/': + folder = query.get('path', '').strip('/') + names = sorted({p[len(folder):].lstrip('/').split('/')[0] for p in FILES + if not folder or p.startswith(folder + '/')}) + entries = [] + for name in names: + path = f'{folder}/{name}'.lstrip('/') + if path in FILES: + entries.append({'type': 'file', 'name': name, 'path': path, 'bytes': len(FILES[path])}) + else: + entries.append({'type': 'folder', 'name': name, 'path': path}) + if FakeApi.escape: + entries.append({'type': 'file', 'name': 'evil', 'path': '../../evil', 'bytes': 1}) + return self.reply(200, {'next': None, 'results': {'path': folder, 'entries': entries}}) + if url.path == '/api/v2/releases/demo/1.0/download/' and query.get('path') not in ('short', 'bad path', 'partial'): + data = FILES.get(query.get('path', '')) + return self.reply(200, data) if data is not None else self.reply(404, {'detail': 'No such file.'}) + if url.path == '/api/v2/redirect/': + return self.reply(302, b'', [('Location', 'http://example.invalid/steal')]) + if url.path == '/api/v2/releases/demo/1.0/download/' and query.get('path') == 'short': + self.close_connection = True + self.send_response(200) + self.send_header('Content-Length', '100') + self.end_headers() + self.wfile.write(b'only part') + return + if url.path == '/api/v2/releases/demo/1.0/download/' and query.get('path') == 'bad path': + return self.reply(400, {'path': ['Invalid path: names joined by "/".']}) + if url.path == '/api/v2/releases/demo/1.0/download/' and query.get('path') == 'partial': + return self.reply(206, b'four', [('Content-Range', 'bytes 0-3/100')]) + if url.path == '/api/v2/relative/': + if page == 1: + return self.reply(200, {'next': '?page=2', 'results': [{'n': 1}]}) + return self.reply(200, {'next': None, 'results': [{'n': 2}]}) + if url.path == '/api/v2/slow/': + return self.reply(429, {'detail': 'slow down'}, [('Retry-After', 'Wed, 21 Oct 2099 07:28:00 GMT')]) + if url.path == '/api/v2/releases/demo/1.0/location/': + return self.reply(200, {'locations': [{'platform': 'aws-s3', 's3_uri': 's3://arn:aws:s3:x/ap/EEG/'}], + 'github': None, 'aws_account_on_file': False, + 'how_to_get_access': 'https://bdsp.io/settings/cloud/'}) + self.reply(404, {'detail': 'Not found.'}) + + +class _FakeApiCase(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = ThreadingHTTPServer(('127.0.0.1', 0), FakeApi) + threading.Thread(target=cls.server.serve_forever, daemon=True).start() + cls.url = f'http://127.0.0.1:{cls.server.server_address[1]}' + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + + def setUp(self): + self.home = tempfile.mkdtemp() + patcher = mock.patch.dict(os.environ, {'XDG_CONFIG_HOME': self.home, 'BDSP_URL': self.url, + 'BDSP_TOKEN': TOKEN}) + patcher.start() + self.addCleanup(patcher.stop) + self.addCleanup(__import__('shutil').rmtree, self.home) + FakeApi.escape = False + FakeApi.throttled_once = False + + def run_cli(self, *argv): + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + code = cli.main(list(argv)) + return code, out.getvalue(), err.getvalue() + + +class BdspTests(_FakeApiCase): + + def test_the_token_is_sent_and_a_429_is_retried(self): + with mock.patch.object(client_module.time, 'sleep') as sleep: + self.assertEqual(Client().me()['username'], 'george') + sleep.assert_called_once_with(0) + + def test_pages_are_followed(self): + self.assertEqual([r['slug'] for r in Client().releases()], ['ds0', 'ds1', 'ds2', 'ds3']) + + def test_a_bad_token_gives_the_servers_message(self): + with self.assertRaises(ApiError) as caught: + Client(token='bdsp_wrong').releases().__next__() + self.assertEqual((caught.exception.status, caught.exception.message), + (401, 'Invalid, expired or revoked token.')) + + def test_no_token(self): + with mock.patch.dict(os.environ, {'BDSP_TOKEN': ''}): + with self.assertRaises(ApiError): + Client() + + def test_login_checks_the_token_and_stores_it_privately(self): + with mock.patch.dict(os.environ, {'BDSP_TOKEN': ''}), mock.patch('sys.stdin', io.StringIO(TOKEN + '\n')): + FakeApi.throttled_once = True + code, out, _ = self.run_cli('login') + self.assertEqual(code, 0, out) + path = client_module.token_path() + self.assertEqual(open(path).read().strip(), TOKEN) + self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o600) + with mock.patch('sys.stdin', io.StringIO('not-a-token\n')): + code, _, err = self.run_cli('login') + self.assertEqual(code, 1) + self.assertIn('bdsp_', err) + + def test_files_and_a_single_download(self): + code, out, _ = self.run_cli('files', 'demo', '1.0') + self.assertEqual(code, 0) + self.assertIn('RECORDS', out) + self.assertIn('waves', out) + target = os.path.join(self.home, 'R') + code, _, _ = self.run_cli('get', 'demo', '1.0', 'RECORDS', '-o', target) + self.assertEqual((code, open(target, 'rb').read()), (0, FILES['RECORDS'])) + self.assertFalse(os.path.exists(target + '.part')) + + def test_a_folder_downloads_recursively_and_skips_whats_already_there(self): + target = os.path.join(self.home, 'waves-copy') + code, out, _ = self.run_cli('get', 'demo', '1.0', 'waves', '-r', '-o', target) + self.assertEqual(code, 0) + self.assertEqual(open(os.path.join(target, '100.dat'), 'rb').read(), FILES['waves/100.dat']) + self.assertEqual(open(os.path.join(target, 'deep', '1.dat'), 'rb').read(), FILES['waves/deep/1.dat']) + code, out, _ = self.run_cli('get', 'demo', '1.0', 'waves', '-r', '-o', target) + self.assertIn('already here', out) + + def test_a_server_path_cant_make_it_write_elsewhere(self): + FakeApi.escape = True + target = os.path.join(self.home, 'all') + code, _, err = self.run_cli('get', 'demo', '1.0', '', '-r', '-o', target) + self.assertEqual(code, 1) + self.assertIn('Refusing an unsafe path', err) + self.assertFalse(os.path.exists(os.path.join(self.home, 'evil'))) + + def test_where(self): + code, out, _ = self.run_cli('where', 'demo', '1.0') + self.assertEqual(code, 0) + self.assertIn('aws s3 ls s3://arn:aws:s3:x/ap/EEG/', out) + self.assertIn('/settings/cloud/', out) + + def test_a_missing_file_is_a_clear_error(self): + code, _, err = self.run_cli('get', 'demo', '1.0', 'nope', '-o', os.path.join(self.home, 'n')) + self.assertEqual(code, 1) + self.assertIn('No such file.', err) + self.assertFalse(os.path.exists(os.path.join(self.home, 'n.part'))) + + +class SecurityTests(_FakeApiCase): + """Codex review of PR #79: the token never leaves the site, and downloads never write through links.""" + + def test_a_redirect_is_refused_so_the_token_stays_here(self): + with self.assertRaises(ApiError) as caught: + Client()._get('/api/v2/redirect/') + self.assertIn('Refusing to follow a redirect', caught.exception.message) + + def test_plain_http_is_refused_except_for_a_local_server(self): + with self.assertRaises(ApiError): + Client(url='http://bdsp.example.org') + Client(url='http://localhost:8000') # a local test server is fine + with mock.patch.dict(os.environ, {'BDSP_ALLOW_HTTP': '1'}): + Client(url='http://bdsp.example.org') + + def test_a_next_link_to_another_site_is_not_followed(self): + with self.assertRaises(ApiError) as caught: + Client()._get_url('https://example.invalid/api/v2/releases/?page=2') + self.assertIn('another site', caught.exception.message) + + def test_a_link_inside_the_target_folder_is_refused(self): + target = os.path.join(self.home, 'out') + elsewhere = os.path.join(self.home, 'elsewhere') + os.makedirs(target) + os.makedirs(elsewhere) + os.symlink(elsewhere, os.path.join(target, 'deep')) + code, _, err = self.run_cli('get', 'demo', '1.0', 'waves', '-r', '-o', target) + self.assertEqual(code, 1) + self.assertIn('through a link', err) + self.assertEqual(os.listdir(elsewhere), []) + + def test_a_link_at_the_destination_is_refused(self): + victim = os.path.join(self.home, 'victim') + with open(victim, 'w') as f: + f.write('keep me') + link = os.path.join(self.home, 'R') + os.symlink(victim, link) + code, _, err = self.run_cli('get', 'demo', '1.0', 'RECORDS', '-o', link) + self.assertEqual(code, 1) + self.assertEqual(open(victim).read(), 'keep me') + + def test_a_short_download_is_not_published_and_leaves_nothing(self): + target = os.path.join(self.home, 'short.dat') + with open(target, 'w') as f: + f.write('the complete old copy') + with self.assertRaises(Exception): + Client().download('demo', '1.0', 'short', target) + self.assertEqual(open(target).read(), 'the complete old copy') + self.assertEqual([n for n in os.listdir(self.home) if n.endswith('.part')], []) + + def test_replacing_a_readable_token_file_keeps_the_new_one_private(self): + path = client_module.token_path() + os.makedirs(os.path.dirname(path)) + with open(path, 'w') as f: + f.write('old') + os.chmod(path, 0o644) + client_module.save_token('bdsp_new') + self.assertEqual(stat.S_IMODE(os.stat(path).st_mode), 0o600) + self.assertEqual(open(path).read().strip(), 'bdsp_new') + + def test_get_r_into_the_current_folder(self): + cwd = os.getcwd() + os.chdir(self.home) + self.addCleanup(os.chdir, cwd) + code, out, err = self.run_cli('get', 'demo', '1.0', 'waves', '-r', '-o', '.') + self.assertEqual(code, 0, err) + self.assertTrue(os.path.isfile(os.path.join(self.home, '100.dat'))) + + def test_a_long_or_dated_retry_after_is_reported_not_retried_early(self): + with mock.patch.object(client_module.time, 'sleep') as sleep, self.assertRaises(ApiError) as caught: + Client()._get('/api/v2/slow/') + sleep.assert_not_called() + self.assertEqual(caught.exception.status, 429) + + def test_an_unrequested_partial_response_is_not_published(self): + target = os.path.join(self.home, 'whole.dat') + with open(target, 'w') as f: + f.write('the complete copy') + with self.assertRaises(ApiError): + Client().download('demo', '1.0', 'partial', target) + self.assertEqual(open(target).read(), 'the complete copy') + + def test_a_relative_next_link_is_read_against_its_own_page(self): + self.assertEqual([r['n'] for r in Client()._pages('/api/v2/relative/', {})], [1, 2]) + + def test_port_zero_is_refused(self): + with self.assertRaises(ApiError): + Client()._get_url(self.url.rsplit(':', 1)[0] + ':0/api/v2/me/') + + def test_a_reparse_point_counts_as_a_link(self): + from bdsp.web.client import redirects_elsewhere + folder = os.path.join(self.home, 'plain') + os.makedirs(folder) + self.assertFalse(redirects_elsewhere(folder)) + self.assertFalse(redirects_elsewhere(os.path.join(self.home, 'missing'))) + fake = mock.Mock(st_mode=0o40755, st_file_attributes=0x400) # a Windows junction, as lstat reports it + with mock.patch.object(os, 'lstat', return_value=fake): + self.assertTrue(redirects_elsewhere(folder)) + + def test_field_errors_are_shown(self): + code, _, err = self.run_cli('get', 'demo', '1.0', 'bad path', '-o', os.path.join(self.home, 'x')) + self.assertEqual(code, 1) + self.assertIn('Invalid path', err) + + +if __name__ == '__main__': + unittest.main()