mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-05 15:35:06 +00:00
feat(kv)!: take KID:KEY pairs and key files as kv add arguments with optional --service and --vault
This commit is contained in:
@@ -460,9 +460,16 @@ A vault argument is the name of a vault in the config, or the path to an SQLite
|
||||
|
||||
Make sure that two or more vaults hold the same set of content keys, essentially a chained bidirectional copy. More than one vault is necessary. Accepts the same `--service` / `--local-only` options as `copy`.
|
||||
|
||||
### `kv add FILE SERVICE VAULT...`
|
||||
### `kv add KEY...`
|
||||
|
||||
Add content keys to one or more vaults for a service. `FILE` contains one `KID:KEY` pair per line (32 hex : 32 hex, UTF-8). unshackle skips every line that does not match that form.
|
||||
Add content keys to vaults. Each `KEY` is a `KID:KEY` pair (32 hex : 32 hex; unshackle removes dashes from the KID), or the path of a UTF-8 file with one `KID:KEY` pair per line. unshackle skips every file line that is not a pair. An argument that is not a pair or an existing file stops `kv add` with an error.
|
||||
|
||||
unshackle sends the content keys to each vault, also when another vault already holds them, and reports how many each vault already held.
|
||||
|
||||
| Option | Description |
|
||||
|---|---|
|
||||
| `-s`, `--service` | The service to add the content keys to. Without it, unshackle writes them to the `generic` table. |
|
||||
| `-v`, `--vault` | A vault name from the config, or the path to an SQLite vault file. Repeat it for more vaults. Without it, unshackle writes to every configured vault that does not set `no_push`. |
|
||||
|
||||
### `kv search KID`
|
||||
|
||||
@@ -485,7 +492,8 @@ unshackle kv copy main backup1 backup2
|
||||
unshackle kv copy main backup -s EXAMPLE
|
||||
unshackle kv copy main ~/Downloads/key_store.db -s EXAMPLE
|
||||
unshackle kv sync main mysql_vault
|
||||
unshackle kv add keys.txt EXAMPLE main backup
|
||||
unshackle kv add 0123456789abcdef0123456789abcdef:fedcba9876543210fedcba9876543210
|
||||
unshackle kv add keys.txt -s EXAMPLE -v main -v backup
|
||||
unshackle kv search 0123456789abcdef0123456789abcdef -s EXAMPLE -v main
|
||||
unshackle kv prepare main mysql_vault
|
||||
```
|
||||
|
||||
@@ -188,12 +188,13 @@ The `kv` command group manages the contents of your configured vaults. Every sub
|
||||
$ unshackle kv --help
|
||||
```
|
||||
|
||||
### `kv add`: import keys from a file
|
||||
### `kv add`: add content keys
|
||||
|
||||
Add `KID:KEY` pairs to one or more vaults for a given service. The file must contain one pair per line as `HEX:HEX` (32 hex characters each); lines that do not match are ignored.
|
||||
Add `KID:KEY` pairs to your vaults, for a service or in the `generic` table. Give each pair on the command line, or give a file with one pair per line. The options are in the [CLI reference](cli-reference.md#kv-add-key).
|
||||
|
||||
```console
|
||||
$ unshackle kv add keys.txt EXAMPLE local shared
|
||||
$ unshackle kv add 9a04f07998404286ab92e65be0885f95:b1c2d3e4f5a6978012345678deadbeef
|
||||
$ unshackle kv add keys.txt -s EXAMPLE -v local -v shared
|
||||
```
|
||||
|
||||
```text title="keys.txt"
|
||||
@@ -201,7 +202,7 @@ $ unshackle kv add keys.txt EXAMPLE local shared
|
||||
0e7cc1a4e2f9411db0f24a3fbb8f8b21:00112233445566778899aabbccddeeff
|
||||
```
|
||||
|
||||
The service argument (`EXAMPLE` above) is normalised to its canonical tag automatically. Keys that already exist in a vault are reported as skipped.
|
||||
The service (`EXAMPLE` above) is normalised to its canonical tag automatically. Keys that already exist in a vault are reported as skipped. The other vaults still receive them.
|
||||
|
||||
If a vault answers and refuses the content keys, `kv add` shows one warning and continues with the next vault. If a vault is unreachable or still rate limited, `kv add` stops with an error.
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
import click
|
||||
import pytest
|
||||
from click.testing import CliRunner
|
||||
|
||||
@@ -12,6 +13,13 @@ from unshackle.vaults.SQLite import SQLite
|
||||
|
||||
KID = "0" * 31 + "1"
|
||||
KEY = "a" * 32
|
||||
DECRYPT_LABS_VAULT = {
|
||||
"type": "HTTP",
|
||||
"name": "labs",
|
||||
"host": "https://vault.example/",
|
||||
"api_key": "tok",
|
||||
"api_mode": "decrypt_labs",
|
||||
}
|
||||
QUERY_VAULT = {"type": "HTTP", "name": "shared", "host": "https://vault.example/", "password": "tok", "username": "u"}
|
||||
|
||||
|
||||
@@ -87,7 +95,7 @@ def test_kv_add_warns_and_skips_a_vault_that_refuses_and_adds_to_the_next(
|
||||
refuse_example(monkeypatch)
|
||||
|
||||
with caplog.at_level(logging.WARNING, logger="kv"):
|
||||
result = CliRunner().invoke(kv_module.kv, ["add", str(keys), "EXAMPLE", "shared", "local"])
|
||||
result = CliRunner().invoke(kv_module.kv, ["add", str(keys), "-s", "EXAMPLE", "-v", "shared", "-v", "local"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert SQLite("check", dest).get_key(KID, "EXAMPLE") == KEY
|
||||
@@ -101,12 +109,109 @@ def test_kv_add_skips_a_null_key_line_and_adds_the_rest(tmp_path: Path, monkeypa
|
||||
null_kid = "0" * 31 + "2"
|
||||
keys.write_text(f"{KID}:{KEY}\n{null_kid}:{'0' * 32}\n", encoding="utf8")
|
||||
dest = tmp_path / "local.db"
|
||||
monkeypatch.setattr(kv_module.config, "key_vaults", [{"type": "SQLite", "name": "local", "path": str(dest)}])
|
||||
monkeypatch.setattr(kv_module.Services, "get_vault_tag", lambda name: name)
|
||||
local_vaults(monkeypatch, dest)
|
||||
|
||||
result = CliRunner().invoke(kv_module.kv, ["add", str(keys), "TESTSVC", "local"])
|
||||
result = CliRunner().invoke(kv_module.kv, ["add", str(keys), "-s", "TESTSVC", "-v", "local"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
check = SQLite("check", dest)
|
||||
assert check.get_key(KID, "TESTSVC") == KEY
|
||||
assert check.get_key(null_kid, "TESTSVC") is None
|
||||
|
||||
|
||||
def local_vaults(monkeypatch: pytest.MonkeyPatch, *paths: Path, no_push: Path | None = None) -> None:
|
||||
"""Configure one SQLite vault per path, plus a no_push one when given, and leave service tags as given."""
|
||||
vaults = [{"type": "SQLite", "name": p.stem, "path": str(p)} for p in paths]
|
||||
if no_push:
|
||||
vaults.append({"type": "SQLite", "name": no_push.stem, "path": str(no_push), "no_push": True})
|
||||
monkeypatch.setattr(kv_module.config, "key_vaults", vaults)
|
||||
monkeypatch.setattr(kv_module.Services, "get_vault_tag", lambda name: name)
|
||||
|
||||
|
||||
def test_kv_add_without_vault_writes_every_configured_vault_even_where_one_already_holds_the_pair(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
first, second, read_only = tmp_path / "local.db", tmp_path / "remote.db", tmp_path / "read_only.db"
|
||||
SQLite("seed", first).add_key("EXAMPLE", KID, KEY)
|
||||
SQLite("seed", read_only).add_key("OTHER", KID, KEY)
|
||||
local_vaults(monkeypatch, first, second, no_push=read_only)
|
||||
monkeypatch.setattr(kv_module.config, "key_vaults", [*kv_module.config.key_vaults, DECRYPT_LABS_VAULT])
|
||||
|
||||
with caplog.at_level(logging.INFO, logger="kv"):
|
||||
result = CliRunner().invoke(kv_module.kv, ["add", f"{KID}:{KEY}", "--service", "EXAMPLE"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert SQLite("check", second).get_key(KID, "EXAMPLE") == KEY
|
||||
assert SQLite("check", read_only).get_key(KID, "EXAMPLE") is None
|
||||
lines = [r.getMessage() for r in caplog.records]
|
||||
assert not any("labs" in line for line in lines)
|
||||
assert "local SQLite: 0 newly added, 1 already existed (skipped)" in lines
|
||||
assert "remote SQLite: 1 newly added, 0 already existed (skipped)" in lines
|
||||
|
||||
|
||||
def test_kv_add_takes_a_dashed_pair_and_a_bom_key_file_into_a_vault_file(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
other_kid = "0" * 31 + "3"
|
||||
keys = tmp_path / "keys.txt"
|
||||
keys.write_text(f"{other_kid}:{KEY}\nnot a pair\n", encoding="utf-8-sig")
|
||||
dest = tmp_path / "file.db"
|
||||
dest.touch()
|
||||
local_vaults(monkeypatch)
|
||||
dashed = "00000000-0000-0000-0000-00000000000A"
|
||||
|
||||
result = CliRunner().invoke(
|
||||
kv_module.kv, ["add", "-s", "EXAMPLE", "-v", str(dest), f"{dashed}:{KEY.upper()}", str(keys)]
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
check = SQLite("check", dest)
|
||||
assert check.get_key("0" * 31 + "a", "EXAMPLE") == KEY
|
||||
assert check.get_key(other_kid, "EXAMPLE") == KEY
|
||||
|
||||
|
||||
def test_kv_add_without_service_writes_the_generic_table(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
dest = tmp_path / "local.db"
|
||||
local_vaults(monkeypatch, dest)
|
||||
|
||||
result = CliRunner().invoke(kv_module.kv, ["add", f"{KID}:{KEY}", "-v", "local"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert SQLite("check", dest).get_key(KID, "generic") == KEY
|
||||
|
||||
|
||||
@pytest.mark.parametrize("no_push", [False, True])
|
||||
def test_kv_add_without_vault_stops_when_no_configured_vault_takes_pushes(
|
||||
no_push: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
local_vaults(monkeypatch, no_push=tmp_path / "read_only.db" if no_push else None)
|
||||
|
||||
result = CliRunner().invoke(kv_module.kv, ["add", f"{KID}:{KEY}", "-s", "EXAMPLE"], standalone_mode=False)
|
||||
|
||||
assert isinstance(result.exception, click.ClickException)
|
||||
assert result.exception.message == "No Key Vaults without no_push are configured."
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arg", [f"{KID}:{KEY[:-1]}", f"{KID}{KEY}", "missing.txt"])
|
||||
def test_kv_add_rejects_an_argument_that_is_neither_a_pair_nor_a_file(
|
||||
arg: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
local_vaults(monkeypatch, tmp_path / "local.db")
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
result = CliRunner().invoke(kv_module.kv, ["add", arg, "-s", "EXAMPLE"], standalone_mode=False)
|
||||
|
||||
assert isinstance(result.exception, click.ClickException)
|
||||
assert result.exception.message == f"Argument ({arg}) is not a KID:KEY or an existing file."
|
||||
assert not (tmp_path / "local.db").exists()
|
||||
|
||||
|
||||
def test_kv_add_names_a_key_file_that_is_not_utf8(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
keys = tmp_path / "keys.txt"
|
||||
keys.write_bytes(b"\xff\xfe" + f"{KID}:{KEY}".encode("utf-16-le"))
|
||||
local_vaults(monkeypatch, tmp_path / "local.db")
|
||||
|
||||
result = CliRunner().invoke(kv_module.kv, ["add", str(keys), "-s", "EXAMPLE"], standalone_mode=False)
|
||||
|
||||
assert isinstance(result.exception, click.ClickException)
|
||||
assert result.exception.message.startswith(f"Could not read {keys} (")
|
||||
|
||||
+51
-29
@@ -288,37 +288,59 @@ def sync(
|
||||
)
|
||||
|
||||
|
||||
def parse_kid_key(text: str) -> tuple[str, str] | None:
|
||||
"""Return the lowercase (kid, key) of a KID:KEY, with dashes removed from the KID, or None."""
|
||||
kid, _, key = text.strip().partition(":")
|
||||
kid, key = kid.replace("-", "").lower(), key.lower()
|
||||
if re.fullmatch(r"[0-9a-f]{32}", kid) and re.fullmatch(r"[0-9a-f]{32}", key):
|
||||
return kid, key
|
||||
return None
|
||||
|
||||
|
||||
@kv.command()
|
||||
@click.argument("file", type=Path)
|
||||
@click.argument("service", type=str)
|
||||
@click.argument("vaults", nargs=-1, type=click.UNPROCESSED)
|
||||
def add(file: Path, service: str, vaults: list[str]) -> None:
|
||||
"""
|
||||
Add new Content Keys to Key Vault(s) by service.
|
||||
|
||||
File should contain one content key per line in the format KID:KEY (HEX:HEX).
|
||||
Each line should have nothing else within it except for the KID:KEY.
|
||||
unshackle reads the file as UTF8.
|
||||
"""
|
||||
if not file.exists():
|
||||
raise click.ClickException(f"File provided ({file}) does not exist.")
|
||||
if not file.is_file():
|
||||
raise click.ClickException(f"File provided ({file}) is not a file.")
|
||||
if not service or not isinstance(service, str):
|
||||
raise click.ClickException(f"Service provided ({service}) is invalid.")
|
||||
if len(vaults) < 1:
|
||||
raise click.ClickException("You must provide at least one Vault.")
|
||||
|
||||
log = logging.getLogger("kv")
|
||||
service = Services.get_vault_tag(service)
|
||||
|
||||
vaults_ = load_vaults(list(vaults))
|
||||
|
||||
data = file.read_text(encoding="utf8")
|
||||
matches = (
|
||||
re.search(r"^(?P<kid>[0-9a-fA-F]{32}):(?P<key>[0-9a-fA-F]{32})$", line.strip()) for line in data.splitlines()
|
||||
@click.argument("keys", metavar="KEY...", nargs=-1, required=True)
|
||||
@click.option(
|
||||
"-s", "--service", type=str, default=None, help="Service to add the content keys to. Default: the generic table."
|
||||
)
|
||||
kid_keys = without_null_keys(((m["kid"].lower(), m["key"].lower()) for m in matches if m), log)
|
||||
@click.option(
|
||||
"-v",
|
||||
"--vault",
|
||||
"vault_names",
|
||||
type=str,
|
||||
multiple=True,
|
||||
help="Vault name from the config or path to an SQLite vault file. Repeat for more vaults. Default: every configured vault without no_push.",
|
||||
)
|
||||
def add(keys: tuple[str, ...], service: str | None, vault_names: tuple[str, ...]) -> None:
|
||||
"""
|
||||
Add content keys to Key Vaults, for a service or in the generic table.
|
||||
|
||||
Each KEY is a KID:KEY (32 hex : 32 hex; unshackle removes dashes from the KID),
|
||||
or the path of a UTF-8 file with one KID:KEY per line.
|
||||
unshackle skips every file line that is not a KID:KEY.
|
||||
"""
|
||||
log = logging.getLogger("kv")
|
||||
|
||||
pairs: list[tuple[str, str]] = []
|
||||
for arg in keys:
|
||||
if pair := parse_kid_key(arg):
|
||||
pairs.append(pair)
|
||||
continue
|
||||
path = Path(arg).expanduser()
|
||||
if not path.is_file():
|
||||
raise click.ClickException(f"Argument ({arg}) is not a KID:KEY or an existing file.")
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
||||
except (OSError, UnicodeDecodeError) as e:
|
||||
raise click.ClickException(f"Could not read {arg} ({brief(e)})") from None
|
||||
pairs.extend(p for line in lines if (p := parse_kid_key(line)))
|
||||
kid_keys = without_null_keys(pairs, log)
|
||||
|
||||
names = list(vault_names) or [v["name"] for v in config.key_vaults if not v.get("no_push")]
|
||||
if not names:
|
||||
raise click.ClickException("No Key Vaults without no_push are configured.")
|
||||
|
||||
service = Services.get_vault_tag(service) if service else "generic"
|
||||
vaults_ = [v for v in load_vaults(names) if vault_names or not v.no_push]
|
||||
|
||||
total_count = len(kid_keys)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user