|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Store provider API keys for moto sidecars without writing them to repos.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import argparse |
| 7 | +import getpass |
| 8 | +import json |
| 9 | +import os |
| 10 | +import platform |
| 11 | +import subprocess |
| 12 | +import sys |
| 13 | +import tempfile |
| 14 | +from pathlib import Path |
| 15 | + |
| 16 | + |
| 17 | +PROVIDERS = { |
| 18 | + "gemini": "GEMINI_FREE_API_KEY", |
| 19 | + "groq": "GROQ_API_KEY", |
| 20 | + "openrouter": "OPENROUTER_API_KEY", |
| 21 | + "nvidia": "NVIDIA_API_KEY", |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +def store_path() -> Path: |
| 26 | + return Path(os.environ.get("AI_SIDECAR_DIR", Path.home() / ".config/ai-sidecar")) / "keys.json" |
| 27 | + |
| 28 | + |
| 29 | +def is_macos() -> bool: |
| 30 | + return platform.system() == "Darwin" and bool(shutil_which("security")) |
| 31 | + |
| 32 | + |
| 33 | +def shutil_which(name: str) -> str | None: |
| 34 | + from shutil import which |
| 35 | + |
| 36 | + return which(name) |
| 37 | + |
| 38 | + |
| 39 | +def keychain_service(provider: str) -> str: |
| 40 | + return f"codex:{PROVIDERS[provider]}" |
| 41 | + |
| 42 | + |
| 43 | +def keychain_get(provider: str) -> str: |
| 44 | + result = subprocess.run( |
| 45 | + [ |
| 46 | + "security", |
| 47 | + "find-generic-password", |
| 48 | + "-a", |
| 49 | + os.environ.get("USER", ""), |
| 50 | + "-s", |
| 51 | + keychain_service(provider), |
| 52 | + "-w", |
| 53 | + ], |
| 54 | + check=False, |
| 55 | + capture_output=True, |
| 56 | + text=True, |
| 57 | + ) |
| 58 | + return result.stdout.strip() if result.returncode == 0 else "" |
| 59 | + |
| 60 | + |
| 61 | +def keychain_set(provider: str, secret: str) -> None: |
| 62 | + subprocess.run( |
| 63 | + [ |
| 64 | + "security", |
| 65 | + "add-generic-password", |
| 66 | + "-U", |
| 67 | + "-a", |
| 68 | + os.environ.get("USER", ""), |
| 69 | + "-s", |
| 70 | + keychain_service(provider), |
| 71 | + "-w", |
| 72 | + secret, |
| 73 | + ], |
| 74 | + check=True, |
| 75 | + stdout=subprocess.DEVNULL, |
| 76 | + ) |
| 77 | + |
| 78 | + |
| 79 | +def keychain_delete(provider: str) -> None: |
| 80 | + subprocess.run( |
| 81 | + [ |
| 82 | + "security", |
| 83 | + "delete-generic-password", |
| 84 | + "-a", |
| 85 | + os.environ.get("USER", ""), |
| 86 | + "-s", |
| 87 | + keychain_service(provider), |
| 88 | + ], |
| 89 | + check=False, |
| 90 | + stdout=subprocess.DEVNULL, |
| 91 | + stderr=subprocess.DEVNULL, |
| 92 | + ) |
| 93 | + |
| 94 | + |
| 95 | +def ensure_file_store() -> Path: |
| 96 | + path = store_path() |
| 97 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 98 | + path.parent.chmod(0o700) |
| 99 | + if not path.exists(): |
| 100 | + path.write_text("{}\n") |
| 101 | + path.chmod(0o600) |
| 102 | + return path |
| 103 | + |
| 104 | + |
| 105 | +def read_file_store() -> dict[str, str]: |
| 106 | + path = ensure_file_store() |
| 107 | + try: |
| 108 | + data = json.loads(path.read_text()) |
| 109 | + except json.JSONDecodeError: |
| 110 | + data = {} |
| 111 | + return {str(k): str(v) for k, v in data.items()} |
| 112 | + |
| 113 | + |
| 114 | +def write_file_store(data: dict[str, str]) -> None: |
| 115 | + path = ensure_file_store() |
| 116 | + fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".keys.", suffix=".tmp") |
| 117 | + with os.fdopen(fd, "w") as handle: |
| 118 | + json.dump(data, handle, indent=2, sort_keys=True) |
| 119 | + handle.write("\n") |
| 120 | + os.chmod(tmp, 0o600) |
| 121 | + os.replace(tmp, path) |
| 122 | + |
| 123 | + |
| 124 | +def get_key(provider: str) -> str: |
| 125 | + if is_macos(): |
| 126 | + return keychain_get(provider) |
| 127 | + return read_file_store().get(provider, "") |
| 128 | + |
| 129 | + |
| 130 | +def set_key(provider: str, secret: str) -> None: |
| 131 | + if is_macos(): |
| 132 | + keychain_set(provider, secret) |
| 133 | + else: |
| 134 | + data = read_file_store() |
| 135 | + data[provider] = secret |
| 136 | + write_file_store(data) |
| 137 | + |
| 138 | + |
| 139 | +def delete_key(provider: str) -> None: |
| 140 | + if is_macos(): |
| 141 | + keychain_delete(provider) |
| 142 | + else: |
| 143 | + data = read_file_store() |
| 144 | + data.pop(provider, None) |
| 145 | + write_file_store(data) |
| 146 | + |
| 147 | + |
| 148 | +def main() -> int: |
| 149 | + parser = argparse.ArgumentParser(description=__doc__) |
| 150 | + parser.add_argument("command", choices=["set", "get", "delete", "list"]) |
| 151 | + parser.add_argument("provider", nargs="?", choices=sorted(PROVIDERS)) |
| 152 | + args = parser.parse_args() |
| 153 | + |
| 154 | + if args.command != "list" and not args.provider: |
| 155 | + parser.error("provider is required") |
| 156 | + |
| 157 | + if args.command == "set": |
| 158 | + secret = sys.stdin.readline().rstrip("\n") if not sys.stdin.isatty() else getpass.getpass( |
| 159 | + f"Enter {PROVIDERS[args.provider]}: " |
| 160 | + ) |
| 161 | + if not secret: |
| 162 | + raise SystemExit("Empty key; nothing stored.") |
| 163 | + set_key(args.provider, secret) |
| 164 | + print(f"Stored {args.provider}.") |
| 165 | + return 0 |
| 166 | + |
| 167 | + if args.command == "get": |
| 168 | + secret = get_key(args.provider) |
| 169 | + if not secret: |
| 170 | + return 1 |
| 171 | + print(secret) |
| 172 | + return 0 |
| 173 | + |
| 174 | + if args.command == "delete": |
| 175 | + delete_key(args.provider) |
| 176 | + print(f"Deleted {args.provider} if it existed.") |
| 177 | + return 0 |
| 178 | + |
| 179 | + for provider in sorted(PROVIDERS): |
| 180 | + if get_key(provider): |
| 181 | + print(provider) |
| 182 | + return 0 |
| 183 | + |
| 184 | + |
| 185 | +if __name__ == "__main__": |
| 186 | + raise SystemExit(main()) |
0 commit comments