Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions libs/kest-core/python/examples/bench/bench_fastapi.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import asyncio
import os
import threading
import time

import httpx
import uvicorn
from fastapi import FastAPI
from kest.core import CedarLocalEngine, MockIdentityProvider, configure, kest_verified

app = FastAPI()

# ---------------------------------------------------------
# Set up Kest backend
# ---------------------------------------------------------
from kest.core import CedarLocalEngine, MockIdentityProvider, configure, kest_verified

configure(
identity=MockIdentityProvider("abc"),
Expand Down
8 changes: 7 additions & 1 deletion libs/kest-core/python/examples/bench/bench_throughput.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,13 @@
# Allow running from the bench directory or from the project root.
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../"))

from kest.core import KestEntry, sign_entry, LocalEd25519Provider, Passport, PassportVerifier
from kest.core import (
KestEntry,
sign_entry,
LocalEd25519Provider,
Passport,
PassportVerifier,
)

PROVIDER = LocalEd25519Provider()
THREAD_COUNTS = [1, 2, 4, 8]
Expand Down
43 changes: 25 additions & 18 deletions libs/kest-core/python/src/kest/core/identity/providers/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ def __init__(self, *args, **kwargs):
self.kest_code: Optional[str] = None
self.kest_state: Optional[str] = None


class OAuthCallbackHandler(BaseHTTPRequestHandler):
"""Handles the local redirect callback for the OAuth Authorization Code flow."""

Expand Down Expand Up @@ -50,7 +51,7 @@ def log_message(self, format: str, *args) -> None:
class OAuthCliProvider(IdentityProvider):
"""
An Identity Engine that performs an Authorization Code Flow + PKCE local OAuth callback.

Determines the root Ed25519 identity key deterministically by hashing the OAuth identity's
unique identifier combined with a user-provided passphrase using PBKDF2HMAC.
"""
Expand All @@ -70,7 +71,7 @@ def __init__(
self.token_url = token_url
self.auto_open_browser = auto_open_browser
self.passphrase_provider = passphrase_provider

self.server_port = port
self.state = None
self.code_verifier = None
Expand All @@ -85,7 +86,9 @@ def _generate_pkce(self) -> tuple[str, str]:
verifier = secrets.token_urlsafe(32)
digest = hashes.Hash(hashes.SHA256())
digest.update(verifier.encode("ascii"))
challenge = base64.urlsafe_b64encode(digest.finalize()).decode("ascii").rstrip("=")
challenge = (
base64.urlsafe_b64encode(digest.finalize()).decode("ascii").rstrip("=")
)
return verifier, challenge

def _get_user_id_from_token(self, id_token: str) -> str:
Expand All @@ -109,29 +112,31 @@ def _get_user_id_from_token(self, id_token: str) -> str:
def _initialize_key(self, user_id: str) -> None:
"""Deterministically generates the Ed25519 key using PBKDF2 on user_id + passphrase."""
passphrase = self.passphrase_provider()

# We use the user_id as a salt (in a real scenario, a static realm/app salt could also be added)
salt = user_id.encode("utf-8")

kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
)
key_material = kdf.derive(passphrase.encode("utf-8"))

self._identity = user_id
self._private_key = ed25519.Ed25519PrivateKey.from_private_bytes(key_material)

def _authenticate(self) -> None:
"""Runs the local server to capture the OAuth flow."""
self.state = secrets.token_urlsafe(16)
self.code_verifier, code_challenge = self._generate_pkce()

server = KestOAuthServer(("localhost", self.server_port), OAuthCallbackHandler)
self.server_port = server.server_address[1] # Update to actual bound port (useful if port=0)

self.server_port = server.server_address[
1
] # Update to actual bound port (useful if port=0)

redirect_uri = f"http://localhost:{self.server_port}/callback"

params = {
Expand All @@ -143,9 +148,9 @@ def _authenticate(self) -> None:
"code_challenge_method": "S256",
"scope": "openid profile email",
}

url = f"{self.auth_url}?{urlencode(params)}"

if self.auto_open_browser:
webbrowser.open(url)
else:
Expand All @@ -154,10 +159,10 @@ def _authenticate(self) -> None:
# We wait for 1 request
server.kest_code = None
server.kest_state = None

while server.kest_code is None:
server.handle_request()

code = server.kest_code
state = server.kest_state
server.server_close()
Expand All @@ -173,18 +178,20 @@ def _authenticate(self) -> None:
"redirect_uri": redirect_uri,
"code_verifier": self.code_verifier,
}

resp = httpx.post(self.token_url, data=token_data)
resp.raise_for_status()

tokens = resp.json()

# Test override hook
if self._test_user_id:
user_id = self._test_user_id
else:
if "id_token" not in tokens:
raise ValueError("Response missing id_token. Cannot extract user identity.")
raise ValueError(
"Response missing id_token. Cannot extract user identity."
)
user_id = self._get_user_id_from_token(tokens["id_token"])

self._initialize_key(user_id)
Expand All @@ -199,7 +206,7 @@ def sign(self, payload: bytes) -> str:
"""Signs the payload using the deterministically derived Ed25519 private key."""
if not self._private_key or not self._identity:
self._authenticate()

# Ensure it's not None for type checker
assert self._private_key is not None
assert self._identity is not None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@

from kest.core.identity.providers.oauth import OAuthCliProvider


@pytest.fixture
def mock_passphrase():
return lambda: "test-passphrase-123"


