hallpass-client 0.4.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,8 @@
1
+ /hallpass
2
+ /hallpass.exe
3
+ /dist/
4
+ *.test
5
+ *.out
6
+ .specs/
7
+ __pycache__/
8
+ node_modules/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.5
2
+ Name: hallpass-client
3
+ Version: 0.4.0
4
+ Summary: Check with hallpass whether a user may do something before your AI agent does it for them.
5
+ Project-URL: Homepage, https://github.com/roee-hersh/hallpass
6
+ Project-URL: Documentation, https://github.com/roee-hersh/hallpass/blob/main/docs/agents.md
7
+ Project-URL: Issues, https://github.com/roee-hersh/hallpass/issues
8
+ Project-URL: Source, https://github.com/roee-hersh/hallpass/tree/main/sdk/python
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: ai-agents,authorization,llm,mcp,permissions,tools
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Security
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+
20
+ # hallpass-client
21
+
22
+ The Python client for [hallpass](https://github.com/roee-hersh/hallpass): before your AI agent
23
+ acts for a user, ask the system that owns the resource whether that user may do it.
24
+
25
+ ```sh
26
+ pip install https://github.com/roee-hersh/hallpass/releases/latest/download/hallpass-client-python.tar.gz
27
+ ```
28
+
29
+ That URL always gives the latest [release](https://github.com/roee-hersh/hallpass/releases). In a
30
+ project, pin a version by replacing `latest/download` with `download/v0.4.0`, in `requirements.txt`
31
+ too:
32
+
33
+ ```
34
+ hallpass-client @ https://github.com/roee-hersh/hallpass/releases/download/v0.4.0/hallpass-client-python.tar.gz
35
+ ```
36
+
37
+ It needs a running hallpass service. The client has no dependencies beyond the standard library.
38
+
39
+ ```python
40
+ from contextvars import ContextVar
41
+ from hallpass_client import Hallpass, guarded
42
+
43
+ hp = Hallpass() # HALLPASS_URL and HALLPASS_API_KEY from the environment
44
+ current_user: ContextVar[str] = ContextVar("current_user")
45
+
46
+ @tool # LangChain, Strands, MCP, the Claude Agent SDK...
47
+ @guarded(hp, "jira-main", "DELETE_ISSUES", "issue:{key}", user=current_user, fresh=True)
48
+ def delete_issue(key: str) -> str:
49
+ jira.delete_issue(key) # the agent's own credential, only after hallpass said allow
50
+ return f"deleted {key}"
51
+
52
+ current_user.set(request.user.email) # from your auth, per request or session
53
+ ```
54
+
55
+ - **The model never picks the user.** It comes from `user=`: a string, a zero-argument
56
+ callable, or a `ContextVar` your application sets. A `user` key in the tool's arguments is ignored.
57
+ - **It fails closed.** `deny`, `unknown` and hallpass being unreachable all raise
58
+ `PermissionDenied` before the body runs. Pass `deny=` to return a message to the model instead.
59
+ - **One package covers every framework.** `guarded` handles plain functions, `async def`,
60
+ and the Claude Agent SDK's `async def f(args: dict)` handler shape.
61
+
62
+ Without a decorator:
63
+
64
+ ```python
65
+ d = hp.check("dana@example.com", "jira-main", "DELETE_ISSUES", "issue:PAY-123")
66
+ d.decision, d.reason # "deny", "denied: ..."
67
+ hp.require(...) # raises PermissionDenied unless allow
68
+ ```
69
+
70
+ Framework examples: [examples/agent](https://github.com/roee-hersh/hallpass/tree/main/examples/agent).
71
+ The guide: [docs/agents.md](https://github.com/roee-hersh/hallpass/blob/main/docs/agents.md).
@@ -0,0 +1,52 @@
1
+ # hallpass-client
2
+
3
+ The Python client for [hallpass](https://github.com/roee-hersh/hallpass): before your AI agent
4
+ acts for a user, ask the system that owns the resource whether that user may do it.
5
+
6
+ ```sh
7
+ pip install https://github.com/roee-hersh/hallpass/releases/latest/download/hallpass-client-python.tar.gz
8
+ ```
9
+
10
+ That URL always gives the latest [release](https://github.com/roee-hersh/hallpass/releases). In a
11
+ project, pin a version by replacing `latest/download` with `download/v0.4.0`, in `requirements.txt`
12
+ too:
13
+
14
+ ```
15
+ hallpass-client @ https://github.com/roee-hersh/hallpass/releases/download/v0.4.0/hallpass-client-python.tar.gz
16
+ ```
17
+
18
+ It needs a running hallpass service. The client has no dependencies beyond the standard library.
19
+
20
+ ```python
21
+ from contextvars import ContextVar
22
+ from hallpass_client import Hallpass, guarded
23
+
24
+ hp = Hallpass() # HALLPASS_URL and HALLPASS_API_KEY from the environment
25
+ current_user: ContextVar[str] = ContextVar("current_user")
26
+
27
+ @tool # LangChain, Strands, MCP, the Claude Agent SDK...
28
+ @guarded(hp, "jira-main", "DELETE_ISSUES", "issue:{key}", user=current_user, fresh=True)
29
+ def delete_issue(key: str) -> str:
30
+ jira.delete_issue(key) # the agent's own credential, only after hallpass said allow
31
+ return f"deleted {key}"
32
+
33
+ current_user.set(request.user.email) # from your auth, per request or session
34
+ ```
35
+
36
+ - **The model never picks the user.** It comes from `user=`: a string, a zero-argument
37
+ callable, or a `ContextVar` your application sets. A `user` key in the tool's arguments is ignored.
38
+ - **It fails closed.** `deny`, `unknown` and hallpass being unreachable all raise
39
+ `PermissionDenied` before the body runs. Pass `deny=` to return a message to the model instead.
40
+ - **One package covers every framework.** `guarded` handles plain functions, `async def`,
41
+ and the Claude Agent SDK's `async def f(args: dict)` handler shape.
42
+
43
+ Without a decorator:
44
+
45
+ ```python
46
+ d = hp.check("dana@example.com", "jira-main", "DELETE_ISSUES", "issue:PAY-123")
47
+ d.decision, d.reason # "deny", "denied: ..."
48
+ hp.require(...) # raises PermissionDenied unless allow
49
+ ```
50
+
51
+ Framework examples: [examples/agent](https://github.com/roee-hersh/hallpass/tree/main/examples/agent).
52
+ The guide: [docs/agents.md](https://github.com/roee-hersh/hallpass/blob/main/docs/agents.md).
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "hallpass-client"
7
+ # The release workflow sets the version from the release tag before it builds.
8
+ version = "0.4.0"
9
+ description = "Check with hallpass whether a user may do something before your AI agent does it for them."
10
+ readme = "README.md"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ requires-python = ">=3.9"
14
+ dependencies = []
15
+ keywords = ["ai-agents", "authorization", "permissions", "llm", "tools", "mcp"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Security",
21
+ "Typing :: Typed",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/roee-hersh/hallpass"
26
+ Documentation = "https://github.com/roee-hersh/hallpass/blob/main/docs/agents.md"
27
+ Issues = "https://github.com/roee-hersh/hallpass/issues"
28
+ Source = "https://github.com/roee-hersh/hallpass/tree/main/sdk/python"
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["src/hallpass_client"]
32
+
33
+ [tool.hatch.build.targets.sdist]
34
+ include = ["src/hallpass_client", "tests", "README.md", "LICENSE"]
@@ -0,0 +1,413 @@
1
+ """The hallpass client for agents. Standard library only.
2
+
3
+ pip install https://github.com/roee-hersh/hallpass/releases/latest/download/hallpass-client-python.tar.gz
4
+
5
+ The one rule an agent has to follow: perform an action on behalf of a user
6
+ only when hallpass answered ``allow``. ``deny`` and ``unknown`` both mean
7
+ "do not act", and so does any failure to reach hallpass at all.
8
+
9
+ hp = Hallpass() # HALLPASS_URL and HALLPASS_API_KEY from the environment
10
+ hp.require("dana@example.com", "jira-main", "DELETE_ISSUES", "issue:PAY-123", fresh=True)
11
+ jira.delete_issue("PAY-123") # only reached when the answer was allow
12
+
13
+ ``fresh=True`` makes hallpass skip its caches and ask the upstream system
14
+ now; use it for destructive actions (delete, merge, scale), where a
15
+ 30-second-old answer is not good enough.
16
+
17
+ Or, for a tool an agent framework exposes to a model, ``guarded``:
18
+
19
+ current_user: ContextVar[str] = ContextVar("current_user")
20
+
21
+ @tool # any framework's decorator
22
+ @guarded(hp, "jira-main", "DELETE_ISSUES", "issue:{key}", user=current_user)
23
+ def delete_issue(key: str) -> str:
24
+ jira.delete_issue(key)
25
+ return f"deleted {key}"
26
+
27
+ The user comes from the application, never from the tool's arguments.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import asyncio
33
+ import contextvars
34
+ import datetime
35
+ import functools
36
+ import http.client
37
+ import inspect
38
+ import ipaddress
39
+ import json
40
+ import logging
41
+ import os
42
+ import re
43
+ import urllib.error
44
+ import urllib.parse
45
+ import urllib.request
46
+ from collections.abc import Mapping
47
+ from dataclasses import dataclass
48
+ from typing import Any, Callable, Iterable, TypeVar, Union
49
+
50
+ __all__ = [
51
+ "ALLOW",
52
+ "DENY",
53
+ "UNKNOWN",
54
+ "Decision",
55
+ "GroupsSource",
56
+ "Hallpass",
57
+ "PermissionDenied",
58
+ "UserSource",
59
+ "current",
60
+ "guarded",
61
+ ]
62
+
63
+ ALLOW = "allow"
64
+ DENY = "deny"
65
+ UNKNOWN = "unknown"
66
+
67
+ # Where guarded reports each write it let through. hallpass never sees the
68
+ # write itself, so this is the record that ties the action to the check.
69
+ log = logging.getLogger("hallpass")
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Decision:
74
+ """One answer from ``POST /check``.
75
+
76
+ ``decision`` is ``allow``, ``deny`` or ``unknown``. ``reason`` is
77
+ ``"<code>: <text>"`` as hallpass sent it, or ``"client_error: ..."`` when
78
+ the request never produced a usable answer. ``status`` is the HTTP status,
79
+ 0 when no response arrived.
80
+ """
81
+
82
+ decision: str
83
+ reason: str
84
+ status: int = 200
85
+
86
+ @property
87
+ def allowed(self) -> bool:
88
+ """True only for a positive ``allow``. ``unknown`` is not allowed."""
89
+ return self.decision == ALLOW
90
+
91
+ @property
92
+ def code(self) -> str:
93
+ """The machine-readable code in front of the colon, e.g. ``user_not_found``."""
94
+ return self.reason.split(":", 1)[0].strip()
95
+
96
+
97
+ class PermissionDenied(Exception):
98
+ """Raised by ``Hallpass.require`` when the answer was not ``allow``."""
99
+
100
+ def __init__(self, decision: Decision, user: str, connection: str, action: str, resource: str):
101
+ self.decision = decision
102
+ self.user, self.connection, self.action, self.resource = user, connection, action, resource
103
+ super().__init__(
104
+ f"{user} may not {action} on {resource} in {connection}: "
105
+ f"{decision.decision} ({decision.reason})"
106
+ )
107
+
108
+
109
+ class Hallpass:
110
+ """Client for one hallpass service.
111
+
112
+ ``url`` defaults to ``$HALLPASS_URL`` or ``http://localhost:8080``.
113
+ ``api_key`` defaults to ``$HALLPASS_API_KEY``. The URL must be ``https://``;
114
+ plain ``http://`` is accepted only for ``localhost`` or a loopback address,
115
+ the same rule hallpass applies to its own upstream URLs, because the API
116
+ key travels in a header. ``timeout`` is the seconds
117
+ the client waits for the connection and then for each read; hallpass itself
118
+ waits up to the connection's ``timeout`` (8 s by default) for the upstream
119
+ system, so keep this a little above that. It is not a total wall-clock
120
+ budget: a peer that keeps trickling bytes keeps the request alive.
121
+
122
+ Redirects are not followed. A redirect would re-send the API key to
123
+ whatever host the ``Location`` header names, and its answer would not be
124
+ hallpass's, so a 3xx becomes an ``unknown`` decision like any other
125
+ unusable response.
126
+ """
127
+
128
+ def __init__(self, url: str | None = None, api_key: str | None = None, timeout: float = 10.0):
129
+ self.url = _validate_url(url or os.environ.get("HALLPASS_URL") or "http://localhost:8080")
130
+ self.api_key = api_key if api_key is not None else os.environ.get("HALLPASS_API_KEY", "")
131
+ if not self.api_key:
132
+ raise ValueError("hallpass API key missing: pass api_key or set HALLPASS_API_KEY")
133
+ self.timeout = timeout
134
+ self._opener = urllib.request.build_opener(_NoRedirect)
135
+
136
+ def check(
137
+ self,
138
+ user: str,
139
+ connection: str,
140
+ action: str,
141
+ resource: str,
142
+ groups: Iterable[str] | None = None,
143
+ *,
144
+ fresh: bool = False,
145
+ ) -> Decision:
146
+ """Ask hallpass. Never raises on transport: every failure becomes an ``unknown`` decision.
147
+
148
+ ``fresh=True`` asks for an answer straight from the upstream system,
149
+ skipping hallpass's caches. It narrows the window between the check
150
+ and the action to the time between the two; it does not close it.
151
+ """
152
+ body: dict = {"user": user, "connection": connection, "action": action, "resource": resource}
153
+ if groups is not None:
154
+ body["groups"] = _group_list(groups)
155
+ if fresh:
156
+ body["fresh"] = True
157
+ try:
158
+ req = urllib.request.Request(
159
+ self.url + "/check",
160
+ data=json.dumps(body).encode(),
161
+ method="POST",
162
+ headers={
163
+ "Authorization": "Bearer " + self.api_key,
164
+ "Content-Type": "application/json",
165
+ "Accept": "application/json",
166
+ },
167
+ )
168
+ with self._opener.open(req, timeout=self.timeout) as resp:
169
+ return _parse(resp.status, resp.read())
170
+ except urllib.error.HTTPError as e:
171
+ # 400 and 401 still carry a decision body; anything else is unusable.
172
+ try:
173
+ raw = e.read()
174
+ except (OSError, http.client.HTTPException):
175
+ raw = b""
176
+ return _parse(e.code, raw)
177
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as e:
178
+ # URLError covers refused connections and DNS failures, OSError the
179
+ # socket timeout, HTTPException a malformed response, ValueError a
180
+ # malformed URL.
181
+ return Decision(UNKNOWN, f"client_error: hallpass unreachable: {e}", 0)
182
+
183
+ def allowed(self, user: str, connection: str, action: str, resource: str, groups=None, *, fresh: bool = False) -> bool:
184
+ """True only when hallpass said ``allow``."""
185
+ return self.check(user, connection, action, resource, groups, fresh=fresh).allowed
186
+
187
+ def require(self, user: str, connection: str, action: str, resource: str, groups=None, *, fresh: bool = False) -> Decision:
188
+ """Return the decision when it is ``allow``; raise ``PermissionDenied`` otherwise."""
189
+ d = self.check(user, connection, action, resource, groups, fresh=fresh)
190
+ if not d.allowed:
191
+ raise PermissionDenied(d, user, connection, action, resource)
192
+ return d
193
+
194
+
195
+ def _validate_url(url: str) -> str:
196
+ """The rule hallpass applies to its own upstream URLs (ValidateHTTPSURL)."""
197
+ if any(c in url for c in " \t\r\n?#"):
198
+ raise ValueError(f"hallpass url {url!r} must not contain whitespace, '?' or '#'")
199
+ u = urllib.parse.urlsplit(url)
200
+ if u.username is not None or u.password is not None:
201
+ raise ValueError(f"hallpass url {url!r} must not contain userinfo")
202
+ if u.scheme == "https" and u.hostname:
203
+ return url.rstrip("/")
204
+ if u.scheme == "http" and u.hostname:
205
+ host = u.hostname
206
+ try:
207
+ loopback = ipaddress.ip_address(host).is_loopback
208
+ except ValueError:
209
+ loopback = host == "localhost"
210
+ if loopback:
211
+ return url.rstrip("/")
212
+ raise ValueError(f"hallpass url {url!r} must start with https:// (http:// only for localhost)")
213
+
214
+
215
+ def _group_list(groups: Iterable[str]) -> list[str]:
216
+ if isinstance(groups, bool):
217
+ raise TypeError("groups must be a list of strings; fresh is keyword-only (fresh=True)")
218
+ if isinstance(groups, str):
219
+ raise TypeError("groups must be a list of strings, not a string")
220
+ out = list(groups)
221
+ if not all(isinstance(g, str) for g in out):
222
+ raise TypeError("groups must be a list of strings")
223
+ return out
224
+
225
+
226
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
227
+ """Turn every redirect into an HTTPError instead of following it."""
228
+
229
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
230
+ return None
231
+
232
+
233
+ def _parse(status: int, raw: bytes) -> Decision:
234
+ try:
235
+ data = json.loads(raw)
236
+ decision, reason = data["decision"], str(data.get("reason", ""))
237
+ except (ValueError, KeyError, TypeError):
238
+ return Decision(UNKNOWN, f"client_error: unexpected response (HTTP {status})", status)
239
+ if decision not in (ALLOW, DENY, UNKNOWN):
240
+ return Decision(UNKNOWN, f"client_error: unexpected decision {decision!r}", status)
241
+ if decision == ALLOW and status != 200:
242
+ # hallpass never allows with a non-200 status; do not trust a proxy that does.
243
+ return Decision(UNKNOWN, f"client_error: allow with HTTP {status}", status)
244
+ return Decision(decision, reason, status)
245
+
246
+
247
+ F = TypeVar("F", bound=Callable)
248
+
249
+ # Where the acting user (or their groups) comes from: a fixed value, a
250
+ # zero-argument callable, or a contextvars.ContextVar the application sets
251
+ # for the current session or request.
252
+ UserSource = Union[str, Callable[[], str], "contextvars.ContextVar[str]"]
253
+ GroupsSource = Union[Iterable[str], Callable[[], Iterable[str]], "contextvars.ContextVar[Iterable[str]]"]
254
+
255
+
256
+ def current(source: Any, what: str = "user") -> Any:
257
+ """Resolve a user or groups source now.
258
+
259
+ A ``ContextVar`` with nothing set for this session raises ``RuntimeError``
260
+ naming it, rather than a bare ``LookupError`` from inside a framework.
261
+ """
262
+ if isinstance(source, contextvars.ContextVar):
263
+ try:
264
+ return source.get()
265
+ except LookupError:
266
+ raise RuntimeError(f"no {what} set for this session in ContextVar {source.name!r}") from None
267
+ if callable(source):
268
+ return source()
269
+ return source
270
+
271
+
272
+ def _takes_one_dict(sig: inspect.Signature) -> bool:
273
+ """True for the Claude Agent SDK handler shape: one positional parameter
274
+ annotated as a dict or Mapping, which receives all the arguments."""
275
+ params = list(sig.parameters.values())
276
+ if len(params) != 1 or params[0].kind not in (params[0].POSITIONAL_ONLY, params[0].POSITIONAL_OR_KEYWORD):
277
+ return False
278
+ ann = params[0].annotation
279
+ if ann is inspect.Parameter.empty:
280
+ return False
281
+ name = ann if isinstance(ann, str) else getattr(ann, "__name__", None) or str(ann)
282
+ origin = getattr(ann, "__origin__", None)
283
+ if isinstance(origin, type) and issubclass(origin, Mapping):
284
+ return True
285
+ if isinstance(ann, type) and issubclass(ann, Mapping):
286
+ return True
287
+ return bool(re.match(r"(typing\.)?(dict|Dict|Mapping|MutableMapping)\b", name))
288
+
289
+
290
+ def guarded(
291
+ hp: Hallpass,
292
+ connection: str,
293
+ action: str,
294
+ resource: str,
295
+ *,
296
+ user: UserSource,
297
+ groups: GroupsSource | None = None,
298
+ deny: Callable[[PermissionDenied], Any] | None = None,
299
+ fresh: bool = False,
300
+ ) -> Callable[[F], F]:
301
+ """Decorate a function so it runs only after hallpass allowed it.
302
+
303
+ The user the check is for comes from ``user``: a string, a zero-argument
304
+ callable, or a ``contextvars.ContextVar`` the application sets for the
305
+ current session. It is never read from the call's arguments, so a
306
+ framework's ``@tool`` can sit directly on top and the model cannot pick
307
+ who it acts as; the decorated function's signature is exactly the
308
+ original's. ``groups`` works the same way and must yield a list.
309
+
310
+ ``resource`` is a format string over the call's arguments, e.g.
311
+ ``"issue:{key}"``; a parameter left at its default is available too. A
312
+ function with ordinary parameters is called with keyword arguments
313
+ (LangChain, Strands, MCP); a function whose only parameter is a dict
314
+ (the Claude Agent SDK handler shape, ``async def f(args: dict)``)
315
+ receives all the arguments in that dict, and a ``user`` key in it is
316
+ ignored, never honoured. ``async def`` is supported and the check then
317
+ runs in a worker thread.
318
+
319
+ Any answer other than ``allow`` raises ``PermissionDenied`` before the
320
+ body runs. With ``deny`` given, its return value is returned instead of
321
+ raising; use that where the framework would hide the exception's text
322
+ from the model (MCPServer does).
323
+
324
+ ``fresh=True`` makes every check skip hallpass's caches and ask the
325
+ upstream system now. Use it for destructive actions.
326
+
327
+ After the body has run, ``guarded`` logs one line on the ``hallpass``
328
+ logger (INFO): the decision, when the check was made, whether it was
329
+ fresh, and that the write was unconditional. hallpass only checked;
330
+ the write itself ran afterwards with no ``If-Match`` on the state
331
+ hallpass saw, so nobody reading the logs later should take check and
332
+ write for one atomic step.
333
+
334
+ @tool
335
+ @guarded(hp, "jira-main", "DELETE_ISSUES", "issue:{key}", user=current_user, fresh=True)
336
+ def delete_issue(key: str) -> str: ...
337
+ """
338
+
339
+ def wrap(fn: F) -> F:
340
+ sig = inspect.signature(fn)
341
+ one_dict = _takes_one_dict(sig)
342
+
343
+ def prepare(args: tuple, kwargs: dict):
344
+ if one_dict:
345
+ if len(args) != 1 or kwargs or not isinstance(args[0], Mapping):
346
+ raise TypeError(f"{fn.__name__} takes one dict of arguments")
347
+ fields, call = args[0], functools.partial(fn, args[0])
348
+ else:
349
+ if args:
350
+ raise TypeError(f"{fn.__name__} takes keyword arguments only")
351
+ bound = sig.bind(**kwargs) # a stray or missing argument fails here, before any check
352
+ bound.apply_defaults()
353
+ fields, call = bound.arguments, functools.partial(fn, **kwargs)
354
+ who = current(user, "user")
355
+ if not isinstance(who, str) or not who:
356
+ raise RuntimeError("guarded: user must be a non-empty string")
357
+ grp = None if groups is None else current(groups, "groups")
358
+ return who, grp, resource.format(**fields), call
359
+
360
+ def refused(e: PermissionDenied):
361
+ if deny is None:
362
+ raise e
363
+ return deny(e)
364
+
365
+ def ran(who: str, res: str, d: Decision, checked_at: datetime.datetime, outcome: str) -> None:
366
+ log.info(
367
+ "unconditional write: %s %s %s on %s in %s; hallpass said %s (%s) at %s, fresh=%s; "
368
+ "the write was not conditioned on the state hallpass saw (no If-Match), "
369
+ "so check and write were not atomic",
370
+ who, outcome, action, res, connection, d.decision, d.reason,
371
+ checked_at.isoformat(timespec="milliseconds"), fresh,
372
+ )
373
+
374
+ if inspect.iscoroutinefunction(fn):
375
+
376
+ @functools.wraps(fn)
377
+ async def inner(*args, **kwargs):
378
+ who, grp, res, call = prepare(args, kwargs)
379
+ checked_at = datetime.datetime.now(datetime.timezone.utc)
380
+ try:
381
+ d = await asyncio.to_thread(hp.require, who, connection, action, res, grp, fresh=fresh)
382
+ except PermissionDenied as e:
383
+ return refused(e)
384
+ try:
385
+ result = await call()
386
+ except BaseException as e:
387
+ ran(who, res, d, checked_at, f"raised {type(e).__name__} from")
388
+ raise
389
+ ran(who, res, d, checked_at, "ran")
390
+ return result
391
+
392
+ else:
393
+
394
+ @functools.wraps(fn)
395
+ def inner(*args, **kwargs):
396
+ who, grp, res, call = prepare(args, kwargs)
397
+ checked_at = datetime.datetime.now(datetime.timezone.utc)
398
+ try:
399
+ d = hp.require(who, connection, action, res, grp, fresh=fresh)
400
+ except PermissionDenied as e:
401
+ return refused(e)
402
+ try:
403
+ result = call()
404
+ except BaseException as e:
405
+ ran(who, res, d, checked_at, f"raised {type(e).__name__} from")
406
+ raise
407
+ ran(who, res, d, checked_at, "ran")
408
+ return result
409
+
410
+ inner.__signature__ = sig # type: ignore[attr-defined]
411
+ return inner # type: ignore[return-value]
412
+
413
+ return wrap
File without changes
@@ -0,0 +1,81 @@
1
+ """Checks the installed package, not the source tree.
2
+
3
+ pip install ./sdk/python && python -m unittest discover -s sdk/python/tests
4
+
5
+ The client's behaviour is tested in examples/agent/test_hallpass_client.py.
6
+ This makes sure the distribution itself is complete and works.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import http.server
12
+ import json
13
+ import os
14
+ import sys
15
+ import threading
16
+ import unittest
17
+ from contextvars import ContextVar
18
+
19
+ import hallpass_client
20
+ from hallpass_client import Hallpass, PermissionDenied, guarded
21
+
22
+
23
+ class _Fake(http.server.BaseHTTPRequestHandler):
24
+ def do_POST(self): # noqa: N802
25
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
26
+ ok = self.headers.get("Authorization") == "Bearer k" and body["user"] == "admin@example.com"
27
+ out = json.dumps({"decision": "allow" if ok else "deny", "reason": "allowed: x" if ok else "denied: x"}).encode()
28
+ self.send_response(200)
29
+ self.send_header("Content-Type", "application/json")
30
+ self.send_header("Content-Length", str(len(out)))
31
+ self.end_headers()
32
+ self.wfile.write(out)
33
+
34
+ def log_message(self, *args):
35
+ pass
36
+
37
+
38
+ class InstalledPackage(unittest.TestCase):
39
+ @classmethod
40
+ def setUpClass(cls):
41
+ cls.srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Fake)
42
+ threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
43
+ cls.hp = Hallpass(url=f"http://127.0.0.1:{cls.srv.server_address[1]}", api_key="k", timeout=2)
44
+
45
+ @classmethod
46
+ def tearDownClass(cls):
47
+ cls.srv.shutdown()
48
+
49
+ def test_imported_from_site_packages(self):
50
+ if os.environ.get("HALLPASS_SDK_REQUIRE_INSTALLED") == "1":
51
+ src = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src"))
52
+ self.assertFalse(os.path.abspath(hallpass_client.__file__).startswith(src), hallpass_client.__file__)
53
+
54
+ def test_typed_marker_shipped(self):
55
+ self.assertTrue(os.path.exists(os.path.join(os.path.dirname(hallpass_client.__file__), "py.typed")))
56
+
57
+ def test_allow_and_deny(self):
58
+ self.assertEqual(self.hp.check("admin@example.com", "demo", "thing.write", "thing:1").decision, "allow")
59
+ with self.assertRaises(PermissionDenied):
60
+ self.hp.require("dana@example.com", "demo", "thing.write", "thing:1")
61
+
62
+ def test_unreachable_is_unknown(self):
63
+ hp = Hallpass(url="http://127.0.0.1:9", api_key="k", timeout=1)
64
+ self.assertEqual(hp.check("admin@example.com", "demo", "thing.write", "thing:1").decision, "unknown")
65
+
66
+ def test_guarded(self):
67
+ user: ContextVar[str] = ContextVar("user")
68
+
69
+ @guarded(self.hp, "demo", "thing.write", "thing:{thing_id}", user=user)
70
+ def write(thing_id: str) -> str:
71
+ return "wrote " + thing_id
72
+
73
+ user.set("admin@example.com")
74
+ self.assertEqual(write(thing_id="1"), "wrote 1")
75
+ user.set("dana@example.com")
76
+ with self.assertRaises(PermissionDenied):
77
+ write(thing_id="1")
78
+
79
+
80
+ if __name__ == "__main__":
81
+ sys.exit(unittest.main())