nfc-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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nfc-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,2 @@
1
+ include README.md LICENSE
2
+ recursive-include tests *.py *.md .env
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: nfc-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline static audit of documented tag capability
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # nfc-claim-audit
12
+
13
+ Version 0.1.0. An offline static checker comparing documented tap-to-tag
14
+ capability with Python AST evidence. Audited source is never executed.
15
+ Requires Python 3.9 or later; no runtime dependencies.
16
+
17
+ ```sh
18
+ python3 -m pip install .
19
+ nfc-claim-audit . --json
20
+ python3 -m nfc_claim_audit . --verbose
21
+ python3 -m unittest discover
22
+ python3 -m build
23
+ ```
24
+
25
+ The positional directory defaults to the current directory. Repeat `--ignore`
26
+ with root-relative globs to omit files. `--version` prints the version.
27
+ JSON output contains verdict, findings (rule, severity, message), and a scanned
28
+ file count. Human output prints the same verdict and findings.
29
+
30
+ The following rules report contradictions between prose and source.
31
+
32
+ ```text
33
+ documented-nfc-claim-false
34
+ documented-no-nfc-claim-false
35
+ ```
36
+
37
+ Production absence yields HIGH;
38
+ evidence confined to test files yields MEDIUM for a positive assertion.
39
+ The default HIGH threshold reports MEDIUM findings with exit 0;
40
+ `--fail-on MEDIUM` makes them exit 2. HIGH findings exit 2. Invalid or
41
+ unreadable paths exit 1. No detected assertion yields PASS and exit 0.
42
+ A positive assertion without any source yields HIGH; an absence assertion
43
+ without source passes. There is at most one finding per family.
44
+
45
+ Documentation includes root README.md and Markdown files beneath any docs
46
+ path component. Fenced blocks are excluded; inline code counts. Matching
47
+ lowercases, expands contracted negation, replaces hyphens with spaces, and
48
+ joins whitespace within blank-line-separated paragraphs. Absence spans are
49
+ removed before positive matching. Exact templates and word boundaries are
50
+ used; the complete templates are in `nfc_claim_audit/phrases.py`.
51
+
52
+ Source includes .py files except tests, test-prefixed or test-suffixed files,
53
+ fixtures, docs, examples, and symlinks. Test evidence is considered separately.
54
+ Alias-resolved nfcpy ContactlessFrontend instantiation is sufficient evidence;
55
+ opening the device counts without a subsequent connect. Bound, self-attribute,
56
+ with-target, and chained connection patterns therefore count as well. Local
57
+ class or function definitions shadow imported names.
58
+
59
+ ## Limitations
60
+
61
+ Only exact templates are recognized. A bare NFC word, user instructions to hold
62
+ or tap a card, Bluetooth or USB reach, printing, and file exports do not make
63
+ an assertion for this checker. Imports, identifiers, NDEF objects, decorators,
64
+ and logging-only functions do not demonstrate a frontend operation.
65
+ System tag helpers invoked through subprocesses are not counted: shell command
66
+ strings are not AST evidence. Other NFC stacks, including Android NFC and
67
+ PC/SC smartcard readers, are out of scope; only nfcpy frontends are counted.
68
+ Static evidence cannot establish hardware availability or successful runtime
69
+ behavior. This is module-level import resolution, not control-flow analysis;
70
+ unparseable source provides no evidence. Environment files are never opened.
@@ -0,0 +1,60 @@
1
+ # nfc-claim-audit
2
+
3
+ Version 0.1.0. An offline static checker comparing documented tap-to-tag
4
+ capability with Python AST evidence. Audited source is never executed.
5
+ Requires Python 3.9 or later; no runtime dependencies.
6
+
7
+ ```sh
8
+ python3 -m pip install .
9
+ nfc-claim-audit . --json
10
+ python3 -m nfc_claim_audit . --verbose
11
+ python3 -m unittest discover
12
+ python3 -m build
13
+ ```
14
+
15
+ The positional directory defaults to the current directory. Repeat `--ignore`
16
+ with root-relative globs to omit files. `--version` prints the version.
17
+ JSON output contains verdict, findings (rule, severity, message), and a scanned
18
+ file count. Human output prints the same verdict and findings.
19
+
20
+ The following rules report contradictions between prose and source.
21
+
22
+ ```text
23
+ documented-nfc-claim-false
24
+ documented-no-nfc-claim-false
25
+ ```
26
+
27
+ Production absence yields HIGH;
28
+ evidence confined to test files yields MEDIUM for a positive assertion.
29
+ The default HIGH threshold reports MEDIUM findings with exit 0;
30
+ `--fail-on MEDIUM` makes them exit 2. HIGH findings exit 2. Invalid or
31
+ unreadable paths exit 1. No detected assertion yields PASS and exit 0.
32
+ A positive assertion without any source yields HIGH; an absence assertion
33
+ without source passes. There is at most one finding per family.
34
+
35
+ Documentation includes root README.md and Markdown files beneath any docs
36
+ path component. Fenced blocks are excluded; inline code counts. Matching
37
+ lowercases, expands contracted negation, replaces hyphens with spaces, and
38
+ joins whitespace within blank-line-separated paragraphs. Absence spans are
39
+ removed before positive matching. Exact templates and word boundaries are
40
+ used; the complete templates are in `nfc_claim_audit/phrases.py`.
41
+
42
+ Source includes .py files except tests, test-prefixed or test-suffixed files,
43
+ fixtures, docs, examples, and symlinks. Test evidence is considered separately.
44
+ Alias-resolved nfcpy ContactlessFrontend instantiation is sufficient evidence;
45
+ opening the device counts without a subsequent connect. Bound, self-attribute,
46
+ with-target, and chained connection patterns therefore count as well. Local
47
+ class or function definitions shadow imported names.
48
+
49
+ ## Limitations
50
+
51
+ Only exact templates are recognized. A bare NFC word, user instructions to hold
52
+ or tap a card, Bluetooth or USB reach, printing, and file exports do not make
53
+ an assertion for this checker. Imports, identifiers, NDEF objects, decorators,
54
+ and logging-only functions do not demonstrate a frontend operation.
55
+ System tag helpers invoked through subprocesses are not counted: shell command
56
+ strings are not AST evidence. Other NFC stacks, including Android NFC and
57
+ PC/SC smartcard readers, are out of scope; only nfcpy frontends are counted.
58
+ Static evidence cannot establish hardware availability or successful runtime
59
+ behavior. This is module-level import resolution, not control-flow analysis;
60
+ unparseable source provides no evidence. Environment files are never opened.
@@ -0,0 +1,2 @@
1
+ """Static documentation audit."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,33 @@
1
+ """Command line interface."""
2
+ import argparse
3
+ import json
4
+ from . import __version__
5
+ from .audit import audit
6
+
7
+
8
+ def main(argv=None):
9
+ parser = argparse.ArgumentParser(description='Audit documented tag capability against static source evidence.')
10
+ parser.add_argument('root', nargs='?', default='.')
11
+ parser.add_argument('--json', action='store_true')
12
+ parser.add_argument('--verbose', action='store_true')
13
+ parser.add_argument('--ignore', action='append', default=[])
14
+ parser.add_argument('--fail-on', choices=['HIGH', 'MEDIUM'], default='HIGH')
15
+ parser.add_argument('--version', action='version', version=__version__)
16
+ args = parser.parse_args(argv)
17
+ try:
18
+ result = audit(args.root, args.ignore, args.fail_on)
19
+ except (ValueError, OSError, UnicodeError) as exc:
20
+ parser.exit(1, str(exc) + '\n')
21
+ if args.json:
22
+ print(json.dumps(result))
23
+ else:
24
+ print(result['verdict'])
25
+ for finding in result['findings']:
26
+ print('{severity} {rule}: {message}'.format(**finding))
27
+ if args.verbose:
28
+ print('Files scanned:', result['files_scanned'])
29
+ return 2 if result['verdict'] == 'FAIL' else 0
30
+
31
+
32
+ if __name__ == '__main__':
33
+ raise SystemExit(main())
@@ -0,0 +1,98 @@
1
+ """Read documentation and parse source without executing it."""
2
+ import ast
3
+ import fnmatch
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ from .phrases import NFC, NONFC
8
+
9
+
10
+ def claims(text):
11
+ lines = []
12
+ fence = None
13
+ for line in text.splitlines():
14
+ match = re.match(r"^ {0,3}(`{3,}|~{3,})", line)
15
+ if fence:
16
+ if match and match[1][0] == fence[0] and len(match[1]) >= len(fence):
17
+ fence = None
18
+ lines.append("")
19
+ elif match:
20
+ fence = match[1]
21
+ lines.append("")
22
+ else:
23
+ lines.append(line)
24
+ positive = negative = False
25
+ for paragraph in re.split(r"\n\s*\n", "\n".join(lines)):
26
+ paragraph = re.sub(r"\s+", " ", paragraph.lower().replace("n't", " not").replace("-", " "))
27
+ for phrase in NONFC:
28
+ paragraph, count = re.subn(r"\b" + re.escape(phrase) + r"\b", " ", paragraph)
29
+ negative |= bool(count)
30
+ positive |= any(re.search(r"\b" + re.escape(p) + r"\b", paragraph) for p in NFC)
31
+ return bool(positive), bool(negative)
32
+
33
+
34
+ def evidence(text):
35
+ try:
36
+ tree = ast.parse(text)
37
+ except (SyntaxError, ValueError):
38
+ return False
39
+ imports = {}
40
+ shadows = set()
41
+ for node in ast.walk(tree):
42
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
43
+ shadows.add(node.name)
44
+ elif isinstance(node, ast.Import):
45
+ for alias in node.names:
46
+ imports[alias.asname or alias.name.split('.')[0]] = alias.name if alias.asname else alias.name.split('.')[0]
47
+ elif isinstance(node, ast.ImportFrom):
48
+ for alias in node.names:
49
+ imports[alias.asname or alias.name] = ((node.module or '') + '.' + alias.name) if not node.level else ''
50
+ def resolve(node):
51
+ if isinstance(node, ast.Name):
52
+ return '' if node.id in shadows else imports.get(node.id, '')
53
+ if isinstance(node, ast.Attribute):
54
+ base = resolve(node.value)
55
+ return base + '.' + node.attr if base else ''
56
+ return ''
57
+ return any(isinstance(n, ast.Call) and resolve(n.func).startswith('nfc.')
58
+ and resolve(n.func).split('.')[-1] == 'ContactlessFrontend'
59
+ for n in ast.walk(tree))
60
+
61
+
62
+ def audit(root, ignore=(), fail_on='HIGH'):
63
+ root = Path(root)
64
+ if not root.is_dir():
65
+ raise ValueError('root must be a readable directory')
66
+ if not os.access(root, os.R_OK | os.X_OK):
67
+ raise ValueError('root must be a readable directory')
68
+ positive = negative = prod = test = False
69
+ scanned = 0
70
+ for directory, dirs, files in os.walk(root, followlinks=False):
71
+ dirs[:] = sorted(d for d in dirs if not (Path(directory) / d).is_symlink())
72
+ for name in sorted(files):
73
+ path = Path(directory) / name
74
+ rel = path.relative_to(root)
75
+ if path.is_symlink() or any(fnmatch.fnmatchcase(rel.as_posix(), g) for g in ignore):
76
+ continue
77
+ is_doc = path.suffix.lower() == '.md' and (rel.as_posix() == 'README.md' or 'docs' in rel.parts[:-1])
78
+ is_source = path.suffix == '.py' and not any(p in ('fixtures', 'docs', 'examples') for p in rel.parts[:-1])
79
+ if not (is_doc or is_source):
80
+ continue
81
+ text = path.read_text(encoding='utf-8')
82
+ scanned += 1
83
+ if is_doc:
84
+ p, n = claims(text)
85
+ positive |= p
86
+ negative |= n
87
+ if is_source and evidence(text):
88
+ if 'tests' in rel.parts[:-1] or name.startswith('test_') or name.endswith('_test.py'):
89
+ test = True
90
+ else:
91
+ prod = True
92
+ findings = []
93
+ if positive and not prod:
94
+ findings.append(dict(rule='documented-nfc-claim-false', severity='MEDIUM' if test else 'HIGH', message='Documented tag capability lacks production frontend evidence.'))
95
+ if negative and prod:
96
+ findings.append(dict(rule='documented-no-nfc-claim-false', severity='HIGH', message='Documented absence conflicts with production frontend evidence.'))
97
+ failed = any(f['severity'] == 'HIGH' or fail_on == 'MEDIUM' for f in findings)
98
+ return dict(verdict='FAIL' if failed else 'PASS', findings=findings, files_scanned=scanned)
@@ -0,0 +1,3 @@
1
+ """Exact documentation templates."""
2
+ NFC = ('reads data from nfc tags', 'read data from nfc tags', 'writes data to nfc tags', 'write data to nfc tags', 'transfers data via nfc', 'communicates over nfc', 'transfer data via nfc', 'receives data via nfc', 'connects to nfc tags', 'communicates via nfc', 'communicate over nfc', 'receive data via nfc', 'connect to nfc tags', 'communicate via nfc', 'reads from nfc tags', 'read from nfc tags', 'writes to nfc tags', 'sends data via nfc', 'write to nfc tags', 'send data via nfc', 'supports nfc tags', 'connects via nfc', 'nfc connectivity', 'support nfc tags', 'connect via nfc', 'writes nfc tags', 'nfc tag support', 'reads nfc tags', 'write nfc tags', 'read nfc tags', 'uses nfc tags', 'supports nfc', 'use nfc tags', 'support nfc', 'writes nfc', 'reads nfc', 'write nfc', 'read nfc', 'uses nfc', 'use nfc')
3
+ NONFC = ('does not transfer data via nfc', 'does not communicate over nfc', 'does not receive data via nfc', 'does not connect to nfc tags', 'does not communicate via nfc', 'does not read from nfc tags', 'does not write to nfc tags', 'does not send data via nfc', 'does not support nfc tags', 'does not connect via nfc', 'without nfc connectivity', 'does not write nfc tags', 'without nfc tag support', 'does not read nfc tags', 'does not use nfc tags', 'nfc tag not supported', 'does not support nfc', 'without nfc support', 'no nfc connectivity', 'no nfc tag support', 'nfc not supported', 'does not use nfc', 'no nfc support', 'without nfc', 'no nfc')
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: nfc-claim-audit
3
+ Version: 0.1.0
4
+ Summary: Offline static audit of documented tag capability
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # nfc-claim-audit
12
+
13
+ Version 0.1.0. An offline static checker comparing documented tap-to-tag
14
+ capability with Python AST evidence. Audited source is never executed.
15
+ Requires Python 3.9 or later; no runtime dependencies.
16
+
17
+ ```sh
18
+ python3 -m pip install .
19
+ nfc-claim-audit . --json
20
+ python3 -m nfc_claim_audit . --verbose
21
+ python3 -m unittest discover
22
+ python3 -m build
23
+ ```
24
+
25
+ The positional directory defaults to the current directory. Repeat `--ignore`
26
+ with root-relative globs to omit files. `--version` prints the version.
27
+ JSON output contains verdict, findings (rule, severity, message), and a scanned
28
+ file count. Human output prints the same verdict and findings.
29
+
30
+ The following rules report contradictions between prose and source.
31
+
32
+ ```text
33
+ documented-nfc-claim-false
34
+ documented-no-nfc-claim-false
35
+ ```
36
+
37
+ Production absence yields HIGH;
38
+ evidence confined to test files yields MEDIUM for a positive assertion.
39
+ The default HIGH threshold reports MEDIUM findings with exit 0;
40
+ `--fail-on MEDIUM` makes them exit 2. HIGH findings exit 2. Invalid or
41
+ unreadable paths exit 1. No detected assertion yields PASS and exit 0.
42
+ A positive assertion without any source yields HIGH; an absence assertion
43
+ without source passes. There is at most one finding per family.
44
+
45
+ Documentation includes root README.md and Markdown files beneath any docs
46
+ path component. Fenced blocks are excluded; inline code counts. Matching
47
+ lowercases, expands contracted negation, replaces hyphens with spaces, and
48
+ joins whitespace within blank-line-separated paragraphs. Absence spans are
49
+ removed before positive matching. Exact templates and word boundaries are
50
+ used; the complete templates are in `nfc_claim_audit/phrases.py`.
51
+
52
+ Source includes .py files except tests, test-prefixed or test-suffixed files,
53
+ fixtures, docs, examples, and symlinks. Test evidence is considered separately.
54
+ Alias-resolved nfcpy ContactlessFrontend instantiation is sufficient evidence;
55
+ opening the device counts without a subsequent connect. Bound, self-attribute,
56
+ with-target, and chained connection patterns therefore count as well. Local
57
+ class or function definitions shadow imported names.
58
+
59
+ ## Limitations
60
+
61
+ Only exact templates are recognized. A bare NFC word, user instructions to hold
62
+ or tap a card, Bluetooth or USB reach, printing, and file exports do not make
63
+ an assertion for this checker. Imports, identifiers, NDEF objects, decorators,
64
+ and logging-only functions do not demonstrate a frontend operation.
65
+ System tag helpers invoked through subprocesses are not counted: shell command
66
+ strings are not AST evidence. Other NFC stacks, including Android NFC and
67
+ PC/SC smartcard readers, are out of scope; only nfcpy frontends are counted.
68
+ Static evidence cannot establish hardware availability or successful runtime
69
+ behavior. This is module-level import resolution, not control-flow analysis;
70
+ unparseable source provides no evidence. Environment files are never opened.
@@ -0,0 +1,25 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ nfc_claim_audit/__init__.py
6
+ nfc_claim_audit/__main__.py
7
+ nfc_claim_audit/audit.py
8
+ nfc_claim_audit/phrases.py
9
+ nfc_claim_audit.egg-info/PKG-INFO
10
+ nfc_claim_audit.egg-info/SOURCES.txt
11
+ nfc_claim_audit.egg-info/dependency_links.txt
12
+ nfc_claim_audit.egg-info/entry_points.txt
13
+ nfc_claim_audit.egg-info/top_level.txt
14
+ tests/__init__.py
15
+ tests/cases.py
16
+ tests/test_audit.py
17
+ tests/fixtures/.env
18
+ tests/fixtures/bad/README.md
19
+ tests/fixtures/bad/app.py
20
+ tests/fixtures/good/README.md
21
+ tests/fixtures/good/app.py
22
+ tests/fixtures/no-nfc/README.md
23
+ tests/fixtures/no-nfc/app.py
24
+ tests/fixtures/testonly/README.md
25
+ tests/fixtures/testonly/tests/test_device.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ nfc-claim-audit = nfc_claim_audit.__main__:main
@@ -0,0 +1 @@
1
+ nfc_claim_audit
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "nfc-claim-audit"
7
+ version = "0.1.0"
8
+ description = "Offline static audit of documented tag capability"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = {text = "MIT"}
12
+
13
+ [project.scripts]
14
+ nfc-claim-audit = "nfc_claim_audit.__main__:main"
15
+
16
+ [tool.setuptools.packages.find]
17
+ include = ["nfc_claim_audit*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1 @@
1
+ GOOD = 'from nfc import ContactlessFrontend\nclf = ContactlessFrontend("usb")\n'
@@ -0,0 +1 @@
1
+ # marker only
@@ -0,0 +1 @@
1
+ reads nfc tags
@@ -0,0 +1 @@
1
+ print("hello")
@@ -0,0 +1 @@
1
+ reads nfc tags
@@ -0,0 +1,2 @@
1
+ from nfc import ContactlessFrontend
2
+ ContactlessFrontend("usb")
@@ -0,0 +1,2 @@
1
+ import nfc
2
+ nfc.ContactlessFrontend("usb")
@@ -0,0 +1 @@
1
+ reads nfc tags
@@ -0,0 +1,2 @@
1
+ import nfc
2
+ nfc.ContactlessFrontend("usb")
@@ -0,0 +1,186 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ from pathlib import Path
5
+ import re
6
+ import tempfile
7
+ import unittest
8
+ from unittest.mock import patch
9
+ from nfc_claim_audit.audit import audit, claims, evidence
10
+ from nfc_claim_audit.__main__ import main
11
+ from nfc_claim_audit.phrases import NFC, NONFC
12
+ from .cases import GOOD
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+
16
+ class AuditTests(unittest.TestCase):
17
+ def scenario(self, doc, source=None, filename='app.py', **options):
18
+ with tempfile.TemporaryDirectory() as tmp:
19
+ root = Path(tmp)
20
+ (root / 'README.md').write_text(doc)
21
+ if source is not None:
22
+ path = root / filename
23
+ path.parent.mkdir(parents=True, exist_ok=True)
24
+ path.write_text(source)
25
+ return audit(root, **options)
26
+
27
+ def high(self, result, rule='documented-nfc-claim-false'):
28
+ self.assertEqual(result['verdict'], 'FAIL')
29
+ self.assertEqual(len(result['findings']), 1)
30
+ self.assertEqual(result['findings'][0]['severity'], 'HIGH')
31
+ self.assertEqual(result['findings'][0]['rule'], rule)
32
+
33
+ def test_testonly(self):
34
+ for filename in ['tests/device.py', 'test_device.py', 'device_test.py']:
35
+ with self.subTest(filename=filename):
36
+ result = self.scenario('reads nfc tags', GOOD, filename)
37
+ self.assertEqual(result['verdict'], 'PASS')
38
+ self.assertEqual(len(result['findings']), 1)
39
+ self.assertEqual(result['findings'][0]['severity'], 'MEDIUM')
40
+ self.assertEqual(result['findings'][0]['rule'], 'documented-nfc-claim-false')
41
+ self.assertEqual(self.scenario('reads nfc tags', GOOD, filename, fail_on='MEDIUM')['verdict'], 'FAIL')
42
+
43
+ def test_negative_with_evidence(self):
44
+ self.high(self.scenario('no nfc', GOOD), 'documented-no-nfc-claim-false')
45
+
46
+ def test_no_source_positive(self):
47
+ self.high(self.scenario('reads nfc tags'))
48
+
49
+ def test_no_source_negative(self):
50
+ self.assertEqual(self.scenario('no nfc')['findings'], [])
51
+
52
+ def test_self_audit(self):
53
+ self.assertEqual(claims((ROOT / 'README.md').read_text()), (False, False))
54
+ self.assertEqual(audit(ROOT)['verdict'], 'PASS')
55
+
56
+ def test_normalization(self):
57
+ self.assertEqual(claims("It doesn't read NFC tags."), (False, True))
58
+ self.assertEqual(claims('READS-data\nfrom NFC tags'), (True, False))
59
+ self.assertEqual(claims('reads\n\nnfc tags'), (False, False))
60
+ self.assertEqual(claims('prereads nfc tagsuffix'), (False, False))
61
+
62
+ def test_two_families(self):
63
+ result = self.scenario('reads nfc tags. no nfc', GOOD)
64
+ self.high(result, 'documented-no-nfc-claim-false')
65
+
66
+ def test_doc_paths_ignore(self):
67
+ with tempfile.TemporaryDirectory() as tmp:
68
+ root = Path(tmp)
69
+ (root / 'nested/docs').mkdir(parents=True)
70
+ (root / 'nested/docs/a.md').write_text('reads nfc tags')
71
+ self.high(audit(root))
72
+ self.assertEqual(audit(root, ['nested/docs/*'])['findings'], [])
73
+
74
+ def test_excluded_sources(self):
75
+ for filename in ['fixtures/app.py', 'docs/app.py', 'examples/app.py']:
76
+ self.high(self.scenario('reads nfc tags', GOOD, filename))
77
+
78
+ def test_symlinks(self):
79
+ with tempfile.TemporaryDirectory() as tmp:
80
+ root = Path(tmp)
81
+ (root / 'README.md').write_text('reads nfc tags')
82
+ (root / 'fixtures').mkdir()
83
+ (root / 'fixtures/source.py').write_text(GOOD)
84
+ (root / 'linked.py').symlink_to(root / 'fixtures/source.py')
85
+ self.high(audit(root))
86
+
87
+ def test_env_never_read(self):
88
+ original = Path.read_text
89
+ def guarded(path, *args, **kwargs):
90
+ self.assertNotEqual(path.name, '.env')
91
+ return original(path, *args, **kwargs)
92
+ with patch.object(Path, 'read_text', guarded):
93
+ self.assertEqual(audit(ROOT / 'tests/fixtures/good')['verdict'], 'PASS')
94
+ audit(ROOT / 'tests/fixtures')
95
+
96
+ def test_cli(self):
97
+ for name, code in [('good', 0), ('bad', 2), ('testonly', 0), ('no-nfc', 2)]:
98
+ with self.subTest(name=name), contextlib.redirect_stdout(io.StringIO()) as out:
99
+ self.assertEqual(main([str(ROOT / 'tests/fixtures' / name), '--json', '--verbose']), code)
100
+ self.assertIn(json.loads(out.getvalue())['verdict'], ['PASS', 'FAIL'])
101
+ with contextlib.redirect_stdout(io.StringIO()):
102
+ self.assertEqual(main([str(ROOT / 'tests/fixtures/testonly'), '--fail-on', 'MEDIUM']), 2)
103
+ self.assertEqual(main([str(ROOT / 'tests/fixtures/bad'), '--ignore', 'README.md']), 0)
104
+ self.assertEqual(main([str(ROOT), '--verbose']), 0)
105
+ with contextlib.redirect_stdout(io.StringIO()) as out, self.assertRaises(SystemExit) as cm:
106
+ main(['--version'])
107
+ self.assertEqual(cm.exception.code, 0)
108
+ self.assertEqual(out.getvalue().strip(), '0.1.0')
109
+ with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as cm:
110
+ main(['/does/not/exist'])
111
+ self.assertEqual(cm.exception.code, 1)
112
+
113
+ def test_packaging(self):
114
+ project = (ROOT / 'pyproject.toml').read_text()
115
+ self.assertIn('nfc-claim-audit = "nfc_claim_audit.__main__:main"', project)
116
+ self.assertIn('MIT License', (ROOT / 'LICENSE').read_text())
117
+ self.assertIn('recursive-include tests *.py *.md .env', (ROOT / 'MANIFEST.in').read_text())
118
+ for folder in ['nfc_claim_audit', 'tests']:
119
+ for path in (ROOT / folder).rglob('*.py'):
120
+ text = path.read_text()
121
+ self.assertIsNone(re.search(r'\bpython\s+(?:-m|-c|\w+\.py)', text))
122
+ self.assertIsNone(re.search(r'(?:AKIA[0-9A-Z]{16}|ghp_[a-zA-Z0-9]{36}|' + '-----BEGIN ' + r'PRIVATE KEY-----)', text))
123
+
124
+
125
+ def add_case(name, doc, source, expected):
126
+ def test(self):
127
+ result = self.scenario(doc, source)
128
+ if expected == 'HIGH':
129
+ self.high(result)
130
+ else:
131
+ self.assertEqual(result['verdict'], 'PASS')
132
+ self.assertEqual(result['findings'], [])
133
+ setattr(AuditTests, 'test_' + name, test)
134
+
135
+ for index, phrase in enumerate(NFC):
136
+ add_case('phrase_positive_%02d' % index, phrase, None, 'HIGH')
137
+ for index, phrase in enumerate(NONFC):
138
+ add_case('phrase_negative_%02d' % index, phrase, None, 'PASS')
139
+
140
+ sources = {
141
+ 'frontend': GOOD,
142
+ 'attribute': 'import nfc\nnfc.ContactlessFrontend("usb")',
143
+ 'alias': 'import nfc as nf\nnf.ContactlessFrontend("usb")',
144
+ 'bound': GOOD + 'clf.connect(rdwr={})',
145
+ 'with': 'import nfc\nwith nfc.ContactlessFrontend("usb") as clf:\n clf.connect(rdwr={})',
146
+ 'chain': 'import nfc\nnfc.ContactlessFrontend("usb").connect(rdwr={})',
147
+ 'self': 'import nfc\nself.clf = nfc.ContactlessFrontend("usb")\nself.clf.connect()',
148
+ 'from_alias': 'from nfc import ContactlessFrontend as CF\nCF("usb")',
149
+ 'dotted_import': 'import nfc.tag\nnfc.ContactlessFrontend("usb")',
150
+ 'submodule': 'from nfc.clf import ContactlessFrontend\nContactlessFrontend("usb")',
151
+ }
152
+ for name, source in sources.items():
153
+ add_case('good_' + name, 'reads nfc tags', source, 'PASS')
154
+ bad = {
155
+ 'none': 'print("hello")',
156
+ 'bare_import': 'import nfc',
157
+ 'unbound': 'clf.connect()',
158
+ 'string': 'tag = "04:11:22:33:44:55:66"',
159
+ 'ndef': 'import ndef\nndef.TextRecord("hello")',
160
+ 'subprocess': 'import subprocess\nsubprocess.run(["nfc-poll"])',
161
+ 'bluetooth': 'import bluetooth\nbluetooth.BluetoothSocket().connect(("x", 1))',
162
+ 'usb': 'import usb.core\nusb.core.find()',
163
+ 'serial': 'import serial\nserial.Serial("port")',
164
+ 'local': 'class ContactlessFrontend: pass\nContactlessFrontend()',
165
+ 'shadow': 'from nfc import ContactlessFrontend\nclass ContactlessFrontend: pass\nContactlessFrontend()',
166
+ 'function_shadow': 'from nfc import ContactlessFrontend\ndef ContactlessFrontend(): pass\nContactlessFrontend()',
167
+ 'other_import': 'import local as nfc\nnfc.ContactlessFrontend()',
168
+ 'smartcard': 'from smartcard import ContactlessFrontend\nContactlessFrontend()',
169
+ 'logging': 'def connect_tag():\n print("tag")\nconnect_tag()',
170
+ 'decorator': '@app.get("/tag")\ndef tag(): return "ok"',
171
+ 'docstring': '\"\"\"import nfc; nfc.ContactlessFrontend()\"\"\"',
172
+ 'syntax': 'import nfc\n!invalid',
173
+ }
174
+ for name, source in bad.items():
175
+ add_case('bad_' + name, 'reads nfc tags', source, 'HIGH')
176
+ for name, doc in {
177
+ 'no_claim': 'A utility for cards.',
178
+ 'user_instruction': 'Hold the tag near the reader first. Tap the card before starting.',
179
+ 'bare_word': '# NFC',
180
+ 'fenced': '```text\nreads nfc tags\n```',
181
+ 'tilde_fenced': '~~~~\nno nfc\nreads nfc tags\n~~~~',
182
+ 'adjacent': 'Connects via Bluetooth. Supports USB. Prints files.',
183
+ }.items():
184
+ add_case(name, doc, None, 'PASS')
185
+ add_case('no_claim_with_evidence', 'Card utility', GOOD, 'PASS')
186
+ add_case('inline', 'It `reads nfc tags`.', None, 'HIGH')