Skip to content

Commit

Permalink
Add ability to get keys from a safe password store
Browse files Browse the repository at this point in the history
I use password-store but this can be configured to use anything
that can print a key or secret on stdout.
  • Loading branch information
jepler committed Oct 23, 2024
1 parent d38a98a commit 4fc3607
Showing 1 changed file with 29 additions and 11 deletions.
40 changes: 29 additions & 11 deletions src/chap/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
#
# SPDX-License-Identifier: MIT

import json
import subprocess
from typing import Protocol
import functools

Expand Down Expand Up @@ -31,14 +33,30 @@ class NoKeyAvailable(Exception):

_key_path_base = platformdirs.user_config_path("chap")


@functools.cache
def get_key(name: str, what: str = "openai api key") -> str:
key_path = _key_path_base / name
if not key_path.exists():
raise NoKeyAvailable(
f"Place your {what} in {key_path} and run the program again"
)

with open(key_path, encoding="utf-8") as f:
return f.read().strip()
USE_PASSWORD_STORE = _key_path_base / "USE_PASSWORD_STORE"

if USE_PASSWORD_STORE.exists():
content = USE_PASSWORD_STORE.read_text(encoding="utf-8")
if content.strip():
cfg = json.loads(content)
pass_command: list[str] = cfg.get("PASS_COMMAND", ["pass", "show"])
pass_prefix: str = cfg.get("PASS_PREFIX", "chap/")

@functools.cache
def get_key(name: str, what: str = "api key") -> str:
key_path = f"{pass_prefix}{name}"
command = pass_command + [key_path]
return subprocess.check_output(command, encoding="utf-8").split("\n")[0]

else:

@functools.cache
def get_key(name: str, what: str = "api key") -> str:
key_path = _key_path_base / name
if not key_path.exists():
raise NoKeyAvailable(
f"Place your {what} in {key_path} and run the program again"
)

with open(key_path, encoding="utf-8") as f:
return f.read().strip()

0 comments on commit 4fc3607

Please sign in to comment.