appecosystem-auth 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.
- appecosystem_auth-0.4.0/LICENSE +21 -0
- appecosystem_auth-0.4.0/PKG-INFO +105 -0
- appecosystem_auth-0.4.0/README.md +76 -0
- appecosystem_auth-0.4.0/appecosystem_auth.egg-info/PKG-INFO +105 -0
- appecosystem_auth-0.4.0/appecosystem_auth.egg-info/SOURCES.txt +12 -0
- appecosystem_auth-0.4.0/appecosystem_auth.egg-info/dependency_links.txt +1 -0
- appecosystem_auth-0.4.0/appecosystem_auth.egg-info/requires.txt +5 -0
- appecosystem_auth-0.4.0/appecosystem_auth.egg-info/top_level.txt +1 -0
- appecosystem_auth-0.4.0/ecosystem_auth/__init__.py +37 -0
- appecosystem_auth-0.4.0/ecosystem_auth/middleware.py +126 -0
- appecosystem_auth-0.4.0/ecosystem_auth/setup.py +110 -0
- appecosystem_auth-0.4.0/ecosystem_auth/tokens.py +332 -0
- appecosystem_auth-0.4.0/pyproject.toml +43 -0
- appecosystem_auth-0.4.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 Mikel Smart
|
|
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,105 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: appecosystem-auth
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Shared HMAC-SHA256 request signing and verification for the appEcosystem service mesh
|
|
5
|
+
Author: Mikel Smart
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/M1K31/appEcosystem
|
|
8
|
+
Project-URL: Source, https://github.com/M1K31/appEcosystem
|
|
9
|
+
Project-URL: Issues, https://github.com/M1K31/appEcosystem/issues
|
|
10
|
+
Keywords: hmac,authentication,request-signing,microservices,appecosystem
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Security
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: fastapi>=0.100.0
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
27
|
+
Requires-Dist: httpx>=0.24; extra == "dev"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# appecosystem-auth
|
|
31
|
+
|
|
32
|
+
Shared HMAC-SHA256 request signing and verification for
|
|
33
|
+
[appEcosystem](https://github.com/M1K31/appEcosystem) services.
|
|
34
|
+
|
|
35
|
+
Every request between ecosystem services is signed with a shared secret. The
|
|
36
|
+
signed payload binds the method, canonical path, a timestamp and a unique
|
|
37
|
+
nonce, plus a digest of the body — so a captured request cannot be replayed.
|
|
38
|
+
|
|
39
|
+
Third-party applications are issued their own `key_id`, sent alongside the
|
|
40
|
+
signature, so their access can be identified, scoped and revoked independently
|
|
41
|
+
of the first-party services.
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install appecosystem-auth
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Requires Python 3.9+.
|
|
50
|
+
|
|
51
|
+
## Signing a request
|
|
52
|
+
|
|
53
|
+
`sign_request` returns the headers to attach; it does not send anything.
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import httpx
|
|
57
|
+
from ecosystem_auth.tokens import sign_request, get_ecosystem_secret
|
|
58
|
+
|
|
59
|
+
secret = get_ecosystem_secret()
|
|
60
|
+
body = {"type": "camera.motion", "source": "my-app", "data": {"camera": "front"}}
|
|
61
|
+
|
|
62
|
+
headers = sign_request(
|
|
63
|
+
"POST",
|
|
64
|
+
"/events/publish",
|
|
65
|
+
secret,
|
|
66
|
+
body=body,
|
|
67
|
+
key_id="k_your_app_key", # omit for first-party services
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
httpx.post("http://localhost:8500/events/publish", json=body, headers=headers)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`body` is the request body **as a dict**, not a pre-serialized string — it is
|
|
74
|
+
digested as part of the signature.
|
|
75
|
+
|
|
76
|
+
## Verifying a request (FastAPI)
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from fastapi import Depends, FastAPI
|
|
80
|
+
from ecosystem_auth.middleware import require_ecosystem_auth
|
|
81
|
+
|
|
82
|
+
app = FastAPI()
|
|
83
|
+
|
|
84
|
+
@app.post("/webhook")
|
|
85
|
+
async def webhook(principal: dict = Depends(require_ecosystem_auth)):
|
|
86
|
+
# principal carries the caller's identity and granted scopes
|
|
87
|
+
return {"caller": principal.get("app_id"), "scopes": principal.get("scopes")}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
An unsigned or badly-signed request is rejected before your handler runs.
|
|
91
|
+
|
|
92
|
+
## Where the secret comes from
|
|
93
|
+
|
|
94
|
+
`get_ecosystem_secret()` resolves in this order:
|
|
95
|
+
|
|
96
|
+
1. the `ECOSYSTEM_SECRET` environment variable
|
|
97
|
+
2. the file-backed store at `~/.config/ecosystem/secret.env` (mode `0600`)
|
|
98
|
+
|
|
99
|
+
Every service on a machine must resolve the *same* secret, or signatures will
|
|
100
|
+
not verify. Use `ecosystem_auth.setup.generate_secret()` /
|
|
101
|
+
`apply_secret()` to provision one.
|
|
102
|
+
|
|
103
|
+
## License
|
|
104
|
+
|
|
105
|
+
MIT — see [LICENSE](https://github.com/M1K31/appEcosystem/blob/main/LICENSE).
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# appecosystem-auth
|
|
2
|
+
|
|
3
|
+
Shared HMAC-SHA256 request signing and verification for
|
|
4
|
+
[appEcosystem](https://github.com/M1K31/appEcosystem) services.
|
|
5
|
+
|
|
6
|
+
Every request between ecosystem services is signed with a shared secret. The
|
|
7
|
+
signed payload binds the method, canonical path, a timestamp and a unique
|
|
8
|
+
nonce, plus a digest of the body — so a captured request cannot be replayed.
|
|
9
|
+
|
|
10
|
+
Third-party applications are issued their own `key_id`, sent alongside the
|
|
11
|
+
signature, so their access can be identified, scoped and revoked independently
|
|
12
|
+
of the first-party services.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install appecosystem-auth
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Requires Python 3.9+.
|
|
21
|
+
|
|
22
|
+
## Signing a request
|
|
23
|
+
|
|
24
|
+
`sign_request` returns the headers to attach; it does not send anything.
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import httpx
|
|
28
|
+
from ecosystem_auth.tokens import sign_request, get_ecosystem_secret
|
|
29
|
+
|
|
30
|
+
secret = get_ecosystem_secret()
|
|
31
|
+
body = {"type": "camera.motion", "source": "my-app", "data": {"camera": "front"}}
|
|
32
|
+
|
|
33
|
+
headers = sign_request(
|
|
34
|
+
"POST",
|
|
35
|
+
"/events/publish",
|
|
36
|
+
secret,
|
|
37
|
+
body=body,
|
|
38
|
+
key_id="k_your_app_key", # omit for first-party services
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
httpx.post("http://localhost:8500/events/publish", json=body, headers=headers)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`body` is the request body **as a dict**, not a pre-serialized string — it is
|
|
45
|
+
digested as part of the signature.
|
|
46
|
+
|
|
47
|
+
## Verifying a request (FastAPI)
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from fastapi import Depends, FastAPI
|
|
51
|
+
from ecosystem_auth.middleware import require_ecosystem_auth
|
|
52
|
+
|
|
53
|
+
app = FastAPI()
|
|
54
|
+
|
|
55
|
+
@app.post("/webhook")
|
|
56
|
+
async def webhook(principal: dict = Depends(require_ecosystem_auth)):
|
|
57
|
+
# principal carries the caller's identity and granted scopes
|
|
58
|
+
return {"caller": principal.get("app_id"), "scopes": principal.get("scopes")}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
An unsigned or badly-signed request is rejected before your handler runs.
|
|
62
|
+
|
|
63
|
+
## Where the secret comes from
|
|
64
|
+
|
|
65
|
+
`get_ecosystem_secret()` resolves in this order:
|
|
66
|
+
|
|
67
|
+
1. the `ECOSYSTEM_SECRET` environment variable
|
|
68
|
+
2. the file-backed store at `~/.config/ecosystem/secret.env` (mode `0600`)
|
|
69
|
+
|
|
70
|
+
Every service on a machine must resolve the *same* secret, or signatures will
|
|
71
|
+
not verify. Use `ecosystem_auth.setup.generate_secret()` /
|
|
72
|
+
`apply_secret()` to provision one.
|
|
73
|
+
|
|
74
|
+
## License
|
|
75
|
+
|
|
76
|
+
MIT — see [LICENSE](https://github.com/M1K31/appEcosystem/blob/main/LICENSE).
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: appecosystem-auth
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Shared HMAC-SHA256 request signing and verification for the appEcosystem service mesh
|
|
5
|
+
Author: Mikel Smart
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/M1K31/appEcosystem
|
|
8
|
+
Project-URL: Source, https://github.com/M1K31/appEcosystem
|
|
9
|
+
Project-URL: Issues, https://github.com/M1K31/appEcosystem/issues
|
|
10
|
+
Keywords: hmac,authentication,request-signing,microservices,appecosystem
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Security
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: fastapi>=0.100.0
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
27
|
+
Requires-Dist: httpx>=0.24; extra == "dev"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# appecosystem-auth
|
|
31
|
+
|
|
32
|
+
Shared HMAC-SHA256 request signing and verification for
|
|
33
|
+
[appEcosystem](https://github.com/M1K31/appEcosystem) services.
|
|
34
|
+
|
|
35
|
+
Every request between ecosystem services is signed with a shared secret. The
|
|
36
|
+
signed payload binds the method, canonical path, a timestamp and a unique
|
|
37
|
+
nonce, plus a digest of the body — so a captured request cannot be replayed.
|
|
38
|
+
|
|
39
|
+
Third-party applications are issued their own `key_id`, sent alongside the
|
|
40
|
+
signature, so their access can be identified, scoped and revoked independently
|
|
41
|
+
of the first-party services.
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install appecosystem-auth
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Requires Python 3.9+.
|
|
50
|
+
|
|
51
|
+
## Signing a request
|
|
52
|
+
|
|
53
|
+
`sign_request` returns the headers to attach; it does not send anything.
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import httpx
|
|
57
|
+
from ecosystem_auth.tokens import sign_request, get_ecosystem_secret
|
|
58
|
+
|
|
59
|
+
secret = get_ecosystem_secret()
|
|
60
|
+
body = {"type": "camera.motion", "source": "my-app", "data": {"camera": "front"}}
|
|
61
|
+
|
|
62
|
+
headers = sign_request(
|
|
63
|
+
"POST",
|
|
64
|
+
"/events/publish",
|
|
65
|
+
secret,
|
|
66
|
+
body=body,
|
|
67
|
+
key_id="k_your_app_key", # omit for first-party services
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
httpx.post("http://localhost:8500/events/publish", json=body, headers=headers)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`body` is the request body **as a dict**, not a pre-serialized string — it is
|
|
74
|
+
digested as part of the signature.
|
|
75
|
+
|
|
76
|
+
## Verifying a request (FastAPI)
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from fastapi import Depends, FastAPI
|
|
80
|
+
from ecosystem_auth.middleware import require_ecosystem_auth
|
|
81
|
+
|
|
82
|
+
app = FastAPI()
|
|
83
|
+
|
|
84
|
+
@app.post("/webhook")
|
|
85
|
+
async def webhook(principal: dict = Depends(require_ecosystem_auth)):
|
|
86
|
+
# principal carries the caller's identity and granted scopes
|
|
87
|
+
return {"caller": principal.get("app_id"), "scopes": principal.get("scopes")}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
An unsigned or badly-signed request is rejected before your handler runs.
|
|
91
|
+
|
|
92
|
+
## Where the secret comes from
|
|
93
|
+
|
|
94
|
+
`get_ecosystem_secret()` resolves in this order:
|
|
95
|
+
|
|
96
|
+
1. the `ECOSYSTEM_SECRET` environment variable
|
|
97
|
+
2. the file-backed store at `~/.config/ecosystem/secret.env` (mode `0600`)
|
|
98
|
+
|
|
99
|
+
Every service on a machine must resolve the *same* secret, or signatures will
|
|
100
|
+
not verify. Use `ecosystem_auth.setup.generate_secret()` /
|
|
101
|
+
`apply_secret()` to provision one.
|
|
102
|
+
|
|
103
|
+
## License
|
|
104
|
+
|
|
105
|
+
MIT — see [LICENSE](https://github.com/M1K31/appEcosystem/blob/main/LICENSE).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
appecosystem_auth.egg-info/PKG-INFO
|
|
5
|
+
appecosystem_auth.egg-info/SOURCES.txt
|
|
6
|
+
appecosystem_auth.egg-info/dependency_links.txt
|
|
7
|
+
appecosystem_auth.egg-info/requires.txt
|
|
8
|
+
appecosystem_auth.egg-info/top_level.txt
|
|
9
|
+
ecosystem_auth/__init__.py
|
|
10
|
+
ecosystem_auth/middleware.py
|
|
11
|
+
ecosystem_auth/setup.py
|
|
12
|
+
ecosystem_auth/tokens.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ecosystem_auth
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Ecosystem shared authentication - HMAC-SHA256 token generation and verification."""
|
|
2
|
+
|
|
3
|
+
from .tokens import (
|
|
4
|
+
NonceStore,
|
|
5
|
+
ensure_ecosystem_secret,
|
|
6
|
+
generate_secure_token,
|
|
7
|
+
get_ecosystem_secret,
|
|
8
|
+
hash_token,
|
|
9
|
+
secret_file_path,
|
|
10
|
+
sign_request,
|
|
11
|
+
verify_request,
|
|
12
|
+
verify_token_hash,
|
|
13
|
+
sign_payload,
|
|
14
|
+
verify_signature,
|
|
15
|
+
write_secret,
|
|
16
|
+
)
|
|
17
|
+
from .setup import apply_secret, generate_secret, secret_status
|
|
18
|
+
from .middleware import require_ecosystem_auth
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"NonceStore",
|
|
22
|
+
"ensure_ecosystem_secret",
|
|
23
|
+
"generate_secure_token",
|
|
24
|
+
"get_ecosystem_secret",
|
|
25
|
+
"hash_token",
|
|
26
|
+
"secret_file_path",
|
|
27
|
+
"sign_request",
|
|
28
|
+
"verify_request",
|
|
29
|
+
"verify_token_hash",
|
|
30
|
+
"sign_payload",
|
|
31
|
+
"verify_signature",
|
|
32
|
+
"write_secret",
|
|
33
|
+
"apply_secret",
|
|
34
|
+
"generate_secret",
|
|
35
|
+
"secret_status",
|
|
36
|
+
"require_ecosystem_auth",
|
|
37
|
+
]
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""FastAPI middleware/dependency for ecosystem authentication."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Callable, Optional
|
|
5
|
+
|
|
6
|
+
from fastapi import Depends, HTTPException, Request, status
|
|
7
|
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
8
|
+
|
|
9
|
+
from .tokens import (
|
|
10
|
+
KEY_ID_HEADER,
|
|
11
|
+
NONCE_HEADER,
|
|
12
|
+
NonceStore,
|
|
13
|
+
SIGNATURE_HEADER,
|
|
14
|
+
TIMESTAMP_HEADER,
|
|
15
|
+
get_ecosystem_secret,
|
|
16
|
+
verify_request,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
security_scheme = HTTPBearer(auto_error=False)
|
|
20
|
+
|
|
21
|
+
# Process-wide nonce cache for replay detection on the signature path.
|
|
22
|
+
_nonce_store = NonceStore()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
async def _read_body_obj(request: Request) -> dict:
|
|
26
|
+
raw = await request.body()
|
|
27
|
+
if request.method in ("GET", "DELETE") or not raw:
|
|
28
|
+
return {}
|
|
29
|
+
try:
|
|
30
|
+
return json.loads(raw)
|
|
31
|
+
except Exception:
|
|
32
|
+
raise HTTPException(
|
|
33
|
+
status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid JSON body"
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
async def authenticate_request(
|
|
38
|
+
request: Request,
|
|
39
|
+
credentials: Optional[HTTPAuthorizationCredentials],
|
|
40
|
+
key_resolver: Optional[Callable[[str], Optional[dict]]] = None,
|
|
41
|
+
) -> dict:
|
|
42
|
+
"""Verify an ecosystem-authenticated request and return its principal.
|
|
43
|
+
|
|
44
|
+
Per-app path: when an ``X-Ecosystem-Key-Id`` header is present AND a
|
|
45
|
+
``key_resolver`` is supplied, resolve the app, verify the HMAC against the
|
|
46
|
+
app's secret, and return that app's principal. Owner path: otherwise verify
|
|
47
|
+
against the shared secret and return the ``__owner__`` principal. Bearer
|
|
48
|
+
tokens are accepted as before. Raises ``HTTPException`` on any failure.
|
|
49
|
+
"""
|
|
50
|
+
signature = request.headers.get(SIGNATURE_HEADER)
|
|
51
|
+
if signature:
|
|
52
|
+
timestamp = request.headers.get(TIMESTAMP_HEADER)
|
|
53
|
+
nonce = request.headers.get(NONCE_HEADER)
|
|
54
|
+
body_obj = await _read_body_obj(request)
|
|
55
|
+
|
|
56
|
+
key_id = request.headers.get(KEY_ID_HEADER)
|
|
57
|
+
if key_id and key_resolver is not None:
|
|
58
|
+
principal = key_resolver(key_id)
|
|
59
|
+
if not principal:
|
|
60
|
+
raise HTTPException(
|
|
61
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
62
|
+
detail="Unknown or suspended ecosystem key",
|
|
63
|
+
)
|
|
64
|
+
secret = principal["secret"]
|
|
65
|
+
if not verify_request(
|
|
66
|
+
request.method, str(request.url), secret, signature,
|
|
67
|
+
timestamp, nonce, body_obj, nonce_store=_nonce_store,
|
|
68
|
+
):
|
|
69
|
+
raise HTTPException(
|
|
70
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
71
|
+
detail="Invalid, stale, or replayed ecosystem signature",
|
|
72
|
+
)
|
|
73
|
+
return {
|
|
74
|
+
"auth_method": "hmac",
|
|
75
|
+
"app_id": principal["app_id"],
|
|
76
|
+
"scopes": list(principal.get("scopes", [])),
|
|
77
|
+
"owned_names": list(principal.get("owned_names", [])),
|
|
78
|
+
"payload": body_obj,
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
# Owner path: shared secret.
|
|
82
|
+
secret = get_ecosystem_secret()
|
|
83
|
+
if not verify_request(
|
|
84
|
+
request.method, str(request.url), secret, signature,
|
|
85
|
+
timestamp, nonce, body_obj, nonce_store=_nonce_store,
|
|
86
|
+
):
|
|
87
|
+
raise HTTPException(
|
|
88
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
89
|
+
detail="Invalid, stale, or replayed ecosystem signature",
|
|
90
|
+
)
|
|
91
|
+
return {
|
|
92
|
+
"auth_method": "hmac",
|
|
93
|
+
"app_id": "__owner__",
|
|
94
|
+
"scopes": ["*"],
|
|
95
|
+
"owned_names": ["*"],
|
|
96
|
+
"payload": body_obj,
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if credentials:
|
|
100
|
+
from .tokens import verify_ecosystem_token
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
token_data = json.loads(credentials.credentials)
|
|
104
|
+
except (json.JSONDecodeError, TypeError):
|
|
105
|
+
raise HTTPException(
|
|
106
|
+
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token format"
|
|
107
|
+
)
|
|
108
|
+
if not verify_ecosystem_token(token_data, get_ecosystem_secret()):
|
|
109
|
+
raise HTTPException(
|
|
110
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
111
|
+
detail="Invalid or expired ecosystem token",
|
|
112
|
+
)
|
|
113
|
+
return {"auth_method": "token", "service": token_data.get("service")}
|
|
114
|
+
|
|
115
|
+
raise HTTPException(
|
|
116
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
117
|
+
detail="Missing ecosystem authentication",
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
async def require_ecosystem_auth(
|
|
122
|
+
request: Request,
|
|
123
|
+
credentials: Optional[HTTPAuthorizationCredentials] = Depends(security_scheme),
|
|
124
|
+
) -> dict:
|
|
125
|
+
"""FastAPI dependency: validate an ecosystem-authenticated request (shared-secret/owner)."""
|
|
126
|
+
return await authenticate_request(request, credentials, key_resolver=None)
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Framework-agnostic helpers for the in-app 'Ecosystem setup' secret panel.
|
|
2
|
+
|
|
3
|
+
Every app exposes the same browser-based second path (beside the
|
|
4
|
+
``ecosystem secret`` CLI) for provisioning the shared HMAC secret — especially
|
|
5
|
+
on a second device joining over the network. The web framework differs per app
|
|
6
|
+
(FastAPI, Flask, Express…), so the *route* lives in each app, but the security-
|
|
7
|
+
sensitive logic — validation, overwrite protection, never echoing the value —
|
|
8
|
+
is centralised here so all apps behave identically.
|
|
9
|
+
|
|
10
|
+
Endpoints in each app should wrap these:
|
|
11
|
+
GET status -> secret_status()
|
|
12
|
+
POST apply -> apply_secret(value, allow_overwrite=...)
|
|
13
|
+
POST generate-> generate_secret() (primary device only)
|
|
14
|
+
|
|
15
|
+
The secret value is NEVER returned by status; only whether one is configured.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
from typing import Optional
|
|
22
|
+
|
|
23
|
+
from .tokens import (
|
|
24
|
+
DEFAULT_DEV_SECRET,
|
|
25
|
+
generate_secure_token,
|
|
26
|
+
secret_file_path,
|
|
27
|
+
write_secret,
|
|
28
|
+
_read_secret_file,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
# A provisioned secret is hex (token_hex) — accept a generous hex range so a
|
|
32
|
+
# manually-pasted value from another device is allowed, but reject obviously
|
|
33
|
+
# malformed input early with a clear message.
|
|
34
|
+
_HEX_RE = re.compile(r"^[0-9a-fA-F]{32,128}$")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _current_secret() -> Optional[str]:
|
|
38
|
+
"""The secret currently in effect (env wins over file), or None."""
|
|
39
|
+
return os.environ.get("ECOSYSTEM_HMAC_SECRET") or _read_secret_file()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def secret_status() -> dict:
|
|
43
|
+
"""Report whether a usable shared secret is configured — never its value.
|
|
44
|
+
|
|
45
|
+
``source`` is "env", "file", or None. ``path`` is where the UI tells the
|
|
46
|
+
user the file lives. ``masked`` is a safe fingerprint (first 6 hex chars +
|
|
47
|
+
length) so a user can confirm two devices match without exposing the key."""
|
|
48
|
+
env = os.environ.get("ECOSYSTEM_HMAC_SECRET")
|
|
49
|
+
file_val = _read_secret_file()
|
|
50
|
+
current = env or file_val
|
|
51
|
+
configured = bool(current) and current != DEFAULT_DEV_SECRET
|
|
52
|
+
masked = None
|
|
53
|
+
if configured and current:
|
|
54
|
+
masked = f"{current[:6]}…({len(current)} chars)"
|
|
55
|
+
return {
|
|
56
|
+
"configured": configured,
|
|
57
|
+
"source": "env" if env else ("file" if file_val else None),
|
|
58
|
+
"path": str(secret_file_path()),
|
|
59
|
+
"masked": masked,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def apply_secret(value: str, allow_overwrite: bool = False) -> dict:
|
|
64
|
+
"""Validate and persist a pasted secret. Returns the new status.
|
|
65
|
+
|
|
66
|
+
Raises ``ValueError`` for malformed input, the dev default, or an attempt to
|
|
67
|
+
change an already-configured secret without ``allow_overwrite`` (overwrite
|
|
68
|
+
protection — the route gates this to a confirmed, loopback request)."""
|
|
69
|
+
value = (value or "").strip()
|
|
70
|
+
if not value:
|
|
71
|
+
raise ValueError("Secret is empty.")
|
|
72
|
+
if value == DEFAULT_DEV_SECRET:
|
|
73
|
+
raise ValueError(
|
|
74
|
+
"That is the known development default — refused. Generate a unique "
|
|
75
|
+
"value instead."
|
|
76
|
+
)
|
|
77
|
+
if not _HEX_RE.match(value):
|
|
78
|
+
raise ValueError(
|
|
79
|
+
"Secret must be 32–128 hexadecimal characters (e.g. the output of "
|
|
80
|
+
"`ecosystem secret generate`)."
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
existing = _current_secret()
|
|
84
|
+
if (
|
|
85
|
+
existing
|
|
86
|
+
and existing != DEFAULT_DEV_SECRET
|
|
87
|
+
and existing != value
|
|
88
|
+
and not allow_overwrite
|
|
89
|
+
):
|
|
90
|
+
raise ValueError(
|
|
91
|
+
"A different shared secret is already configured. Re-submit with "
|
|
92
|
+
"overwrite confirmed to replace it (this will break auth with peers "
|
|
93
|
+
"that still use the old secret)."
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
write_secret(value)
|
|
97
|
+
return secret_status()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def generate_secret() -> dict:
|
|
101
|
+
"""Generate, persist, and return a fresh secret (PRIMARY device only).
|
|
102
|
+
|
|
103
|
+
Unlike :func:`secret_status`, this returns the raw value once so the user can
|
|
104
|
+
copy it to other devices. Callers must gate this to the first/primary host —
|
|
105
|
+
a joining device should *paste* the existing secret, not mint a new one."""
|
|
106
|
+
value = generate_secure_token(32)
|
|
107
|
+
write_secret(value)
|
|
108
|
+
status = secret_status()
|
|
109
|
+
status["secret"] = value # returned exactly once, for copy-to-other-devices
|
|
110
|
+
return status
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
"""
|
|
2
|
+
HMAC-SHA256 token generation and verification.
|
|
3
|
+
|
|
4
|
+
Extracted from OpenEye's ecosystem_security.py for cross-project reuse.
|
|
5
|
+
All projects in the ecosystem use the same HMAC secret for inter-service auth.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import hmac
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import secrets
|
|
13
|
+
import time
|
|
14
|
+
from typing import Optional
|
|
15
|
+
|
|
16
|
+
# Known insecure development default. There is intentionally NO automatic
|
|
17
|
+
# fallback to it — a committed shared secret is a forgeable credential. The
|
|
18
|
+
# constant is kept only so we can explicitly reject it if someone sets it.
|
|
19
|
+
DEFAULT_DEV_SECRET = "dev-ecosystem-secret-change-in-production"
|
|
20
|
+
|
|
21
|
+
# Single source of truth for the shared secret on a device. Every service
|
|
22
|
+
# (launchd, systemd, or shell) reads this same file at runtime, so writing it
|
|
23
|
+
# once provisions the whole machine — no launchctl setenv / per-plist env needed.
|
|
24
|
+
# Override the location with ECOSYSTEM_SECRET_FILE.
|
|
25
|
+
import pathlib
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def secret_file_path() -> "pathlib.Path":
|
|
29
|
+
return pathlib.Path(
|
|
30
|
+
os.environ.get("ECOSYSTEM_SECRET_FILE", "")
|
|
31
|
+
or (pathlib.Path.home() / ".config" / "ecosystem" / "secret.env")
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _read_secret_file() -> Optional[str]:
|
|
36
|
+
"""Read ECOSYSTEM_HMAC_SECRET from the shared secret file, if present."""
|
|
37
|
+
p = secret_file_path()
|
|
38
|
+
try:
|
|
39
|
+
if not p.exists():
|
|
40
|
+
return None
|
|
41
|
+
for raw in p.read_text().splitlines():
|
|
42
|
+
line = raw.strip()
|
|
43
|
+
if not line or line.startswith("#"):
|
|
44
|
+
continue
|
|
45
|
+
if line.startswith("export "):
|
|
46
|
+
line = line[len("export "):]
|
|
47
|
+
if line.startswith("ECOSYSTEM_HMAC_SECRET="):
|
|
48
|
+
val = line.split("=", 1)[1].strip().strip('"').strip("'")
|
|
49
|
+
return val or None
|
|
50
|
+
except Exception:
|
|
51
|
+
return None
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _validate_secret(secret: str) -> str:
|
|
56
|
+
if secret == DEFAULT_DEV_SECRET:
|
|
57
|
+
raise RuntimeError(
|
|
58
|
+
"Refusing the known development default secret. "
|
|
59
|
+
"Set a unique generated value (e.g. `ecosystem secret generate`)."
|
|
60
|
+
)
|
|
61
|
+
return secret
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def get_ecosystem_secret(override: Optional[str] = None) -> str:
|
|
65
|
+
"""
|
|
66
|
+
Resolve the shared HMAC secret. Resolution order:
|
|
67
|
+
explicit override -> ECOSYSTEM_HMAC_SECRET env -> ~/.config/ecosystem/secret.env
|
|
68
|
+
|
|
69
|
+
Fail-closed: there is no built-in default. If none is found (or it is the
|
|
70
|
+
known development default), a RuntimeError is raised rather than trusting a
|
|
71
|
+
guessable key. Provision one with `ecosystem secret generate` / `import`.
|
|
72
|
+
"""
|
|
73
|
+
secret = override or os.environ.get("ECOSYSTEM_HMAC_SECRET") or _read_secret_file()
|
|
74
|
+
if not secret:
|
|
75
|
+
raise RuntimeError(
|
|
76
|
+
"No ecosystem secret found (checked override, ECOSYSTEM_HMAC_SECRET, "
|
|
77
|
+
f"and {secret_file_path()}). A shared secret is required and there is "
|
|
78
|
+
"no default. Run `ecosystem secret generate` (or `ecosystem secret "
|
|
79
|
+
"import <value>` on additional devices)."
|
|
80
|
+
)
|
|
81
|
+
return _validate_secret(secret)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def write_secret(value: str) -> "pathlib.Path":
|
|
85
|
+
"""Persist a secret to the shared file (chmod 600). Returns the path."""
|
|
86
|
+
value = _validate_secret(value.strip())
|
|
87
|
+
if not value:
|
|
88
|
+
raise ValueError("Refusing to write an empty secret")
|
|
89
|
+
p = secret_file_path()
|
|
90
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
91
|
+
p.write_text(f"ECOSYSTEM_HMAC_SECRET={value}\n")
|
|
92
|
+
try:
|
|
93
|
+
p.chmod(0o600)
|
|
94
|
+
except Exception:
|
|
95
|
+
pass
|
|
96
|
+
return p
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def ensure_ecosystem_secret() -> str:
|
|
100
|
+
"""Return the existing shared secret, or generate+persist one (install-time).
|
|
101
|
+
|
|
102
|
+
Unlike get_ecosystem_secret (read-only, runtime), this MAY create the secret
|
|
103
|
+
file — use it from installers / the `ecosystem secret` CLI, never per-request.
|
|
104
|
+
"""
|
|
105
|
+
existing = (
|
|
106
|
+
os.environ.get("ECOSYSTEM_HMAC_SECRET") or _read_secret_file()
|
|
107
|
+
)
|
|
108
|
+
if existing and existing != DEFAULT_DEV_SECRET:
|
|
109
|
+
return existing
|
|
110
|
+
generated = secrets.token_hex(32)
|
|
111
|
+
write_secret(generated)
|
|
112
|
+
return generated
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def generate_secure_token(length: int = 32) -> str:
|
|
116
|
+
"""Generate a cryptographically secure hex token."""
|
|
117
|
+
return secrets.token_hex(length)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def hash_token(token: str) -> str:
|
|
121
|
+
"""Create a one-way SHA-256 hash of a token for secure storage."""
|
|
122
|
+
return hashlib.sha256(token.encode()).hexdigest()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def verify_token_hash(token: str, token_hash: str) -> bool:
|
|
126
|
+
"""Verify a token against its stored hash using constant-time comparison."""
|
|
127
|
+
return hmac.compare_digest(hash_token(token), token_hash)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def sign_payload(payload: dict, secret: str) -> str:
|
|
131
|
+
"""
|
|
132
|
+
Sign a payload with HMAC-SHA256.
|
|
133
|
+
|
|
134
|
+
The payload is JSON-serialized with sorted keys for deterministic output,
|
|
135
|
+
ensuring the same payload produces the same signature across Python and JS.
|
|
136
|
+
"""
|
|
137
|
+
message = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str).encode()
|
|
138
|
+
return hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def verify_signature(payload: dict, signature: str, secret: str) -> bool:
|
|
142
|
+
"""Verify the HMAC-SHA256 signature of a payload (constant-time comparison)."""
|
|
143
|
+
expected = sign_payload(payload, secret)
|
|
144
|
+
return hmac.compare_digest(expected, signature)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _canonical_path(url: str) -> str:
|
|
148
|
+
"""Return a host-independent canonical path (path + sorted query)."""
|
|
149
|
+
from urllib.parse import urlsplit, parse_qsl, urlencode
|
|
150
|
+
|
|
151
|
+
parts = urlsplit(url)
|
|
152
|
+
query = urlencode(sorted(parse_qsl(parts.query, keep_blank_values=True)))
|
|
153
|
+
return parts.path + (f"?{query}" if query else "")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def canonical_body_digest(body: Optional[dict]) -> str:
|
|
157
|
+
"""SHA-256 of the canonical JSON form of a request body.
|
|
158
|
+
|
|
159
|
+
Hashing the re-serialized (sorted, compact) form makes the digest
|
|
160
|
+
independent of on-the-wire JSON formatting, so client and server agree.
|
|
161
|
+
A missing/empty body hashes as ``{}``.
|
|
162
|
+
"""
|
|
163
|
+
obj = body if body else {}
|
|
164
|
+
message = json.dumps(obj, sort_keys=True, separators=(",", ":"), default=str).encode()
|
|
165
|
+
return hashlib.sha256(message).hexdigest()
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _request_payload(method: str, url: str, ts: int, nonce: str, body: Optional[dict]) -> dict:
|
|
169
|
+
"""Build the canonical dict that is signed for a request."""
|
|
170
|
+
return {
|
|
171
|
+
"method": method.upper(),
|
|
172
|
+
"path": _canonical_path(url),
|
|
173
|
+
"ts": ts,
|
|
174
|
+
"nonce": nonce,
|
|
175
|
+
"body_sha256": canonical_body_digest(body),
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# Header names for the replay-resistant request signature scheme.
|
|
180
|
+
SIGNATURE_HEADER = "X-Ecosystem-Signature"
|
|
181
|
+
TIMESTAMP_HEADER = "X-Ecosystem-Timestamp"
|
|
182
|
+
NONCE_HEADER = "X-Ecosystem-Nonce"
|
|
183
|
+
KEY_ID_HEADER = "X-Ecosystem-Key-Id"
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def sign_request(
|
|
187
|
+
method: str,
|
|
188
|
+
url: str,
|
|
189
|
+
secret: str,
|
|
190
|
+
body: Optional[dict] = None,
|
|
191
|
+
ts: Optional[int] = None,
|
|
192
|
+
nonce: Optional[str] = None,
|
|
193
|
+
key_id: Optional[str] = None,
|
|
194
|
+
) -> dict:
|
|
195
|
+
"""Produce signature/timestamp/nonce headers for an authenticated request.
|
|
196
|
+
|
|
197
|
+
The signed payload binds method, canonical path, a timestamp and a unique
|
|
198
|
+
nonce, plus a digest of the body, so captured requests cannot be replayed.
|
|
199
|
+
``key_id`` (optional) is attached as a header to identify a per-app
|
|
200
|
+
credential; it is NOT part of the signed payload.
|
|
201
|
+
"""
|
|
202
|
+
ts = int(time.time()) if ts is None else ts
|
|
203
|
+
nonce = nonce or secrets.token_hex(16)
|
|
204
|
+
payload = _request_payload(method, url, ts, nonce, body)
|
|
205
|
+
headers = {
|
|
206
|
+
SIGNATURE_HEADER: sign_payload(payload, secret),
|
|
207
|
+
TIMESTAMP_HEADER: str(ts),
|
|
208
|
+
NONCE_HEADER: nonce,
|
|
209
|
+
}
|
|
210
|
+
if key_id:
|
|
211
|
+
headers[KEY_ID_HEADER] = key_id
|
|
212
|
+
return headers
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def verify_request(
|
|
216
|
+
method: str,
|
|
217
|
+
url: str,
|
|
218
|
+
secret: str,
|
|
219
|
+
signature: Optional[str],
|
|
220
|
+
timestamp: Optional[str],
|
|
221
|
+
nonce: Optional[str],
|
|
222
|
+
body: Optional[dict] = None,
|
|
223
|
+
max_skew_seconds: int = 300,
|
|
224
|
+
nonce_store: Optional["NonceStore"] = None,
|
|
225
|
+
) -> bool:
|
|
226
|
+
"""Verify a replay-resistant request signature.
|
|
227
|
+
|
|
228
|
+
Checks the signature, that the timestamp is within ``max_skew_seconds`` of
|
|
229
|
+
now, and (when a ``nonce_store`` is supplied) that the nonce has not been
|
|
230
|
+
seen before within its retention window.
|
|
231
|
+
"""
|
|
232
|
+
if not signature or not timestamp or not nonce:
|
|
233
|
+
return False
|
|
234
|
+
try:
|
|
235
|
+
ts = int(timestamp)
|
|
236
|
+
except (TypeError, ValueError):
|
|
237
|
+
return False
|
|
238
|
+
if abs(int(time.time()) - ts) > max_skew_seconds:
|
|
239
|
+
return False
|
|
240
|
+
payload = _request_payload(method, url, ts, nonce, body)
|
|
241
|
+
if not verify_signature(payload, signature, secret):
|
|
242
|
+
return False
|
|
243
|
+
if nonce_store is not None and not nonce_store.add_if_new(nonce):
|
|
244
|
+
return False
|
|
245
|
+
return True
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
class NonceStore:
|
|
249
|
+
"""In-memory nonce cache with time-based expiry for replay detection.
|
|
250
|
+
|
|
251
|
+
Suitable for a single-process registry. For multi-instance deployments back
|
|
252
|
+
this with a shared store (e.g. Redis) keyed by nonce with a TTL.
|
|
253
|
+
"""
|
|
254
|
+
|
|
255
|
+
def __init__(self, ttl_seconds: int = 600):
|
|
256
|
+
self.ttl = ttl_seconds
|
|
257
|
+
self._seen: dict[str, float] = {}
|
|
258
|
+
|
|
259
|
+
def add_if_new(self, nonce: str) -> bool:
|
|
260
|
+
"""Record a nonce; return False if it was already seen (a replay)."""
|
|
261
|
+
now = time.time()
|
|
262
|
+
self._purge(now)
|
|
263
|
+
if nonce in self._seen:
|
|
264
|
+
return False
|
|
265
|
+
self._seen[nonce] = now
|
|
266
|
+
return True
|
|
267
|
+
|
|
268
|
+
def _purge(self, now: float) -> None:
|
|
269
|
+
expired = [n for n, t in self._seen.items() if now - t > self.ttl]
|
|
270
|
+
for n in expired:
|
|
271
|
+
del self._seen[n]
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def create_ecosystem_token(secret: str, service_name: str, ttl_seconds: int = 86400) -> dict:
|
|
275
|
+
"""
|
|
276
|
+
Create a signed ecosystem token for inter-service communication.
|
|
277
|
+
|
|
278
|
+
Returns a dict with token, issued_at, expires_at, and signature.
|
|
279
|
+
"""
|
|
280
|
+
now = int(time.time())
|
|
281
|
+
token = generate_secure_token()
|
|
282
|
+
token_data = {
|
|
283
|
+
"token": token,
|
|
284
|
+
"service": service_name,
|
|
285
|
+
"issued_at": now,
|
|
286
|
+
"expires_at": now + ttl_seconds,
|
|
287
|
+
}
|
|
288
|
+
token_data["signature"] = sign_payload(
|
|
289
|
+
{
|
|
290
|
+
"token": token,
|
|
291
|
+
"service": service_name,
|
|
292
|
+
"issued_at": now,
|
|
293
|
+
"expires_at": now + ttl_seconds,
|
|
294
|
+
},
|
|
295
|
+
secret,
|
|
296
|
+
)
|
|
297
|
+
return token_data
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# Maximum acceptable token lifetime (issued_at -> expires_at). Even a correctly
|
|
301
|
+
# signed token is rejected if it claims a longer life, capping the blast radius
|
|
302
|
+
# of a leaked secret. Default is double the standard 24h validity.
|
|
303
|
+
MAX_TOKEN_LIFETIME_SECONDS = 172800 # 48h
|
|
304
|
+
# Tolerance for clock skew when checking issued_at is not in the future.
|
|
305
|
+
_CLOCK_SKEW_SECONDS = 60
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def verify_ecosystem_token(token_data: dict, secret: str) -> bool:
|
|
309
|
+
"""
|
|
310
|
+
Verify a signed ecosystem token is valid, unexpired, and sanely scoped.
|
|
311
|
+
"""
|
|
312
|
+
now = int(time.time())
|
|
313
|
+
|
|
314
|
+
issued_at = token_data.get("issued_at", 0)
|
|
315
|
+
expires_at = token_data.get("expires_at", 0)
|
|
316
|
+
|
|
317
|
+
# Expired, or issued in the future (beyond clock skew).
|
|
318
|
+
if now > expires_at:
|
|
319
|
+
return False
|
|
320
|
+
if issued_at > now + _CLOCK_SKEW_SECONDS:
|
|
321
|
+
return False
|
|
322
|
+
# Reject implausibly long-lived tokens regardless of a valid signature.
|
|
323
|
+
if expires_at - issued_at > MAX_TOKEN_LIFETIME_SECONDS:
|
|
324
|
+
return False
|
|
325
|
+
|
|
326
|
+
expected_payload = {
|
|
327
|
+
"token": token_data.get("token", ""),
|
|
328
|
+
"service": token_data.get("service", ""),
|
|
329
|
+
"issued_at": issued_at,
|
|
330
|
+
"expires_at": expires_at,
|
|
331
|
+
}
|
|
332
|
+
return verify_signature(expected_payload, token_data.get("signature", ""), secret)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
# >=77 for the PEP 639 `license`/`license-files` fields used below.
|
|
3
|
+
requires = ["setuptools>=77.0", "wheel"]
|
|
4
|
+
build-backend = "setuptools.build_meta"
|
|
5
|
+
|
|
6
|
+
[project]
|
|
7
|
+
# Prefixed to group the family under the reserved `appEcosystem` PyPI name;
|
|
8
|
+
# PyPI organizations/namespaces are not available to this project yet. The
|
|
9
|
+
# import name is unchanged: `pip install appecosystem-auth` -> `import ecosystem_auth`.
|
|
10
|
+
name = "appecosystem-auth"
|
|
11
|
+
version = "0.4.0"
|
|
12
|
+
description = "Shared HMAC-SHA256 request signing and verification for the appEcosystem service mesh"
|
|
13
|
+
readme = "README.md"
|
|
14
|
+
license = "MIT"
|
|
15
|
+
license-files = ["LICENSE"]
|
|
16
|
+
requires-python = ">=3.9"
|
|
17
|
+
authors = [{ name = "Mikel Smart" }]
|
|
18
|
+
keywords = ["hmac", "authentication", "request-signing", "microservices", "appecosystem"]
|
|
19
|
+
classifiers = [
|
|
20
|
+
"Development Status :: 4 - Beta",
|
|
21
|
+
"Intended Audience :: Developers",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Programming Language :: Python :: 3.9",
|
|
25
|
+
"Programming Language :: Python :: 3.10",
|
|
26
|
+
"Programming Language :: Python :: 3.11",
|
|
27
|
+
"Programming Language :: Python :: 3.12",
|
|
28
|
+
"Topic :: Security",
|
|
29
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
30
|
+
]
|
|
31
|
+
dependencies = ["fastapi>=0.100.0"]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Homepage = "https://github.com/M1K31/appEcosystem"
|
|
35
|
+
Source = "https://github.com/M1K31/appEcosystem"
|
|
36
|
+
Issues = "https://github.com/M1K31/appEcosystem/issues"
|
|
37
|
+
|
|
38
|
+
[project.optional-dependencies]
|
|
39
|
+
dev = ["pytest>=7.0", "httpx>=0.24"]
|
|
40
|
+
|
|
41
|
+
[tool.setuptools.packages.find]
|
|
42
|
+
where = ["."]
|
|
43
|
+
include = ["ecosystem_auth*"]
|