spellwarden 0.1.0__py3-none-any.whl

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,143 @@
1
+ Metadata-Version: 2.5
2
+ Name: spellwarden
3
+ Version: 0.1.0
4
+ Summary: The Spellwarden scan engine: baseline rules for agent skills and MCP servers, probe classification, migration checklist and curation score. Pure code, no I/O.
5
+ Project-URL: Homepage, https://spellwarden.ai
6
+ Project-URL: Source, https://github.com/spellwarden-ai/spellwarden
7
+ Author: Spellwarden
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: agent-skills,mcp,scanner,security
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Security
18
+ Requires-Python: >=3.11
19
+ Requires-Dist: pyyaml>=6.0
20
+ Description-Content-Type: text/markdown
21
+
22
+ # spellwarden
23
+
24
+ The Spellwarden scan engine: the baseline rules for agent skills and MCP servers, the probe classification against the 2026-07-28 MCP specification, the migration checklist and the curation score. It is the engine of the hosted product at [spellwarden.ai](https://spellwarden.ai) and is published so that the same rules run in your own tooling.
25
+
26
+ This package is pure code. It never opens a connection, reads a file or an environment variable: you hand it the bytes of a package or the recorded result of a probe, and it hands back findings. The command-line scanner, discovery in a repository and the CI wrappers arrive in a later release; this one is the library they are built on.
27
+
28
+ ```
29
+ pip install spellwarden
30
+ ```
31
+
32
+ Python 3.11 or newer. The only dependency is PyYAML.
33
+
34
+ ## Scanning a skill package
35
+
36
+ ```python
37
+ from spellwarden_scan import RuleSet, scan_skill_package, unpack_zip
38
+
39
+ files, executable = unpack_zip(open_bytes, with_modes=True) # or any {path: bytes} mapping you built yourself
40
+ result = scan_skill_package(files, RuleSet.baseline(), executable_paths=executable)
41
+ for finding in result.findings:
42
+ print(finding.rule_id, finding.severity, finding.location.path, finding.location.line, finding.evidence)
43
+ print(result.sha256, result.metadata.name, result.truncated)
44
+ ```
45
+
46
+ - `files` maps POSIX relative paths to bytes. `root` names the directory that holds `SKILL.md` when it is not the package root.
47
+ - `unpack_zip(data, limits=ArchiveLimits(), with_modes=False)` reads a zip held in memory and refuses unsafe archives with an `ArchiveError` whose `code` is one of `too_large`, `too_many_files`, `unsafe_path`, `symlink`, `bad_zip`, `empty`. The default limits are 20 MiB compressed, 50 MiB uncompressed, 2000 files, 10 MiB per file.
48
+ - `result.sha256` is the canonical hash of the package: SHA-256 over `path NUL content NUL` for every path in sorted order, stable across archive layout.
49
+ - `result.metadata` holds `name`, `description`, `version`, `license`, `publisher` from the frontmatter (nested `metadata:` keys and `author` are read too), which of them are present, and the problems that rule SW-SKL-015 reports.
50
+ - `max_findings` (500) and `max_per_rule` (100) bound what the scan keeps; rules run worst severity first and `result.truncated` counts the matches that were not kept.
51
+ - Evidence is at most 300 characters and credential-shaped text in it is masked. `fingerprint` is the SHA-256 of rule id, path and matched text, so a finding keeps its identity across scans.
52
+
53
+ ## Evaluating an MCP server probe
54
+
55
+ ```python
56
+ from spellwarden_scan import ProbeResult, RuleSet, evaluate_probe
57
+
58
+ probe = ProbeResult.from_dict(recorded) # what your prober recorded; every field has a default
59
+ result = evaluate_probe(probe, RuleSet.baseline())
60
+ print(result.transport, result.auth_mode, result.spec_version, result.migration_status)
61
+ for item in result.checklist:
62
+ print(item.order, item.text)
63
+ ```
64
+
65
+ `ProbeResult` is the record of an unauthenticated probe: the `server/discover` or `initialize` result, the status and content type of the POST and GET, whether a session header was seen, the `tools/list` answer, the RFC 9728 protected resource metadata and the authorization server metadata. The classification follows one rule set:
66
+
67
+ - transport: `streamable-http`, `sse`, `stdio` (a repository without an endpoint) or `unknown`;
68
+ - authentication: `none`, `static-key`, `oauth-dcr`, `oauth-cimd`, `xaa` or `unknown`;
69
+ - spec version: the highest `supportedVersions` date of `server/discover`, else the negotiated `initialize` version;
70
+ - deprecated features, in a fixed order: `sse`, `initialize_only`, `sessions`, `roots`, `sampling`, `logging`, `dcr`;
71
+ - `migration_status`: `ready` when the spec version is 2026-07-28 or later, authentication is CIMD or XAA and nothing deprecated is in use; `to_migrate` otherwise; `not_probeable` for stdio servers.
72
+
73
+ The checklist has twelve items in a fixed order, each present only when it applies (move to streamable HTTP; add `server/discover`; remove sessions; carry the protocol version and capabilities in `_meta`; replace `sampling/createMessage` with an `input_required` result; replace Logging with a per-request `_meta` log level; move long jobs to the Tasks extension; register a Client ID Metadata Document and enable OAuth with RFC 9728 and RFC 8707; validate `iss`; set `ttlMs` and `cacheScope` on list results; propagate `traceparent`; re-run the scan, which is always last).
74
+
75
+ ## Curation score
76
+
77
+ ```python
78
+ from spellwarden_scan import CurationInputs, curation_score, is_curated, is_quarantined
79
+
80
+ inputs = CurationInputs(open_findings=open_ones, accepted_findings=accepted_ones, metadata_present=5, eval_component=0.5)
81
+ score = curation_score(inputs) # 0 to 12, one decimal
82
+ curated = is_curated(inputs, score) # score >= 8, no open critical or high finding, hash unchanged, not quarantined
83
+ quarantined = is_quarantined(open_ones) # any open finding from a malicious-indicator rule
84
+ ```
85
+
86
+ The score is `12 x (0.6 S + 0.2 M + 0.2 E)`: `S = max(0, 1 - (6 critical + 3 high + 1 medium + 0.25 low) / 12)` over open findings with accepted findings at half weight, `M` the share of the five metadata fields present, `E` an evaluation component that is 0.5 until evaluations exist.
87
+
88
+ ## The rules
89
+
90
+ Ids are `SW-SKL-NNN` (skill packages) and `SW-MCP-NNN` (MCP servers). Mappings use the OWASP Agentic Top 10 (ASI) and OWASP MCP Top 10 (MCP) identifiers and NIST SP 800-53 base controls, labelled as a provisional mapping to SP 800-53 base controls. Two rules are malicious indicators: an open finding from one of them quarantines the package.
91
+
92
+ | Id | Title | Severity | OWASP | NIST |
93
+ |---|---|---|---|---|
94
+ | SW-SKL-001 | Prompt-injection phrases in skill instructions | high | ASI01 | SI-10 |
95
+ | SW-SKL-002 | Hidden text: zero-width or bidirectional control characters | high | ASI01 | SI-10 |
96
+ | SW-SKL-003 | Instructions to skip approvals or disable hooks | high | ASI10 | AC-6 |
97
+ | SW-SKL-004 | Encoded payload decoded and executed (malicious indicator) | critical | ASI04 | SR-3 |
98
+ | SW-SKL-005 | Writes to agent configuration | high | ASI10 | AC-6 |
99
+ | SW-SKL-006 | Destructive command without a confirmation step | medium | ASI10 | AC-6 |
100
+ | SW-SKL-007 | Remote script piped to a shell | high | ASI04 | SR-3 |
101
+ | SW-SKL-008 | Sends local file contents to an external host (malicious indicator) | critical | ASI10 | SC-7 |
102
+ | SW-SKL-009 | Unpinned dependency install | medium | ASI04 | SR-3 |
103
+ | SW-SKL-010 | Bundled binary or executable file | medium | ASI04 | SR-3 |
104
+ | SW-SKL-011 | Hard-coded credential in the package | critical | MCP01 | IA-5 |
105
+ | SW-SKL-012 | Reads a credential file path without stating purpose | medium | ASI04 | IA-5 |
106
+ | SW-SKL-013 | Network calls to raw IP addresses or URL shorteners | medium | ASI10 | SC-7 |
107
+ | SW-SKL-014 | Obfuscated script code | medium | ASI04 | SR-3 |
108
+ | SW-SKL-015 | Frontmatter missing or invalid (name, description) | low | ASI04 | SR-3 |
109
+ | SW-SKL-019 | Fetches external URL content into context without an allowlist | medium | ASI01, MCP10 | SI-10 |
110
+ | SW-SKL-031 | Missing license and version metadata | low | ASI04 | SR-3 |
111
+ | SW-MCP-001 | Server lists tools without authentication | high | MCP01 | AC-3 |
112
+ | SW-MCP-002 | Static key authentication instead of OAuth | medium | MCP01 | IA-5 |
113
+ | SW-MCP-003 | OAuth dynamic client registration (deprecated; use Client ID Metadata Documents) | medium | MCP01 | IA-5 |
114
+ | SW-MCP-004 | HTTP+SSE transport (deprecated) | medium | ASI04 | SR-3 |
115
+ | SW-MCP-005 | Spec version older than 2026-07-28 | low | ASI04 | SR-3 |
116
+ | SW-MCP-006 | Protocol sessions (Mcp-Session-Id) in use | medium | ASI04 | SR-3 |
117
+ | SW-MCP-007 | Requires the initialize handshake; no server/discover | medium | ASI04 | SR-3 |
118
+ | SW-MCP-008 | Uses deprecated Roots, Sampling or Logging | medium | ASI04 | SR-3 |
119
+ | SW-MCP-009 | Endpoint not served over HTTPS | high | MCP01 | SC-7 |
120
+ | SW-MCP-010 | No protected resource metadata, or issuer not validated | medium | MCP01 | IA-5 |
121
+ | SW-MCP-011 | Tool description contains instruction-like text | high | ASI01, MCP10 | SI-10 |
122
+
123
+ Ids 016 to 018 and 020 to 030 are reserved. `RuleSet.baseline()` returns these rules; `ruleset.with_rules(extra)` adds your own `Rule` objects built with `spellwarden_scan.rules.make_rule`.
124
+
125
+ ## Versions
126
+
127
+ `spellwarden_scan.__version__` is the package version and `spellwarden_scan.RULES_VERSION` (`YYYY.MM.N`) the rule set's. A change to what any rule detects bumps both the rules version and the package minor version; a fix anywhere else bumps the patch. Every scan result carries both, so a stored finding always says which rules produced it.
128
+
129
+ ## Releases
130
+
131
+ Releases are built and published by GitHub Actions through PyPI trusted publishing (OpenID Connect): a push of a tag `vX.Y.Z` whose version equals the one in `pyproject.toml` builds the sdist and the wheel and publishes them from the `pypi` environment. No API token exists anywhere. The sources are checked on Python 3.11, 3.12 and 3.13 on every push.
132
+
133
+ ## Development
134
+
135
+ ```
136
+ make check # ruff, pytest, uv build
137
+ ```
138
+
139
+ `tests/test_pure.py` fails the build if any module reaches for the network, the file system or the environment; `tests/test_fixture_coverage.py` fails it if a rule lacks a positive or a negative fixture.
140
+
141
+ ## License
142
+
143
+ Apache-2.0. See `LICENSE`.
@@ -0,0 +1,20 @@
1
+ spellwarden_scan/__init__.py,sha256=QW2a7OOWwL8kTQoQNoqhiR2WPO7D986t4JXr5mQHyH8,1646
2
+ spellwarden_scan/archive.py,sha256=Ul7RswMmuP7C1kzhWJ8quyh_CGRK-5DjmxdEUijhKfE,9916
3
+ spellwarden_scan/canonical.py,sha256=IPs_uwK-uzC9ZfmU_BINiPBfQHNBhOu7UX4D9wgMKFw,534
4
+ spellwarden_scan/checklist.py,sha256=8OfRUk_ZdDZSXIDDoQJan4oGafXKhYC6xTcQ09bMags,2614
5
+ spellwarden_scan/curation.py,sha256=ECmxuCqVBwtZv4F24nkpvZnE0hQRMvpkO2RMyGoQ4Wk,2116
6
+ spellwarden_scan/evidence.py,sha256=UIcvWNw0iLYxM0mFLdZZxjRfyUW9uJYZ1zv4gGW-k1s,4754
7
+ spellwarden_scan/frontmatter.py,sha256=YrR2xjafDhY4CQ9JMHGWn2XzFYeCCW9ZN0BAWuyxYvw,4520
8
+ spellwarden_scan/model.py,sha256=jgTcy3R1Q3IFC0YfXOlp64yD2tnHg9_oWCRAhCqZgUI,6339
9
+ spellwarden_scan/package.py,sha256=7KPHFDi4eX5x1ydT_UPDxj8qDgsg5UAoO207JUIEIIc,6885
10
+ spellwarden_scan/probe.py,sha256=ljdUfrtKabqHZZeNrIUhpL4tKNrlImJ1iUBuh5wyS_E,8109
11
+ spellwarden_scan/scan.py,sha256=GivzsXl8ONCk3AzLES5gDHl4jomqFpQWZGipazU1vRo,2172
12
+ spellwarden_scan/version.py,sha256=Fp8tbs_ZZjaED6W3Npgtc1bZrz_J9FP4niAaALmzLjQ,107
13
+ spellwarden_scan/rules/__init__.py,sha256=iMCAozIkzr6JzOl35ZSBp15dY3SPosR3le_L5V4CokY,4194
14
+ spellwarden_scan/rules/mcp.py,sha256=eaqV9to-QFo60VQmmugcANwb5G_8WHUxYtOYf2xmj7k,12802
15
+ spellwarden_scan/rules/patterns.py,sha256=IM16KNPfYx1dnv9r4bcKTJbO-y6-2zqxFjD0rPQ497U,6893
16
+ spellwarden_scan/rules/skill.py,sha256=T67oKhW58gq9Ewvpmlu0hI_Acc0_uK7Sv0_t6BfTVHw,33619
17
+ spellwarden-0.1.0.dist-info/METADATA,sha256=P1LFmlNVLUy93dS6sb7CK0zIAQUkIjcBXbSqEmBXAqc,10207
18
+ spellwarden-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
19
+ spellwarden-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
20
+ spellwarden-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,28 @@
1
+ """spellwarden_scan: the Spellwarden scan engine (spec 5). Pure code: it
2
+ takes bytes and recorded probe results and returns findings. Tasks 2 to 4
3
+ add `scan_skill_package`, `evaluate_probe`, `migration_checklist` and the
4
+ curation functions to this list."""
5
+ from __future__ import annotations
6
+
7
+ from spellwarden_scan.archive import ArchiveError, ArchiveLimits, unpack_zip
8
+ from spellwarden_scan.canonical import canonical_sha256
9
+ from spellwarden_scan.evidence import mask_credentials
10
+ from spellwarden_scan.frontmatter import FrontmatterError, parse_frontmatter
11
+ from spellwarden_scan.model import (
12
+ SEVERITY_RANK, Area, AuthServerMetadata, ChecklistItem, CurationInputs, Finding, Location, McpScanResult, Metadata,
13
+ ProbeResult, Severity, SkillScanResult, ToolInfo,
14
+ )
15
+ from spellwarden_scan.checklist import migration_checklist
16
+ from spellwarden_scan.curation import curation_score, is_curated, is_quarantined
17
+ from spellwarden_scan.probe import evaluate_probe
18
+ from spellwarden_scan.rules import Rule, RuleSet
19
+ from spellwarden_scan.scan import scan_skill_package
20
+ from spellwarden_scan.version import RULES_VERSION, __version__
21
+
22
+ __all__ = [
23
+ "RULES_VERSION", "SEVERITY_RANK", "Area", "ArchiveError", "ArchiveLimits", "AuthServerMetadata", "ChecklistItem",
24
+ "CurationInputs", "Finding", "FrontmatterError", "Location", "McpScanResult", "Metadata", "ProbeResult", "Rule",
25
+ "RuleSet", "Severity", "SkillScanResult", "ToolInfo", "__version__", "canonical_sha256", "curation_score",
26
+ "evaluate_probe", "is_curated", "is_quarantined", "mask_credentials", "migration_checklist", "parse_frontmatter",
27
+ "scan_skill_package", "unpack_zip",
28
+ ]
@@ -0,0 +1,209 @@
1
+ """Zip unpacking with the safety rules of spec 5.6. The archive is bytes in
2
+ memory; nothing touches the file system."""
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import lzma
7
+ import posixpath
8
+ import re
9
+ import stat
10
+ import unicodedata
11
+ import zipfile
12
+ import zlib
13
+ from dataclasses import dataclass
14
+
15
+ _DRIVE = re.compile(r"^[A-Za-z]:")
16
+ _CHUNK = 65536
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class ArchiveLimits:
21
+ max_compressed: int = 20 * 2**20
22
+ max_uncompressed: int = 50 * 2**20
23
+ max_files: int = 2000
24
+ max_file: int = 10 * 2**20
25
+ max_path: int = 255
26
+
27
+
28
+ DEFAULT_LIMITS = ArchiveLimits()
29
+
30
+
31
+ class ArchiveError(ValueError):
32
+ """`code` is one of `too_large`, `too_many_files`, `unsafe_path`, `symlink`, `bad_zip`, `empty`."""
33
+
34
+ def __init__(self, code: str, detail: str = "") -> None:
35
+ super().__init__(f"{code}: {detail}" if detail else code)
36
+ self.code = code
37
+ self.detail = detail
38
+
39
+
40
+ def _unsafe(name: str, limits: ArchiveLimits) -> bool:
41
+ if not name or "\x00" in name or "\\" in name or _DRIVE.match(name) or name.startswith("/"):
42
+ return True
43
+ if len(name) > limits.max_path:
44
+ return True
45
+ parts = name.split("/")
46
+ # `.` and `..` anywhere, and empty parts (`a//b`): every consumer must read the same path the scan read.
47
+ return any(part in ("..", ".", "") for part in parts[:-1]) or parts[-1] in ("..", ".")
48
+
49
+
50
+ def _platform_unsafe(name: str) -> bool:
51
+ """A part ending in a dot or a space, or holding `:`, is renamed or refused by Windows extractors (`run.sh.`
52
+ becomes `run.sh`): checked only under the scanned root (a repository may hold `docs/10:00.md` elsewhere)."""
53
+ return any(part.endswith((".", " ")) or ":" in part for part in name.split("/"))
54
+
55
+
56
+ def _folded(name: str) -> str:
57
+ """The key two names collide on in a case-insensitive, normalising file system (Windows, macOS): NFC and
58
+ `lower()` (not `casefold()`, which maps `ß` to `ss` where NTFS and APFS do not)."""
59
+ return unicodedata.normalize("NFC", name).lower()
60
+
61
+
62
+ def _platform_key(name: str) -> str:
63
+ """The path as a case-insensitive, normalising Windows or macOS extractor writes it: each segment without its
64
+ trailing dots and spaces, NFC, lower-cased."""
65
+ return "/".join(_folded(part.rstrip(". ")) for part in name.split("/"))
66
+
67
+
68
+ def _under(name: str, root: str | None) -> bool:
69
+ """Whether `name` lands under the scanned root on some file system: decided on the platform key, so
70
+ `Skill/SKILL.md` or `skill./x` is under `skill` too (a macOS or Windows extractor merges them)."""
71
+ if root is None:
72
+ return False
73
+ if not root:
74
+ return True
75
+ key, scope = _platform_key(name), _platform_key(root)
76
+ return key == scope or key.startswith(scope + "/")
77
+
78
+
79
+ def _is_special(info: zipfile.ZipInfo) -> bool:
80
+ mode = info.external_attr >> 16
81
+ return stat.S_ISLNK(mode) or stat.S_ISCHR(mode) or stat.S_ISBLK(mode) or stat.S_ISFIFO(mode) or stat.S_ISSOCK(mode)
82
+
83
+
84
+ def _is_executable(info: zipfile.ZipInfo) -> bool:
85
+ mode = info.external_attr >> 16
86
+ return bool(mode & stat.S_IXUSR)
87
+
88
+
89
+ def _strip_common_top(names: list[str]) -> str:
90
+ """The single top-level directory every entry shares, or an empty string."""
91
+ tops = {name.split("/", 1)[0] for name in names}
92
+ if len(tops) != 1:
93
+ return ""
94
+ top = tops.pop()
95
+ return top if all("/" in name for name in names) else ""
96
+
97
+
98
+ def unpack_zip(data: bytes, limits: ArchiveLimits = DEFAULT_LIMITS, *, with_modes: bool = False, root: str | None = ""):
99
+ """`{path: bytes}` of a zip held in memory; with `with_modes=True`,
100
+ `(files, executable_paths)`. Raises `ArchiveError` (spec 5.6).
101
+
102
+ Everywhere in the archive, a repeated name, a `.`, `..` or empty segment and a file that is also a
103
+ directory are `unsafe_path` (every extractor reads them differently). Under `root` (the directory
104
+ that will be scanned, relative to the stripped top; `""` is the whole archive, `None` none of it),
105
+ two names equal after NFC normalisation and lower-casing and a segment Windows renames or refuses
106
+ are `unsafe_path` as well: outside it they belong to another directory of a repository."""
107
+ scope = None if root is None else root.strip("/")
108
+ if len(data) > limits.max_compressed:
109
+ raise ArchiveError("too_large", "compressed size over the limit")
110
+ try:
111
+ archive = zipfile.ZipFile(io.BytesIO(data))
112
+ infos = archive.infolist()
113
+ except (zipfile.BadZipFile, ValueError, EOFError, RuntimeError, OSError) as exc:
114
+ # `NotImplementedError` (a `RuntimeError`) for an unsupported "version needed to extract" in the central directory.
115
+ raise ArchiveError("bad_zip", str(exc)) from exc
116
+ for info in infos:
117
+ if info.is_dir() and _unsafe(info.filename.rstrip("/"), limits):
118
+ raise ArchiveError("unsafe_path", info.filename)
119
+ directories = [info.filename.rstrip("/") for info in infos if info.is_dir()]
120
+ entries = [info for info in infos if not info.is_dir()]
121
+ if not entries:
122
+ raise ArchiveError("empty")
123
+ if len(entries) > limits.max_files:
124
+ raise ArchiveError("too_many_files", str(len(entries)))
125
+ for info in entries:
126
+ if _unsafe(info.filename, limits):
127
+ raise ArchiveError("unsafe_path", info.filename)
128
+ if _is_special(info):
129
+ raise ArchiveError("symlink", info.filename)
130
+ _check_declared(entries, limits)
131
+ top = _strip_common_top([info.filename for info in entries])
132
+ files: dict[str, bytes] = {}
133
+ executable: set[str] = set()
134
+ folded: set[str] = set()
135
+ total = 0
136
+ for info in entries:
137
+ name = info.filename[len(top) + 1:] if top else info.filename
138
+ if _unsafe(name, limits) or posixpath.normpath(name) != name or name in files:
139
+ raise ArchiveError("unsafe_path", info.filename)
140
+ if _under(name, scope):
141
+ # Under the scanned root, a name that differs only in case or normalisation, or that Windows renames,
142
+ # would let an extractor install a file the scan never read; so would a name an extractor merges into the
143
+ # root that is not under it byte for byte (`Skill/run.sh` for `skill`: the scan reads `skill/` only).
144
+ exact = not scope or name == scope or name.startswith(scope + "/")
145
+ if not exact or _platform_unsafe(name) or _platform_key(name) in folded:
146
+ raise ArchiveError("unsafe_path", f"colliding {info.filename}")
147
+ folded.add(_platform_key(name))
148
+ content, total = _read_entry(archive, info, limits, total)
149
+ files[name] = content
150
+ if _is_executable(info):
151
+ executable.add(name)
152
+ _check_file_directory_clash(files, [d[len(top) + 1:] if top and d.startswith(top + "/") else d for d in directories], scope)
153
+ if with_modes:
154
+ return files, frozenset(executable)
155
+ return files
156
+
157
+
158
+ def _check_file_directory_clash(files: dict[str, bytes], directories: list[str], scope: str | None) -> None:
159
+ """`a/b` as a file and `a/b/c` (or a directory entry `a/b/`) as another: no file system holds both, so an
160
+ extractor keeps one of them. Exact names everywhere; under the scanned root also case- and NFC-folded."""
161
+ exact = set(files)
162
+ folded = {_platform_key(name) for name in files if _under(name, scope)}
163
+ directory_set = set(directories)
164
+ for name in list(files) + directories:
165
+ parts = name.split("/")
166
+ for depth in range(1, len(parts) + (name in directory_set)):
167
+ prefix = "/".join(parts[:depth])
168
+ if prefix in exact or (_under(prefix, scope) and _platform_key(prefix) in folded):
169
+ raise ArchiveError("unsafe_path", f"file and directory {name}")
170
+
171
+
172
+ def _check_declared(entries: list[zipfile.ZipInfo], limits: ArchiveLimits) -> None:
173
+ """The sizes the headers declare (`file_size`, `compress_size`), checked before any entry is
174
+ opened: a declared size over a limit is `too_large` without reading a byte. The declared
175
+ sizes are not trusted for the opposite case; `_read_entry` counts the real bytes."""
176
+ declared = 0
177
+ for info in entries:
178
+ if info.file_size > limits.max_file or info.compress_size > limits.max_compressed:
179
+ raise ArchiveError("too_large", info.filename)
180
+ declared += info.file_size
181
+ if declared > limits.max_uncompressed:
182
+ raise ArchiveError("too_large", "declared uncompressed size over the limit")
183
+
184
+
185
+ def _read_entry(archive: zipfile.ZipFile, info: zipfile.ZipInfo, limits: ArchiveLimits, total: int) -> tuple[bytes, int]:
186
+ """Reads one entry in chunks and counts the real decompressed bytes: `too_large` is raised the
187
+ moment the entry or the running total exceeds its limit, before `zipfile` reaches the CRC check.
188
+ `zipfile` never yields more than the declared size, so a header that understates the size ends
189
+ in a size or CRC mismatch, which is `bad_zip`."""
190
+ chunks: list[bytes] = []
191
+ size = 0
192
+ try:
193
+ with archive.open(info) as handle:
194
+ while True:
195
+ chunk = handle.read(_CHUNK)
196
+ if not chunk:
197
+ break
198
+ size += len(chunk)
199
+ total += len(chunk)
200
+ if size > limits.max_file or total > limits.max_uncompressed:
201
+ raise ArchiveError("too_large", info.filename)
202
+ chunks.append(chunk)
203
+ except ArchiveError:
204
+ raise # an `ArchiveError` is a `ValueError`: keep `too_large` out of the corrupt-stream clause below
205
+ except (zipfile.BadZipFile, RuntimeError, EOFError, ValueError, OSError, zlib.error, lzma.LZMAError) as exc:
206
+ # A corrupt stream surfaces as `zlib.error` (deflate), `OSError` (bzip2) or `LZMAError`, and an
207
+ # unsupported method as `NotImplementedError` (a `RuntimeError`): all are `bad_zip`, the one code callers catch.
208
+ raise ArchiveError("bad_zip", info.filename) from exc
209
+ return b"".join(chunks), total
@@ -0,0 +1,16 @@
1
+ """The canonical package hash (spec 5.5): SHA-256 over `path NUL content NUL`
2
+ for every path in byte-wise sorted order."""
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from collections.abc import Mapping
7
+
8
+
9
+ def canonical_sha256(files: Mapping[str, bytes]) -> str:
10
+ digest = hashlib.sha256()
11
+ for path in sorted(files, key=lambda p: p.encode("utf-8")):
12
+ digest.update(path.encode("utf-8"))
13
+ digest.update(b"\x00")
14
+ digest.update(files[path])
15
+ digest.update(b"\x00")
16
+ return digest.hexdigest()