from __future__ import annotations
import os
import sys
_SDK = os.path.join(os.path.dirname(__file__), "..", "..", "..", "sdk", "python")
sys.path.insert(0, _SDK)
sys.path.insert(0, os.path.join(_SDK, "gen"))
from udb_client.auth import UdbAuthClient from udb_client.metadata import Metadata from udb.core.authz.services.v1 import core_pb2 as authz
TARGET = os.getenv("UDB_TARGET", "127.0.0.1:50051")
API_KEY = os.getenv("UDB_API_KEY", "")
def main() -> None:
meta = Metadata(
tenant_id="acme",
project_id="billing",
purpose="control-plane",
correlation_id="native-py-example",
scopes=("udb:*",),
service_identity="examples.native-py",
)
with UdbAuthClient(TARGET, meta) as auth:
if API_KEY:
principal = auth.authenticate_api_key(API_KEY).principal
print(f"1) api key authenticated → user_id={principal.user_id} scopes={list(principal.scopes)}")
else:
print("1) set UDB_API_KEY (mint one with the Go example) to see authentication")
invoice = authz.ResourceRef(resource_name="invoice", message_type="invoice")
allowed, decision = auth.can(invoice, "data.select")
print(f"2) can data.select on invoice → {allowed} (decision_id={decision.decision_id})")
denied, _ = auth.can(invoice, "data.delete")
print(f" can data.delete on invoice → {denied}")
try:
grant = auth.native_access(invoice, "data.select")
if grant is None:
print("3) access allowed; no native grant minted (server native-access not configured)")
else:
print(
f"3) native grant: role={grant.role} session_vars={len(grant.session_variables)} "
"(open a psycopg conn on grant.dsn, then auth.native_transaction(...))"
)
except PermissionError as exc:
print(f"3) native access denied: {exc}")
if __name__ == "__main__":
main()