daemon-claim-audit 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.
- daemon_claim_audit-0.1.0/LICENSE +21 -0
- daemon_claim_audit-0.1.0/PKG-INFO +8 -0
- daemon_claim_audit-0.1.0/README.md +84 -0
- daemon_claim_audit-0.1.0/daemon_claim_audit/__init__.py +2 -0
- daemon_claim_audit-0.1.0/daemon_claim_audit/__main__.py +3 -0
- daemon_claim_audit-0.1.0/daemon_claim_audit/audit.py +144 -0
- daemon_claim_audit-0.1.0/daemon_claim_audit/cli.py +39 -0
- daemon_claim_audit-0.1.0/daemon_claim_audit/phrases.py +2 -0
- daemon_claim_audit-0.1.0/daemon_claim_audit.egg-info/PKG-INFO +8 -0
- daemon_claim_audit-0.1.0/daemon_claim_audit.egg-info/SOURCES.txt +14 -0
- daemon_claim_audit-0.1.0/daemon_claim_audit.egg-info/dependency_links.txt +1 -0
- daemon_claim_audit-0.1.0/daemon_claim_audit.egg-info/entry_points.txt +2 -0
- daemon_claim_audit-0.1.0/daemon_claim_audit.egg-info/top_level.txt +1 -0
- daemon_claim_audit-0.1.0/pyproject.toml +16 -0
- daemon_claim_audit-0.1.0/setup.cfg +4 -0
- daemon_claim_audit-0.1.0/tests/test_audit.py +178 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 daemon-claim-audit contributors
|
|
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,84 @@
|
|
|
1
|
+
# daemon-claim-audit
|
|
2
|
+
|
|
3
|
+
An offline static audit of documented detachment promises against Python AST and service unit evidence. Inspected programs are never executed. Requires Python 3.9 or later; runtime dependencies are entirely standard library.
|
|
4
|
+
|
|
5
|
+
## Use
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pip install daemon-claim-audit
|
|
9
|
+
daemon-claim-audit . --json
|
|
10
|
+
python3 -m daemon_claim_audit . --verbose
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
ROOT defaults to the current directory. Options: `--json`, `--verbose`, `--ignore GLOB ...`, `--fail-on HIGH|MEDIUM`, and `--version`. Ignore patterns use fnmatch on POSIX relative paths. Symlinks are skipped and environment files are never opened.
|
|
14
|
+
|
|
15
|
+
The scanner reads root README.md and Markdown beneath any docs directory. It excludes fenced blocks, retains inline code, normalizes case and hyphens, and joins paragraph lines. Negative spans are removed before positive matching. Each contradictory family produces one finding, preferring a non-test document. Test documents receive MEDIUM; other documents receive HIGH.
|
|
16
|
+
|
|
17
|
+
Exit codes: 0 means PASS at the chosen threshold; 2 means findings at that threshold; 1 means usage or input error. The default threshold is MEDIUM. HIGH leaves MEDIUM findings visible without failing. JSON includes status, evidence paths, claims, and findings. Text prints status and `RULE SEVERITY`; verbose adds the relative path.
|
|
18
|
+
|
|
19
|
+
Static evidence includes explicit true flags, attribute assignments, the legacy thread setter, subprocess session options, Unix session calls, imported library context calls, and service units containing both required directives. Evidence is project-wide. Test Python and service files are excluded. This is a syntactic heuristic, not a runtime guarantee: arbitrary calls with a true keyword can qualify, and unreachable calls qualify too. Import aliases are resolved syntactically; dynamic imports and runtime rebinding are not evaluated.
|
|
20
|
+
|
|
21
|
+
Rules and exact recognized phrases:
|
|
22
|
+
|
|
23
|
+
```text
|
|
24
|
+
documented-daemon-claim-false HIGH
|
|
25
|
+
documented-no-daemon-claim-false HIGH
|
|
26
|
+
|
|
27
|
+
DAEMON:
|
|
28
|
+
daemon mode
|
|
29
|
+
daemon support
|
|
30
|
+
supports daemon mode
|
|
31
|
+
supports daemon
|
|
32
|
+
runs as a daemon
|
|
33
|
+
run as a daemon
|
|
34
|
+
runs in the background
|
|
35
|
+
run in the background
|
|
36
|
+
runs in background
|
|
37
|
+
run in background
|
|
38
|
+
background mode
|
|
39
|
+
background support
|
|
40
|
+
supports background mode
|
|
41
|
+
runs as a background process
|
|
42
|
+
run as a background process
|
|
43
|
+
background process
|
|
44
|
+
background daemon
|
|
45
|
+
runs detached
|
|
46
|
+
run detached
|
|
47
|
+
detached mode
|
|
48
|
+
detaches from the terminal
|
|
49
|
+
detach from the terminal
|
|
50
|
+
keeps running after you close the terminal
|
|
51
|
+
keeps running after closing the terminal
|
|
52
|
+
continues running after you log out
|
|
53
|
+
continues running after logout
|
|
54
|
+
runs as a service
|
|
55
|
+
run as a service
|
|
56
|
+
systemd service
|
|
57
|
+
runs without a terminal
|
|
58
|
+
runs without a terminal attached
|
|
59
|
+
|
|
60
|
+
NODAEMON:
|
|
61
|
+
does not run as a daemon
|
|
62
|
+
does not run in the background
|
|
63
|
+
does not run in background
|
|
64
|
+
no daemon mode
|
|
65
|
+
no daemon support
|
|
66
|
+
no background mode
|
|
67
|
+
no background support
|
|
68
|
+
never runs in the background
|
|
69
|
+
never runs as a daemon
|
|
70
|
+
must be run in the foreground
|
|
71
|
+
foreground only
|
|
72
|
+
runs in the foreground only
|
|
73
|
+
run in the foreground only
|
|
74
|
+
does not detach
|
|
75
|
+
does not run detached
|
|
76
|
+
requires a terminal
|
|
77
|
+
must keep the terminal open
|
|
78
|
+
stops when you close the terminal
|
|
79
|
+
stops when the terminal closes
|
|
80
|
+
does not run as a service
|
|
81
|
+
no systemd service
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Develop locally with `python3 -m unittest discover` and `python3 -m build`. Licensed under MIT.
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Static documentation and source inspection; inspected code is never executed."""
|
|
2
|
+
import ast
|
|
3
|
+
import fnmatch
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
from .phrases import DAEMON, NODAEMON
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def normalize(text):
|
|
12
|
+
return ' '.join(text.lower().replace('-', ' ').split())
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _pattern(phrases):
|
|
16
|
+
return re.compile(r'(?<!\w)(?:' + '|'.join(re.escape(p) for p in
|
|
17
|
+
sorted(phrases, key=len, reverse=True)) + r')(?!\w)')
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
NEG_RE = _pattern(NODAEMON)
|
|
21
|
+
POS_RE = _pattern(DAEMON)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def families(text):
|
|
25
|
+
paragraphs = []
|
|
26
|
+
lines = []
|
|
27
|
+
fence = None
|
|
28
|
+
for line in text.splitlines():
|
|
29
|
+
match = re.match(r'^\s{0,3}(`{3,}|~{3,})', line)
|
|
30
|
+
if fence:
|
|
31
|
+
if re.match(r'^\s{0,3}' + re.escape(fence[0]) + '{' + str(len(fence)) + r',}\s*$', line):
|
|
32
|
+
fence = None
|
|
33
|
+
continue
|
|
34
|
+
if match:
|
|
35
|
+
fence = match.group(1)
|
|
36
|
+
paragraphs.append(normalize(' '.join(lines)))
|
|
37
|
+
lines = []
|
|
38
|
+
elif not line.strip():
|
|
39
|
+
paragraphs.append(normalize(' '.join(lines)))
|
|
40
|
+
lines = []
|
|
41
|
+
else:
|
|
42
|
+
lines.append(line)
|
|
43
|
+
paragraphs.append(normalize(' '.join(lines)))
|
|
44
|
+
found = set()
|
|
45
|
+
for paragraph in paragraphs:
|
|
46
|
+
spans = [(m.start(), m.end()) for m in NEG_RE.finditer(paragraph)]
|
|
47
|
+
if spans:
|
|
48
|
+
found.add('NODAEMON')
|
|
49
|
+
remaining = list(paragraph)
|
|
50
|
+
for start, end in spans:
|
|
51
|
+
remaining[start:end] = ' ' * (end - start)
|
|
52
|
+
if POS_RE.search(''.join(remaining)):
|
|
53
|
+
found.add('DAEMON')
|
|
54
|
+
return found
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def python_evidence(text, filename):
|
|
58
|
+
tree = ast.parse(text, filename=filename)
|
|
59
|
+
aliases = {}
|
|
60
|
+
library = False
|
|
61
|
+
for node in ast.walk(tree):
|
|
62
|
+
if isinstance(node, ast.Import):
|
|
63
|
+
for item in node.names:
|
|
64
|
+
aliases[item.asname or item.name.split('.')[0]] = item.name if item.asname else item.name.split('.')[0]
|
|
65
|
+
library |= item.name in ('daemon', 'daemonize')
|
|
66
|
+
elif isinstance(node, ast.ImportFrom):
|
|
67
|
+
for item in node.names:
|
|
68
|
+
aliases[item.asname or item.name] = (node.module or '') + '.' + item.name
|
|
69
|
+
library |= node.module in ('daemon', 'daemonize')
|
|
70
|
+
|
|
71
|
+
def dotted(node):
|
|
72
|
+
if isinstance(node, ast.Name):
|
|
73
|
+
return aliases.get(node.id, node.id)
|
|
74
|
+
if isinstance(node, ast.Attribute):
|
|
75
|
+
return dotted(node.value) + '.' + node.attr
|
|
76
|
+
return ''
|
|
77
|
+
|
|
78
|
+
def true(node):
|
|
79
|
+
return isinstance(node, ast.Constant) and node.value is True
|
|
80
|
+
|
|
81
|
+
for node in ast.walk(tree):
|
|
82
|
+
if isinstance(node, (ast.Assign, ast.AnnAssign)) and true(node.value):
|
|
83
|
+
targets = node.targets if isinstance(node, ast.Assign) else [node.target]
|
|
84
|
+
if any(isinstance(t, ast.Attribute) and t.attr == 'daemon' for t in targets):
|
|
85
|
+
return True
|
|
86
|
+
if not isinstance(node, ast.Call):
|
|
87
|
+
continue
|
|
88
|
+
name = dotted(node.func)
|
|
89
|
+
if any(k.arg == 'daemon' and true(k.value) for k in node.keywords):
|
|
90
|
+
return True
|
|
91
|
+
if isinstance(node.func, ast.Attribute) and node.func.attr == 'setDaemon' and node.args and true(node.args[0]):
|
|
92
|
+
return True
|
|
93
|
+
if name == 'os.setsid':
|
|
94
|
+
return True
|
|
95
|
+
if library and name in ('daemon.DaemonContext', 'daemonize.daemonize', 'daemon.daemonize'):
|
|
96
|
+
return True
|
|
97
|
+
if name == 'subprocess.Popen':
|
|
98
|
+
for kw in node.keywords:
|
|
99
|
+
if kw.arg == 'start_new_session' and true(kw.value):
|
|
100
|
+
return True
|
|
101
|
+
if kw.arg == 'creationflags' and any(isinstance(n, ast.Name) and n.id in ('DETACHED_PROCESS', 'CREATE_NEW_PROCESS_GROUP') for n in ast.walk(kw.value)):
|
|
102
|
+
return True
|
|
103
|
+
return False
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def audit(root, ignore=(), fail_on='MEDIUM'):
|
|
107
|
+
root = Path(root)
|
|
108
|
+
if not root.is_dir():
|
|
109
|
+
raise ValueError('ROOT must be a directory')
|
|
110
|
+
claims = []
|
|
111
|
+
evidence = []
|
|
112
|
+
paths = []
|
|
113
|
+
def walk_error(error):
|
|
114
|
+
raise error
|
|
115
|
+
for directory, dirs, files in os.walk(root, followlinks=False, onerror=walk_error):
|
|
116
|
+
dirs[:] = sorted(d for d in dirs if not (Path(directory) / d).is_symlink() and not any(fnmatch.fnmatchcase((Path(directory) / d).relative_to(root).as_posix(), g) for g in ignore))
|
|
117
|
+
for name in sorted(files):
|
|
118
|
+
path = Path(directory) / name
|
|
119
|
+
rel = path.relative_to(root)
|
|
120
|
+
if path.is_symlink() or name == '.env' or name.startswith('.env.'):
|
|
121
|
+
continue
|
|
122
|
+
if any(fnmatch.fnmatchcase(rel.as_posix(), g) for g in ignore):
|
|
123
|
+
continue
|
|
124
|
+
paths.append((rel, path))
|
|
125
|
+
for rel, path in sorted(paths):
|
|
126
|
+
doc = rel.as_posix() == 'README.md' or (rel.suffix == '.md' and 'docs' in rel.parts[:-1])
|
|
127
|
+
source = rel.suffix == '.py' and 'tests' not in rel.parts and not rel.name.startswith('test_')
|
|
128
|
+
service = rel.suffix == '.service' and 'tests' not in rel.parts
|
|
129
|
+
if not (doc or source or service):
|
|
130
|
+
continue
|
|
131
|
+
text = path.read_text(encoding='utf-8')
|
|
132
|
+
if doc:
|
|
133
|
+
for family in sorted(families(text)):
|
|
134
|
+
claims.append({'family': family, 'path': rel.as_posix(), 'severity': 'MEDIUM' if 'tests' in rel.parts else 'HIGH'})
|
|
135
|
+
if (source and python_evidence(text, str(path))) or (service and '[Service]' in text and 'ExecStart' in text):
|
|
136
|
+
evidence.append(rel.as_posix())
|
|
137
|
+
findings = []
|
|
138
|
+
for family, false in [('DAEMON', not evidence), ('NODAEMON', bool(evidence))]:
|
|
139
|
+
candidates = [c for c in claims if c['family'] == family]
|
|
140
|
+
if false and candidates:
|
|
141
|
+
claim = sorted(candidates, key=lambda c: (c['severity'] != 'HIGH', c['path']))[0]
|
|
142
|
+
findings.append({'rule': 'documented-' + ('daemon' if family == 'DAEMON' else 'no-daemon') + '-claim-false', 'severity': claim['severity'], 'path': claim['path']})
|
|
143
|
+
failed = any(f['severity'] == 'HIGH' or fail_on == 'MEDIUM' for f in findings)
|
|
144
|
+
return {'status': 'FAIL' if failed else 'PASS', 'evidence': evidence, 'claims': claims, 'findings': findings}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Command line interface."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from . import __version__
|
|
7
|
+
from .audit import audit
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Parser(argparse.ArgumentParser):
|
|
11
|
+
def error(self, message):
|
|
12
|
+
self.print_usage(sys.stderr)
|
|
13
|
+
self.exit(1, self.prog + ': error: ' + message + '\n')
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main(argv=None):
|
|
17
|
+
parser = Parser(prog='daemon-claim-audit')
|
|
18
|
+
parser.add_argument('root', nargs='?', default='.')
|
|
19
|
+
parser.add_argument('--json', action='store_true')
|
|
20
|
+
parser.add_argument('--verbose', action='store_true')
|
|
21
|
+
parser.add_argument('--ignore', nargs='+', action='extend', default=[])
|
|
22
|
+
parser.add_argument('--fail-on', choices=['HIGH', 'MEDIUM'], default='MEDIUM')
|
|
23
|
+
parser.add_argument('--version', action='version', version=__version__)
|
|
24
|
+
try:
|
|
25
|
+
args = parser.parse_args(argv)
|
|
26
|
+
except SystemExit as error:
|
|
27
|
+
return error.code
|
|
28
|
+
try:
|
|
29
|
+
result = audit(args.root, args.ignore, args.fail_on)
|
|
30
|
+
except (OSError, ValueError, SyntaxError) as error:
|
|
31
|
+
print('error: ' + str(error), file=sys.stderr)
|
|
32
|
+
return 1
|
|
33
|
+
if args.json:
|
|
34
|
+
print(json.dumps(result, sort_keys=True))
|
|
35
|
+
else:
|
|
36
|
+
print(result['status'])
|
|
37
|
+
for finding in result['findings']:
|
|
38
|
+
print(finding['rule'] + ' ' + finding['severity'] + (' ' + finding['path'] if args.verbose else ''))
|
|
39
|
+
return 2 if result['status'] == 'FAIL' else 0
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
DAEMON = ('daemon mode', 'daemon support', 'supports daemon mode', 'supports daemon', 'runs as a daemon', 'run as a daemon', 'runs in the background', 'run in the background', 'runs in background', 'run in background', 'background mode', 'background support', 'supports background mode', 'runs as a background process', 'run as a background process', 'background process', 'background daemon', 'runs detached', 'run detached', 'detached mode', 'detaches from the terminal', 'detach from the terminal', 'keeps running after you close the terminal', 'keeps running after closing the terminal', 'continues running after you log out', 'continues running after logout', 'runs as a service', 'run as a service', 'systemd service', 'runs without a terminal', 'runs without a terminal attached')
|
|
2
|
+
NODAEMON = ('does not run as a daemon', 'does not run in the background', 'does not run in background', 'no daemon mode', 'no daemon support', 'no background mode', 'no background support', 'never runs in the background', 'never runs as a daemon', 'must be run in the foreground', 'foreground only', 'runs in the foreground only', 'run in the foreground only', 'does not detach', 'does not run detached', 'requires a terminal', 'must keep the terminal open', 'stops when you close the terminal', 'stops when the terminal closes', 'does not run as a service', 'no systemd service')
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
daemon_claim_audit/__init__.py
|
|
5
|
+
daemon_claim_audit/__main__.py
|
|
6
|
+
daemon_claim_audit/audit.py
|
|
7
|
+
daemon_claim_audit/cli.py
|
|
8
|
+
daemon_claim_audit/phrases.py
|
|
9
|
+
daemon_claim_audit.egg-info/PKG-INFO
|
|
10
|
+
daemon_claim_audit.egg-info/SOURCES.txt
|
|
11
|
+
daemon_claim_audit.egg-info/dependency_links.txt
|
|
12
|
+
daemon_claim_audit.egg-info/entry_points.txt
|
|
13
|
+
daemon_claim_audit.egg-info/top_level.txt
|
|
14
|
+
tests/test_audit.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
daemon_claim_audit
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "daemon-claim-audit"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Offline static audit of documented detachment promises"
|
|
9
|
+
requires-python = ">=3.9"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
|
|
12
|
+
[project.scripts]
|
|
13
|
+
daemon-claim-audit = "daemon_claim_audit.cli:main"
|
|
14
|
+
|
|
15
|
+
[tool.setuptools.packages.find]
|
|
16
|
+
include = ["daemon_claim_audit*"]
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import io
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
import unittest
|
|
9
|
+
from unittest.mock import patch
|
|
10
|
+
|
|
11
|
+
from daemon_claim_audit.audit import audit, families
|
|
12
|
+
from daemon_claim_audit.cli import main
|
|
13
|
+
from daemon_claim_audit.phrases import DAEMON, NODAEMON
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AuditTests(unittest.TestCase):
|
|
17
|
+
def setUp(self):
|
|
18
|
+
self.temp = tempfile.TemporaryDirectory()
|
|
19
|
+
self.addCleanup(self.temp.cleanup)
|
|
20
|
+
self.root = Path(self.temp.name)
|
|
21
|
+
|
|
22
|
+
def write(self, name, text):
|
|
23
|
+
path = self.root / name
|
|
24
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
25
|
+
path.write_text(text)
|
|
26
|
+
return path
|
|
27
|
+
|
|
28
|
+
def cli(self, *args):
|
|
29
|
+
out, err = io.StringIO(), io.StringIO()
|
|
30
|
+
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
|
31
|
+
code = main([str(self.root)] + list(args))
|
|
32
|
+
return code, out.getvalue(), err.getvalue()
|
|
33
|
+
|
|
34
|
+
def test_bad_exact(self):
|
|
35
|
+
self.write('README.md', 'runs in the background')
|
|
36
|
+
code, out, _ = self.cli()
|
|
37
|
+
self.assertEqual((code, out), (2, 'FAIL\ndocumented-daemon-claim-false HIGH\n'))
|
|
38
|
+
|
|
39
|
+
def test_negative_exact(self):
|
|
40
|
+
self.write('README.md', 'does not run as a daemon')
|
|
41
|
+
self.write('app.py', 'f(daemon=True)')
|
|
42
|
+
self.assertEqual(audit(self.root)['findings'], [{'rule': 'documented-no-daemon-claim-false', 'severity': 'HIGH', 'path': 'README.md'}])
|
|
43
|
+
|
|
44
|
+
def test_no_source(self):
|
|
45
|
+
self.write('README.md', 'no daemon mode')
|
|
46
|
+
self.assertEqual(audit(self.root)['status'], 'PASS')
|
|
47
|
+
self.write('README.md', 'daemon mode')
|
|
48
|
+
self.assertEqual(audit(self.root)['findings'][0]['severity'], 'HIGH')
|
|
49
|
+
|
|
50
|
+
def test_fences_inline_wrapping(self):
|
|
51
|
+
for text, expected in [('```text\ndaemon mode\n```', set()), ('~~~\ndaemon mode\n~~~', set()), ('`daemon mode`', {'DAEMON'}), ('runs in the\nbackground', {'DAEMON'}), ('runs in the\n\nbackground', set()), ('background-mode', {'DAEMON'}), ('the daemon handles requests; background jobs', set())]:
|
|
52
|
+
with self.subTest(text=text):
|
|
53
|
+
self.assertEqual(families(text), expected)
|
|
54
|
+
|
|
55
|
+
def test_word_boundaries(self):
|
|
56
|
+
for text in ('daemon model', 'daemon modes', 'background processes',
|
|
57
|
+
'a background processing job', 'daemonmodel'):
|
|
58
|
+
with self.subTest(text=text):
|
|
59
|
+
self.assertEqual(families(text), set())
|
|
60
|
+
self.assertEqual(families('runs in the background.'), {'DAEMON'})
|
|
61
|
+
|
|
62
|
+
def test_spans(self):
|
|
63
|
+
for phrase in NODAEMON:
|
|
64
|
+
self.assertEqual(families(phrase), {'NODAEMON'})
|
|
65
|
+
self.assertEqual(families('no daemon mode; runs detached'), {'NODAEMON', 'DAEMON'})
|
|
66
|
+
|
|
67
|
+
def test_medium_priority(self):
|
|
68
|
+
self.write('tests/docs/a.md', 'daemon mode')
|
|
69
|
+
self.assertEqual(self.cli()[0], 2)
|
|
70
|
+
code, out, _ = self.cli('--fail-on', 'HIGH', '--json')
|
|
71
|
+
self.assertEqual(code, 0)
|
|
72
|
+
self.assertEqual(json.loads(out)['findings'][0]['severity'], 'MEDIUM')
|
|
73
|
+
self.write('docs/z.md', 'daemon mode')
|
|
74
|
+
self.write('docs/y.md', 'daemon mode')
|
|
75
|
+
result = audit(self.root)
|
|
76
|
+
self.assertEqual(len(result['findings']), 1)
|
|
77
|
+
self.assertEqual(result['findings'][0]['path'], 'docs/y.md')
|
|
78
|
+
|
|
79
|
+
def test_ignore(self):
|
|
80
|
+
self.write('README.md', 'daemon mode')
|
|
81
|
+
self.write('app.py', 'f(daemon=True)')
|
|
82
|
+
self.assertEqual(self.cli('--ignore', '*.py')[0], 2)
|
|
83
|
+
self.assertEqual(self.cli('--ignore', 'README.md')[0], 0)
|
|
84
|
+
|
|
85
|
+
def test_errors(self):
|
|
86
|
+
self.write('app.py', 'def :')
|
|
87
|
+
self.assertEqual(self.cli()[0], 1)
|
|
88
|
+
self.assertEqual(main([str(self.root / 'missing')]), 1)
|
|
89
|
+
self.assertEqual(self.cli('--invalid')[0], 1)
|
|
90
|
+
self.assertEqual(self.cli('--fail-on', 'LOW')[0], 1)
|
|
91
|
+
|
|
92
|
+
def test_unreadable(self):
|
|
93
|
+
self.write('README.md', 'hello')
|
|
94
|
+
with patch.object(Path, 'read_text', side_effect=PermissionError('unreadable')):
|
|
95
|
+
self.assertEqual(self.cli()[0], 1)
|
|
96
|
+
|
|
97
|
+
def test_env_never_opened(self):
|
|
98
|
+
self.write('.env', 'daemon mode ENV_GUARD_MARKER')
|
|
99
|
+
original = Path.read_text
|
|
100
|
+
def guarded(path, *args, **kwargs):
|
|
101
|
+
self.assertNotEqual(path.name, '.env')
|
|
102
|
+
return original(path, *args, **kwargs)
|
|
103
|
+
with patch.object(Path, 'read_text', guarded):
|
|
104
|
+
code, out, err = self.cli('--json')
|
|
105
|
+
self.assertEqual(code, 0)
|
|
106
|
+
self.assertNotIn('ENV_GUARD_MARKER', out + err)
|
|
107
|
+
|
|
108
|
+
def test_symlinks(self):
|
|
109
|
+
outside = self.write('outside.txt', 'daemon mode')
|
|
110
|
+
(self.root / 'README.md').symlink_to(outside)
|
|
111
|
+
(self.root / 'docs').symlink_to(self.root, target_is_directory=True)
|
|
112
|
+
self.assertEqual(audit(self.root)['claims'], [])
|
|
113
|
+
|
|
114
|
+
def test_json_verbose_version_module(self):
|
|
115
|
+
self.write('README.md', 'daemon mode')
|
|
116
|
+
result = json.loads(self.cli('--json')[1])
|
|
117
|
+
self.assertEqual(set(result), {'status', 'evidence', 'claims', 'findings'})
|
|
118
|
+
self.assertIn('HIGH README.md', self.cli('--verbose')[1])
|
|
119
|
+
self.assertEqual(self.cli('--fail-on', 'MEDIUM')[0], 2)
|
|
120
|
+
run = subprocess.run([sys.executable, '-m', 'daemon_claim_audit', '--version'], capture_output=True, text=True)
|
|
121
|
+
self.assertEqual((run.returncode, run.stdout.strip()), (0, '0.1.0'))
|
|
122
|
+
|
|
123
|
+
def test_self_audit(self):
|
|
124
|
+
result = audit(Path(__file__).resolve().parents[1])
|
|
125
|
+
self.assertEqual((result['status'], result['claims']), ('PASS', []))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def evidence_test(source, expected, name='app.py'):
|
|
129
|
+
def test(self):
|
|
130
|
+
self.write('README.md', 'daemon mode')
|
|
131
|
+
self.write(name, source)
|
|
132
|
+
result = audit(self.root)
|
|
133
|
+
self.assertEqual(bool(result['evidence']), expected)
|
|
134
|
+
self.assertEqual(result['status'], 'PASS' if expected else 'FAIL')
|
|
135
|
+
return test
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
GOOD = [
|
|
139
|
+
'f(daemon=True)', 't.daemon = True', 't.daemon: bool = True',
|
|
140
|
+
't.setDaemon(True)',
|
|
141
|
+
'import subprocess as sp\nsp.Popen([], start_new_session=True)',
|
|
142
|
+
'from subprocess import Popen as P\nP([], creationflags=DETACHED_PROCESS)',
|
|
143
|
+
'import subprocess\nsubprocess.Popen([], creationflags=CREATE_NEW_PROCESS_GROUP | 1)',
|
|
144
|
+
'import os as o\no.setsid()',
|
|
145
|
+
'from os import fork, setsid\ndef f():\n fork()\n setsid()',
|
|
146
|
+
'import daemon as d\nd.DaemonContext()',
|
|
147
|
+
'from daemon import DaemonContext as D\nD()',
|
|
148
|
+
'import daemonize as d\nd.daemonize()',
|
|
149
|
+
'from daemonize import daemonize as d\nd()',
|
|
150
|
+
'import daemon\ndaemon.daemonize()',
|
|
151
|
+
]
|
|
152
|
+
BAD = [
|
|
153
|
+
'import daemon', 'import daemonize', 'f(daemon=False)', 't.daemon=False',
|
|
154
|
+
't.setDaemon(False)', 'import subprocess\nsubprocess.Popen([], start_new_session=False)',
|
|
155
|
+
'import subprocess\nsubprocess.Popen([])', 'import os\nos.fork()',
|
|
156
|
+
'from threading import Thread\nThread()',
|
|
157
|
+
'def daemonize():\n pass\ndaemonize()',
|
|
158
|
+
'"os.setsid()"\n# f(daemon=True)',
|
|
159
|
+
'import signal\nsignal.signal(2, lambda: None)',
|
|
160
|
+
'while True:\n pass',
|
|
161
|
+
]
|
|
162
|
+
for index, source in enumerate(GOOD):
|
|
163
|
+
setattr(AuditTests, 'test_evidence_%02d' % index, evidence_test(source, True))
|
|
164
|
+
for index, source in enumerate(BAD):
|
|
165
|
+
setattr(AuditTests, 'test_not_evidence_%02d' % index, evidence_test(source, False))
|
|
166
|
+
for index, (name, text, expected) in enumerate([
|
|
167
|
+
('worker.service', '[Service]\nExecStart=/bin/true', True),
|
|
168
|
+
('worker.service', '[Service]', False),
|
|
169
|
+
('worker.service', 'ExecStart=/bin/true', False),
|
|
170
|
+
('tests/worker.service', '[Service]\nExecStart=/bin/true', False),
|
|
171
|
+
('tests/app.py', 'f(daemon=True)', False),
|
|
172
|
+
('test_app.py', 'f(daemon=True)', False),
|
|
173
|
+
]):
|
|
174
|
+
setattr(AuditTests, 'test_file_evidence_%02d' % index, evidence_test(text, expected, name))
|
|
175
|
+
for index, phrase in enumerate(DAEMON):
|
|
176
|
+
def test(self, phrase=phrase):
|
|
177
|
+
self.assertEqual(families(phrase.upper()), {'DAEMON'})
|
|
178
|
+
setattr(AuditTests, 'test_phrase_%02d' % index, test)
|