asiri-guard 0.1.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.
- asiri_guard-0.1.0/.github/workflows/publish.yml +39 -0
- asiri_guard-0.1.0/.gitignore +6 -0
- asiri_guard-0.1.0/LICENSE +21 -0
- asiri_guard-0.1.0/PKG-INFO +59 -0
- asiri_guard-0.1.0/README.md +49 -0
- asiri_guard-0.1.0/pyproject.toml +18 -0
- asiri_guard-0.1.0/src/asiri/__init__.py +3 -0
- asiri_guard-0.1.0/src/asiri/__main__.py +5 -0
- asiri_guard-0.1.0/src/asiri/cli.py +122 -0
- asiri_guard-0.1.0/src/asiri/hook.py +42 -0
- asiri_guard-0.1.0/src/asiri/install.py +104 -0
- asiri_guard-0.1.0/src/asiri/scan.py +60 -0
- asiri_guard-0.1.0/src/asiri/store.py +39 -0
- asiri_guard-0.1.0/tests/test_scan.py +129 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
name: publish
|
|
2
|
+
|
|
3
|
+
# Publishes to PyPI when a version tag such as v0.1.0 is pushed.
|
|
4
|
+
# Uses PyPI trusted publishing (OIDC), so no API token is stored in the repo.
|
|
5
|
+
|
|
6
|
+
on:
|
|
7
|
+
push:
|
|
8
|
+
tags:
|
|
9
|
+
- "v*"
|
|
10
|
+
|
|
11
|
+
permissions:
|
|
12
|
+
contents: read
|
|
13
|
+
|
|
14
|
+
jobs:
|
|
15
|
+
test:
|
|
16
|
+
runs-on: ubuntu-latest
|
|
17
|
+
steps:
|
|
18
|
+
- uses: actions/checkout@v4
|
|
19
|
+
- uses: actions/setup-python@v5
|
|
20
|
+
with:
|
|
21
|
+
python-version: "3.12"
|
|
22
|
+
- run: pip install -e .
|
|
23
|
+
- run: PYTHONPATH=src python -m unittest discover -s tests
|
|
24
|
+
|
|
25
|
+
publish:
|
|
26
|
+
needs: test
|
|
27
|
+
runs-on: ubuntu-latest
|
|
28
|
+
environment: pypi
|
|
29
|
+
permissions:
|
|
30
|
+
id-token: write # required for trusted publishing
|
|
31
|
+
contents: read
|
|
32
|
+
steps:
|
|
33
|
+
- uses: actions/checkout@v4
|
|
34
|
+
- uses: actions/setup-python@v5
|
|
35
|
+
with:
|
|
36
|
+
python-version: "3.12"
|
|
37
|
+
- run: pip install build
|
|
38
|
+
- run: python -m build
|
|
39
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Muyiwa Alashi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: asiri-guard
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Keep secrets out of AI chats: scan text before it is sent to an LLM.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: keyring>=24
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# asiri (àṣírí)
|
|
12
|
+
|
|
13
|
+
*àṣírí* is Yoruba for "secret." asiri keeps secrets out of AI chats.
|
|
14
|
+
|
|
15
|
+
It scans text for secret-looking values before a prompt is sent, and it stores named secrets in your OS keychain so you can refer to them by name instead of pasting them.
|
|
16
|
+
|
|
17
|
+
> Status: early version. Claude Code only, macOS-tested.
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
uv tool install asiri-guard
|
|
23
|
+
asiri install claude
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`asiri install claude` adds a `UserPromptSubmit` hook to `~/.claude/settings.json`. It makes a timestamped backup first, and `asiri uninstall claude` removes only asiri's entries.
|
|
27
|
+
|
|
28
|
+
## Use
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
asiri set stripe-test # value is prompted, never echoed
|
|
32
|
+
asiri list # names only
|
|
33
|
+
asiri check stripe-test # confirms a name exists, never prints the value
|
|
34
|
+
asiri rm stripe-test
|
|
35
|
+
asiri scan notes.md # scan a file or stdin for secret-looking values
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
If you paste a live key into Claude Code, the hook blocks the prompt and tells you to store the value with `asiri set`.
|
|
39
|
+
|
|
40
|
+
## What it detects
|
|
41
|
+
|
|
42
|
+
Stripe live keys, Anthropic and OpenAI keys, GitHub tokens, AWS access keys, Slack tokens, Google API keys, private key headers, and `api_key = "..."`-style assignments. Stripe test keys (`sk_test_`) are allowed on purpose.
|
|
43
|
+
|
|
44
|
+
## Limits
|
|
45
|
+
|
|
46
|
+
- Pattern matching only catches known formats. A custom key with no recognizable shape can get through.
|
|
47
|
+
- The hook covers messages typed into Claude Code. It can't see text in other apps, and it can't remove anything already sent.
|
|
48
|
+
- Anything a tool can read from your environment can still be read by that tool.
|
|
49
|
+
|
|
50
|
+
## Development
|
|
51
|
+
|
|
52
|
+
```
|
|
53
|
+
uv venv .venv && uv pip install -e .
|
|
54
|
+
PYTHONPATH=src .venv/bin/python -m unittest discover -s tests -v
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## License
|
|
58
|
+
|
|
59
|
+
MIT.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# asiri (àṣírí)
|
|
2
|
+
|
|
3
|
+
*àṣírí* is Yoruba for "secret." asiri keeps secrets out of AI chats.
|
|
4
|
+
|
|
5
|
+
It scans text for secret-looking values before a prompt is sent, and it stores named secrets in your OS keychain so you can refer to them by name instead of pasting them.
|
|
6
|
+
|
|
7
|
+
> Status: early version. Claude Code only, macOS-tested.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
uv tool install asiri-guard
|
|
13
|
+
asiri install claude
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
`asiri install claude` adds a `UserPromptSubmit` hook to `~/.claude/settings.json`. It makes a timestamped backup first, and `asiri uninstall claude` removes only asiri's entries.
|
|
17
|
+
|
|
18
|
+
## Use
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
asiri set stripe-test # value is prompted, never echoed
|
|
22
|
+
asiri list # names only
|
|
23
|
+
asiri check stripe-test # confirms a name exists, never prints the value
|
|
24
|
+
asiri rm stripe-test
|
|
25
|
+
asiri scan notes.md # scan a file or stdin for secret-looking values
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
If you paste a live key into Claude Code, the hook blocks the prompt and tells you to store the value with `asiri set`.
|
|
29
|
+
|
|
30
|
+
## What it detects
|
|
31
|
+
|
|
32
|
+
Stripe live keys, Anthropic and OpenAI keys, GitHub tokens, AWS access keys, Slack tokens, Google API keys, private key headers, and `api_key = "..."`-style assignments. Stripe test keys (`sk_test_`) are allowed on purpose.
|
|
33
|
+
|
|
34
|
+
## Limits
|
|
35
|
+
|
|
36
|
+
- Pattern matching only catches known formats. A custom key with no recognizable shape can get through.
|
|
37
|
+
- The hook covers messages typed into Claude Code. It can't see text in other apps, and it can't remove anything already sent.
|
|
38
|
+
- Anything a tool can read from your environment can still be read by that tool.
|
|
39
|
+
|
|
40
|
+
## Development
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
uv venv .venv && uv pip install -e .
|
|
44
|
+
PYTHONPATH=src .venv/bin/python -m unittest discover -s tests -v
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## License
|
|
48
|
+
|
|
49
|
+
MIT.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "asiri-guard"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Keep secrets out of AI chats: scan text before it is sent to an LLM."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = ["keyring>=24"]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
asiri = "asiri.cli:main"
|
|
16
|
+
|
|
17
|
+
[tool.hatch.build.targets.wheel]
|
|
18
|
+
packages = ["src/asiri"]
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""asiri command line: keep secrets out of AI chats."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import getpass
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from asiri import install, store
|
|
9
|
+
from asiri.scan import scan
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _cmd_set(args) -> int:
|
|
13
|
+
value = getpass.getpass(f"Value for {args.name} (hidden): ")
|
|
14
|
+
if not value:
|
|
15
|
+
print("No value entered; nothing saved.", file=sys.stderr)
|
|
16
|
+
return 1
|
|
17
|
+
store.set_secret(args.name, value)
|
|
18
|
+
print(f'Saved "{args.name}" to the keychain.')
|
|
19
|
+
return 0
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _cmd_get_check(args) -> int:
|
|
23
|
+
# Confirms a name exists without printing the value.
|
|
24
|
+
if store.get_secret(args.name) is None:
|
|
25
|
+
print(f'No secret named "{args.name}".', file=sys.stderr)
|
|
26
|
+
return 1
|
|
27
|
+
print(f'"{args.name}" is stored.')
|
|
28
|
+
return 0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _cmd_list(args) -> int:
|
|
32
|
+
names = store.list_names()
|
|
33
|
+
if not names:
|
|
34
|
+
print("No secrets stored.")
|
|
35
|
+
for n in names:
|
|
36
|
+
print(n)
|
|
37
|
+
return 0
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _cmd_rm(args) -> int:
|
|
41
|
+
store.remove_secret(args.name)
|
|
42
|
+
print(f'Removed "{args.name}".')
|
|
43
|
+
return 0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _cmd_scan(args) -> int:
|
|
47
|
+
text = Path(args.file).read_text() if args.file else sys.stdin.read()
|
|
48
|
+
findings = scan(text)
|
|
49
|
+
if not findings:
|
|
50
|
+
print("No secret-looking values found.")
|
|
51
|
+
return 0
|
|
52
|
+
for f in findings:
|
|
53
|
+
print(f"{f.kind}: {f.snippet}")
|
|
54
|
+
return 1
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _cmd_install(args) -> int:
|
|
58
|
+
try:
|
|
59
|
+
install.install()
|
|
60
|
+
except RuntimeError as exc:
|
|
61
|
+
print(f"asiri: {exc}", file=sys.stderr)
|
|
62
|
+
return 1
|
|
63
|
+
print(f"Added the asiri hook to {install.SETTINGS} and self-tested it. Restart Claude Code to pick it up.")
|
|
64
|
+
return 0
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _cmd_doctor(args) -> int:
|
|
68
|
+
ok, detail = install.self_test()
|
|
69
|
+
if ok:
|
|
70
|
+
print("asiri hook self-test passed: live keys are blocked and clean prompts pass.")
|
|
71
|
+
return 0
|
|
72
|
+
print(f"asiri hook self-test FAILED: {detail}", file=sys.stderr)
|
|
73
|
+
return 1
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _cmd_uninstall(args) -> int:
|
|
77
|
+
install.uninstall()
|
|
78
|
+
print(f"Removed the asiri hook from {install.SETTINGS}.")
|
|
79
|
+
return 0
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def main(argv=None) -> int:
|
|
83
|
+
p = argparse.ArgumentParser(prog="asiri", description="Keep secrets out of AI chats.")
|
|
84
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
85
|
+
|
|
86
|
+
s = sub.add_parser("set", help="store a secret (value is prompted, never echoed)")
|
|
87
|
+
s.add_argument("name")
|
|
88
|
+
s.set_defaults(func=_cmd_set)
|
|
89
|
+
|
|
90
|
+
s = sub.add_parser("check", help="confirm a secret name is stored")
|
|
91
|
+
s.add_argument("name")
|
|
92
|
+
s.set_defaults(func=_cmd_get_check)
|
|
93
|
+
|
|
94
|
+
s = sub.add_parser("list", help="list secret names (values are never shown)")
|
|
95
|
+
s.set_defaults(func=_cmd_list)
|
|
96
|
+
|
|
97
|
+
s = sub.add_parser("rm", help="remove a stored secret")
|
|
98
|
+
s.add_argument("name")
|
|
99
|
+
s.set_defaults(func=_cmd_rm)
|
|
100
|
+
|
|
101
|
+
s = sub.add_parser("scan", help="scan a file, or stdin, for secret-looking values")
|
|
102
|
+
s.add_argument("file", nargs="?")
|
|
103
|
+
s.set_defaults(func=_cmd_scan)
|
|
104
|
+
|
|
105
|
+
s = sub.add_parser("install", help="install the Claude Code hook")
|
|
106
|
+
s.add_argument("target", choices=["claude"])
|
|
107
|
+
s.set_defaults(func=_cmd_install)
|
|
108
|
+
|
|
109
|
+
s = sub.add_parser("uninstall", help="remove the Claude Code hook")
|
|
110
|
+
s.add_argument("target", choices=["claude"])
|
|
111
|
+
s.set_defaults(func=_cmd_uninstall)
|
|
112
|
+
|
|
113
|
+
s = sub.add_parser("doctor", help="self-test the installed hook")
|
|
114
|
+
s.add_argument("target", choices=["claude"])
|
|
115
|
+
s.set_defaults(func=_cmd_doctor)
|
|
116
|
+
|
|
117
|
+
args = p.parse_args(argv)
|
|
118
|
+
return args.func(args)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
if __name__ == "__main__":
|
|
122
|
+
sys.exit(main())
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Claude Code UserPromptSubmit hook.
|
|
2
|
+
|
|
3
|
+
Claude Code sends the prompt as JSON on stdin. Exit code 2 blocks the prompt
|
|
4
|
+
and shows stderr to the user. Any other exit code lets it through, so this
|
|
5
|
+
hook fails closed: if it can't read or check a prompt, it blocks.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from asiri.scan import scan
|
|
12
|
+
|
|
13
|
+
BLOCK = 2
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def check_prompt(payload: dict) -> list:
|
|
17
|
+
return scan(payload.get("prompt", ""))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main() -> int:
|
|
21
|
+
try:
|
|
22
|
+
payload = json.load(sys.stdin)
|
|
23
|
+
findings = check_prompt(payload)
|
|
24
|
+
except Exception as exc: # fail closed: an unchecked prompt must not go through
|
|
25
|
+
print(
|
|
26
|
+
f"asiri could not check this prompt ({type(exc).__name__}), so it was blocked. "
|
|
27
|
+
"Run `asiri doctor claude` to diagnose the hook.",
|
|
28
|
+
file=sys.stderr,
|
|
29
|
+
)
|
|
30
|
+
return BLOCK
|
|
31
|
+
if not findings:
|
|
32
|
+
return 0
|
|
33
|
+
lines = ["asiri blocked this prompt: it contains secret-looking values:"]
|
|
34
|
+
for f in findings:
|
|
35
|
+
lines.append(f" - {f.kind}: {f.snippet}")
|
|
36
|
+
lines.append("Store the value with `asiri set <name>` and refer to it by name instead.")
|
|
37
|
+
print("\n".join(lines), file=sys.stderr)
|
|
38
|
+
return BLOCK
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
if __name__ == "__main__":
|
|
42
|
+
sys.exit(main())
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Install and remove the asiri hook in ~/.claude/settings.json.
|
|
2
|
+
|
|
3
|
+
Writes a timestamped backup before changing anything, and only touches
|
|
4
|
+
hook entries that point at asiri, so other hooks are left alone.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import shlex
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
SETTINGS = Path.home() / ".claude" / "settings.json"
|
|
16
|
+
EVENT = "UserPromptSubmit"
|
|
17
|
+
MARKER = "asiri.hook"
|
|
18
|
+
BLOCK = 2
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _command() -> str:
|
|
22
|
+
return f"{sys.executable} -m {MARKER}"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def self_test(command: str | None = None) -> tuple[bool, str]:
|
|
26
|
+
"""Run the hook command on a live-looking key (must block) and a clean prompt (must pass).
|
|
27
|
+
|
|
28
|
+
The key is built at runtime so this file never contains a real-looking secret.
|
|
29
|
+
"""
|
|
30
|
+
command = command or _command()
|
|
31
|
+
live = "sk_" + "live_" + "A" * 24
|
|
32
|
+
cases = [("live key", live, BLOCK), ("clean prompt", "fix the failing test", 0)]
|
|
33
|
+
for label, prompt, expected in cases:
|
|
34
|
+
try:
|
|
35
|
+
result = subprocess.run(
|
|
36
|
+
shlex.split(command),
|
|
37
|
+
input=json.dumps({"prompt": prompt}),
|
|
38
|
+
text=True,
|
|
39
|
+
capture_output=True,
|
|
40
|
+
timeout=30,
|
|
41
|
+
)
|
|
42
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
43
|
+
return False, f"{label}: could not run the hook command ({exc})"
|
|
44
|
+
if result.returncode != expected:
|
|
45
|
+
detail = (result.stderr or result.stdout).strip()[:200]
|
|
46
|
+
return False, f"{label}: expected exit {expected}, got {result.returncode}. {detail}"
|
|
47
|
+
return True, ""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _load(path: Path) -> dict:
|
|
51
|
+
if not path.exists():
|
|
52
|
+
return {}
|
|
53
|
+
return json.loads(path.read_text() or "{}")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _backup(path: Path) -> None:
|
|
57
|
+
if path.exists():
|
|
58
|
+
stamp = time.strftime("%Y%m%d-%H%M%S")
|
|
59
|
+
shutil.copy2(path, path.with_name(f"{path.name}.asiri-backup-{stamp}"))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _strip(groups: list) -> list:
|
|
63
|
+
kept = []
|
|
64
|
+
for group in groups:
|
|
65
|
+
hooks = [h for h in group.get("hooks", []) if MARKER not in h.get("command", "")]
|
|
66
|
+
if hooks:
|
|
67
|
+
kept.append({**group, "hooks": hooks})
|
|
68
|
+
return kept
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def install(path: Path = SETTINGS) -> None:
|
|
72
|
+
"""Install the hook, then self-test it. If the test fails, restore the original settings."""
|
|
73
|
+
original = path.read_text() if path.exists() else None
|
|
74
|
+
data = _load(path)
|
|
75
|
+
_backup(path)
|
|
76
|
+
hooks = data.setdefault("hooks", {})
|
|
77
|
+
groups = _strip(hooks.get(EVENT, []))
|
|
78
|
+
groups.append({"hooks": [{"type": "command", "command": _command()}]})
|
|
79
|
+
hooks[EVENT] = groups
|
|
80
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
81
|
+
path.write_text(json.dumps(data, indent=2) + "\n")
|
|
82
|
+
|
|
83
|
+
ok, detail = self_test()
|
|
84
|
+
if not ok:
|
|
85
|
+
if original is None:
|
|
86
|
+
path.unlink(missing_ok=True)
|
|
87
|
+
else:
|
|
88
|
+
path.write_text(original)
|
|
89
|
+
raise RuntimeError(f"hook self-test failed, settings were restored: {detail}")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def uninstall(path: Path = SETTINGS) -> None:
|
|
93
|
+
if not path.exists():
|
|
94
|
+
return
|
|
95
|
+
data = _load(path)
|
|
96
|
+
_backup(path)
|
|
97
|
+
hooks = data.get("hooks", {})
|
|
98
|
+
if EVENT in hooks:
|
|
99
|
+
remaining = _strip(hooks[EVENT])
|
|
100
|
+
if remaining:
|
|
101
|
+
hooks[EVENT] = remaining
|
|
102
|
+
else:
|
|
103
|
+
del hooks[EVENT]
|
|
104
|
+
path.write_text(json.dumps(data, indent=2) + "\n")
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Find secret-shaped strings in text.
|
|
2
|
+
|
|
3
|
+
Rules are regexes for known key formats, plus one generic assignment rule.
|
|
4
|
+
Test-mode Stripe keys are allowed by default; everything else is a finding.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
# Order matters: more specific patterns first. Overlapping matches are dropped.
|
|
11
|
+
RULES = [
|
|
12
|
+
("private-key", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA |)?PRIVATE KEY-----")),
|
|
13
|
+
("stripe-live-key", re.compile(r"\b(?:sk|rk)_live_[0-9A-Za-z]{16,}")),
|
|
14
|
+
("stripe-test-key", re.compile(r"\b(?:sk|rk)_test_[0-9A-Za-z]{16,}")),
|
|
15
|
+
("anthropic-key", re.compile(r"\bsk-ant-[A-Za-z0-9_\-]{20,}")),
|
|
16
|
+
("openai-key", re.compile(r"\bsk-(?:proj-)?[A-Za-z0-9_\-]{20,}")),
|
|
17
|
+
("github-token", re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})")),
|
|
18
|
+
("aws-access-key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),
|
|
19
|
+
("slack-token", re.compile(r"\bxox[abprs]-[A-Za-z0-9\-]{10,}")),
|
|
20
|
+
("google-api-key", re.compile(r"\bAIza[0-9A-Za-z_\-]{35}\b")),
|
|
21
|
+
(
|
|
22
|
+
"generic-secret",
|
|
23
|
+
re.compile(
|
|
24
|
+
r"(?i)\b(?:api[_-]?key|secret|token|password|passwd)\b\s*[:=]\s*[\"']?([A-Za-z0-9_\-/+]{16,})"
|
|
25
|
+
),
|
|
26
|
+
),
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
# Test-mode keys are harmless to share and useful for local testing.
|
|
30
|
+
ALLOWED_KINDS = {"stripe-test-key"}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Finding:
|
|
35
|
+
kind: str
|
|
36
|
+
start: int
|
|
37
|
+
end: int
|
|
38
|
+
snippet: str # redacted preview, never the full value
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _redact(value: str) -> str:
|
|
42
|
+
if len(value) <= 8:
|
|
43
|
+
return "*" * len(value)
|
|
44
|
+
return value[:4] + "*" * (len(value) - 8) + value[-4:]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def scan(text: str, allowed: set[str] = frozenset(ALLOWED_KINDS)) -> list[Finding]:
|
|
48
|
+
findings: list[Finding] = []
|
|
49
|
+
taken: list[tuple[int, int]] = []
|
|
50
|
+
for kind, pattern in RULES:
|
|
51
|
+
if kind in allowed:
|
|
52
|
+
continue
|
|
53
|
+
for m in pattern.finditer(text):
|
|
54
|
+
# For rules with a capture group, the secret is the group, not the key name.
|
|
55
|
+
start, end = (m.span(1) if m.re.groups else m.span())
|
|
56
|
+
if any(start < t_end and end > t_start for t_start, t_end in taken):
|
|
57
|
+
continue
|
|
58
|
+
taken.append((start, end))
|
|
59
|
+
findings.append(Finding(kind, start, end, _redact(text[start:end])))
|
|
60
|
+
return sorted(findings, key=lambda f: f.start)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Named secret storage backed by the OS keychain (keyring).
|
|
2
|
+
|
|
3
|
+
Values never go into project files. `list` returns names only.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import keyring
|
|
7
|
+
|
|
8
|
+
SERVICE = "asiri"
|
|
9
|
+
_INDEX_KEY = "__index__"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _names() -> list[str]:
|
|
13
|
+
raw = keyring.get_password(SERVICE, _INDEX_KEY) or ""
|
|
14
|
+
return [n for n in raw.split("\n") if n]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _save_names(names: list[str]) -> None:
|
|
18
|
+
keyring.set_password(SERVICE, _INDEX_KEY, "\n".join(sorted(set(names))))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def set_secret(name: str, value: str) -> None:
|
|
22
|
+
keyring.set_password(SERVICE, name, value)
|
|
23
|
+
_save_names(_names() + [name])
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def get_secret(name: str) -> str | None:
|
|
27
|
+
return keyring.get_password(SERVICE, name)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def list_names() -> list[str]:
|
|
31
|
+
return _names()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def remove_secret(name: str) -> None:
|
|
35
|
+
try:
|
|
36
|
+
keyring.delete_password(SERVICE, name)
|
|
37
|
+
except keyring.errors.PasswordDeleteError:
|
|
38
|
+
pass
|
|
39
|
+
_save_names([n for n in _names() if n != name])
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
import unittest
|
|
4
|
+
from unittest import mock
|
|
5
|
+
|
|
6
|
+
from asiri.hook import main as hook_main
|
|
7
|
+
from asiri.scan import scan
|
|
8
|
+
|
|
9
|
+
# Fake values built at runtime so this file never contains a real-looking key.
|
|
10
|
+
LIVE = "sk_" + "live_" + "51H" + "a" * 20
|
|
11
|
+
TEST = "sk_" + "test_" + "51H" + "b" * 20
|
|
12
|
+
ANTHROPIC = "sk-" + "ant-" + "api03-" + "c" * 30
|
|
13
|
+
OPENAI = "sk-" + "proj-" + "d" * 30
|
|
14
|
+
GH = "ghp_" + "e" * 36
|
|
15
|
+
AWS = "AKIA" + "F" * 16
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ScanTests(unittest.TestCase):
|
|
19
|
+
def kinds(self, text):
|
|
20
|
+
return [f.kind for f in scan(text)]
|
|
21
|
+
|
|
22
|
+
def test_detects_live_stripe_key(self):
|
|
23
|
+
self.assertEqual(self.kinds(f"key is {LIVE}"), ["stripe-live-key"])
|
|
24
|
+
|
|
25
|
+
def test_allows_test_stripe_key(self):
|
|
26
|
+
self.assertEqual(self.kinds(f"key is {TEST}"), [])
|
|
27
|
+
|
|
28
|
+
def test_anthropic_key_is_not_reported_as_openai(self):
|
|
29
|
+
self.assertEqual(self.kinds(ANTHROPIC), ["anthropic-key"])
|
|
30
|
+
|
|
31
|
+
def test_openai_project_key(self):
|
|
32
|
+
self.assertEqual(self.kinds(OPENAI), ["openai-key"])
|
|
33
|
+
|
|
34
|
+
def test_github_and_aws(self):
|
|
35
|
+
self.assertEqual(self.kinds(f"{GH} and {AWS}"), ["github-token", "aws-access-key"])
|
|
36
|
+
|
|
37
|
+
def test_private_key_header(self):
|
|
38
|
+
self.assertEqual(self.kinds("-----BEGIN RSA PRIVATE KEY-----"), ["private-key"])
|
|
39
|
+
|
|
40
|
+
def test_generic_assignment_reports_value_not_name(self):
|
|
41
|
+
value = "x" * 24
|
|
42
|
+
findings = scan(f'API_KEY = "{value}"')
|
|
43
|
+
self.assertEqual([f.kind for f in findings], ["generic-secret"])
|
|
44
|
+
self.assertEqual(findings[0].start, len('API_KEY = "'))
|
|
45
|
+
|
|
46
|
+
def test_snippet_never_contains_full_value(self):
|
|
47
|
+
findings = scan(f"key {LIVE}")
|
|
48
|
+
self.assertEqual(len(findings), 1)
|
|
49
|
+
self.assertNotIn(LIVE, findings[0].snippet)
|
|
50
|
+
self.assertIn("*", findings[0].snippet)
|
|
51
|
+
|
|
52
|
+
def test_plain_text_is_clean(self):
|
|
53
|
+
self.assertEqual(self.kinds("please fix the login bug in views.py"), [])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class HookTests(unittest.TestCase):
|
|
57
|
+
def run_hook(self, prompt):
|
|
58
|
+
stdin = io.StringIO(json.dumps({"prompt": prompt}))
|
|
59
|
+
stderr = io.StringIO()
|
|
60
|
+
with mock.patch("sys.stdin", stdin), mock.patch("sys.stderr", stderr):
|
|
61
|
+
code = hook_main()
|
|
62
|
+
return code, stderr.getvalue()
|
|
63
|
+
|
|
64
|
+
def test_blocks_live_key(self):
|
|
65
|
+
code, msg = self.run_hook(f"here: {LIVE}")
|
|
66
|
+
self.assertEqual(code, 2)
|
|
67
|
+
self.assertIn("stripe-live-key", msg)
|
|
68
|
+
self.assertNotIn(LIVE, msg)
|
|
69
|
+
|
|
70
|
+
def test_allows_clean_prompt(self):
|
|
71
|
+
code, msg = self.run_hook("fix the tests")
|
|
72
|
+
self.assertEqual(code, 0)
|
|
73
|
+
self.assertEqual(msg, "")
|
|
74
|
+
|
|
75
|
+
def test_malformed_input_fails_closed(self):
|
|
76
|
+
with mock.patch("sys.stdin", io.StringIO("not json")), mock.patch("sys.stderr", io.StringIO()):
|
|
77
|
+
self.assertEqual(hook_main(), 2)
|
|
78
|
+
|
|
79
|
+
def test_unexpected_error_fails_closed(self):
|
|
80
|
+
with mock.patch("asiri.hook.check_prompt", side_effect=RuntimeError("boom")), \
|
|
81
|
+
mock.patch("sys.stdin", io.StringIO('{"prompt": "hi"}')), \
|
|
82
|
+
mock.patch("sys.stderr", io.StringIO()) as stderr:
|
|
83
|
+
self.assertEqual(hook_main(), 2)
|
|
84
|
+
self.assertIn("RuntimeError", stderr.getvalue())
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class SelfTestAndInstallTests(unittest.TestCase):
|
|
88
|
+
def test_self_test_passes_for_working_hook(self):
|
|
89
|
+
from asiri import install
|
|
90
|
+
ok, detail = install.self_test() # runs the real hook with the current interpreter
|
|
91
|
+
self.assertTrue(ok, detail)
|
|
92
|
+
|
|
93
|
+
def test_self_test_fails_when_hook_lets_everything_through(self):
|
|
94
|
+
from asiri import install
|
|
95
|
+
ok, detail = install.self_test(command="/usr/bin/true")
|
|
96
|
+
self.assertFalse(ok)
|
|
97
|
+
self.assertIn("live key", detail)
|
|
98
|
+
|
|
99
|
+
def test_install_restores_settings_when_self_test_fails(self):
|
|
100
|
+
import json
|
|
101
|
+
import tempfile
|
|
102
|
+
from pathlib import Path
|
|
103
|
+
from asiri import install
|
|
104
|
+
|
|
105
|
+
original = {"model": "x", "hooks": {"UserPromptSubmit": [{"hooks": [{"type": "command", "command": "other-tool"}]}]}}
|
|
106
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
107
|
+
path = Path(tmp) / "settings.json"
|
|
108
|
+
path.write_text(json.dumps(original))
|
|
109
|
+
before = path.read_text()
|
|
110
|
+
with mock.patch.object(install, "self_test", return_value=(False, "forced failure")):
|
|
111
|
+
with self.assertRaises(RuntimeError):
|
|
112
|
+
install.install(path)
|
|
113
|
+
self.assertEqual(path.read_text(), before)
|
|
114
|
+
|
|
115
|
+
def test_install_removes_new_settings_file_when_self_test_fails(self):
|
|
116
|
+
import tempfile
|
|
117
|
+
from pathlib import Path
|
|
118
|
+
from asiri import install
|
|
119
|
+
|
|
120
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
121
|
+
path = Path(tmp) / "settings.json"
|
|
122
|
+
with mock.patch.object(install, "self_test", return_value=(False, "forced failure")):
|
|
123
|
+
with self.assertRaises(RuntimeError):
|
|
124
|
+
install.install(path)
|
|
125
|
+
self.assertFalse(path.exists())
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
if __name__ == "__main__":
|
|
129
|
+
unittest.main()
|