@respx.mock
def test_oauth_cli_provider_flow(mock_passphrase):
# Mock the token endpoint
Expand All @@ -21,76 +23,77 @@ def test_oauth_cli_provider_flow(mock_passphrase):
json={
"access_token": "mock-access",
"id_token": "mock-id-token",
"token_type": "Bearer"
}
"token_type": "Bearer",
},
)
)

provider = OAuthCliProvider(
client_id="test-client-id",
auth_url="https://auth.example.com/auth",
token_url="https://auth.example.com/token",
auto_open_browser=False,
auto_open_browser=False,
passphrase_provider=mock_passphrase,
port=0,
# We need to mock decoded ID token or userinfo since we aren't doing real JWT validation
_test_user_id="user-123"
_test_user_id="user-123",
)

# We need a way to know what port the provider bound to and what state it generated.
# The provider's get_identity() is blocking. We can run it in a thread.
result_container = {}

def run_provider():
try:
# Overriding get_identity to return "user-123" and initialize the key
identity = provider.get_identity()
result_container["identity"] = identity
except Exception as e:
result_container["error"] = e

provider_thread = threading.Thread(target=run_provider)
provider_thread.start()

# Wait for the server to start (we assume port is set on provider instance)
# Give it a tiny bit of time
time.sleep(0.1)

# Verify the PKCE state
assert provider.state is not None
assert provider.code_verifier is not None

# Simulate the browser callback
port = provider.server_port
callback_url = f"http://localhost:{port}/callback?code=test-code&state={provider.state}"

callback_url = (
f"http://localhost:{port}/callback?code=test-code&state={provider.state}"
)

response = urllib.request.urlopen(callback_url)
assert response.status == 200
assert b"Success" in response.read()

provider_thread.join(timeout=2)

assert "error" not in result_container
assert result_container.get("identity") == "user-123"

# Check that signature is stable and valid Ed25519
payload = b"hello world"
sig = provider.sign(payload)
assert payload in base64.urlsafe_b64decode(sig.split('.')[1] + "==")

assert payload in base64.urlsafe_b64decode(sig.split(".")[1] + "==")

# Test stability: recreate provider with same mock inputs
provider2 = OAuthCliProvider(
client_id="test-client-id",
auth_url="https://auth.example.com/auth",
token_url="https://auth.example.com/token",
auto_open_browser=False,
auto_open_browser=False,
passphrase_provider=mock_passphrase,
port=0,
_test_user_id="user-123"
_test_user_id="user-123",
)
# The key is generated dynamically after login. Let's force it here.
provider2._initialize_key("user-123")
assert provider2.get_identity() == "user-123"
assert provider2.sign(payload) == sig

12 changes: 6 additions & 6 deletions libs/kest-core/python/src/kest/core/policies/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
class RegoValidator:
"""
Validates Rego policy syntax structurally without executing it.

Requires the optional `rego` extra (regopy).
"""

Expand All @@ -18,10 +18,10 @@ def __init__(self) -> None:
def validate_syntax(self, policy_str: str) -> None:
"""
Validates the syntax of a Rego policy string.

Args:
policy_str: The Rego policy to validate.

Raises:
ValueError: If the policy has syntax errors.
"""
Expand All @@ -35,7 +35,7 @@ def validate_syntax(self, policy_str: str) -> None:
class CedarValidator:
"""
Validates Cedar policy syntax and optionally validates against a specific Cedar Schema.

Requires the optional `cedar` extra (cedarpy).
"""

Expand All @@ -51,11 +51,11 @@ def validate_syntax(
) -> None:
"""
Validates the syntax of a Cedar policy, and optionally checks it against a schema.

Args:
policy_str: The Cedar policy string to validate.
schema: Optional schema (Cedar schema syntax or JSON) to validate against.

Raises:
ValueError: If the policy has syntax errors or fails schema validation.
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,41 +55,50 @@
# Syntax error without proper assignments
"""


@pytest.fixture
def cedar_validator():
from kest.core.policies.validators import CedarValidator

return CedarValidator()


@pytest.fixture
def rego_validator():
from kest.core.policies.validators import RegoValidator

return RegoValidator()


@pytest.mark.skipif(not HAS_CEDAR, reason="cedarpy not installed")
def test_cedar_validator_valid(cedar_validator):
# Should not raise
cedar_validator.validate_syntax(VALID_CEDAR)


@pytest.mark.skipif(not HAS_CEDAR, reason="cedarpy not installed")
def test_cedar_validator_invalid(cedar_validator):
with pytest.raises(ValueError):
cedar_validator.validate_syntax(INVALID_CEDAR)


@pytest.mark.skipif(not HAS_CEDAR, reason="cedarpy not installed")
def test_cedar_validator_with_schema(cedar_validator):
cedar_validator.validate_syntax(VALID_CEDAR, schema=VALID_SCHEMA)

with pytest.raises(ValueError):
cedar_validator.validate_syntax(INVALID_CEDAR, schema=VALID_SCHEMA)

with pytest.raises(ValueError, match="schema"):
cedar_validator.validate_syntax(VALID_CEDAR, schema=INVALID_SCHEMA)


@pytest.mark.skipif(not HAS_REGO, reason="regopy not installed")
def test_rego_validator_valid(rego_validator):
# Should not raise
rego_validator.validate_syntax(VALID_REGO)


@pytest.mark.skipif(not HAS_REGO, reason="regopy not installed")
def test_rego_validator_invalid(rego_validator):
with pytest.raises(ValueError):
Expand Down
Loading