Skip to content

feat(sdk): implement Phase 3 SDK tooling for agentguard-py and agentguard-js. - #102

Merged
p3ris0n merged 1 commit into
mainfrom
feat/phase3-sdk-tooling
Oct 27, 2026
Merged

p3ris0n merged 1 commit into
mainfrom
feat/phase3-sdk-tooling

Conversation

@p3ris0n

@p3ris0n p3ris0n commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Title: feat(sdk): Implement Phase 3 SDK Tooling (agentguard-py & agentguard-js)

Overview

This pull request implements Phase 3: SDK Development (Tooling) for the AgentGuard on-chain Identity and RBAC ecosystem on Stellar & Soroban. It delivers two standalone, fully-tested, zero-defect SDKs:

  1. agentguard-py: A Python SDK for autonomous AI agents and LLM scripts to manage Ed25519 cryptographic keypairs, deterministically serialize payloads, and sign requests with replay protection.
  2. agentguard-js: A TypeScript/Node.js SDK for Web2 Resource Providers to cryptographically verify agent signatures, enforce strict 5-minute replay thresholds, simulate Soroban smart contracts with automatic retry resilience, and gate endpoints via Express.js middleware.

Both packages achieve 100.00% line coverage, strict typing (mypy --strict & TypeScript strict: true), custom error handling, and verified cross-language cryptographic interoperability.


Key Changes & Architecture

1. Python SDK (agentguard-py)

  • Key Management (agentguard/keys.py):
    • Uses audited Ed25519 libraries (stellar-sdk & pynacl / libsodium).
    • AgentKeypair.generate() creates new Ed25519 keypairs mapped to Stellar StrKey G-addresses and S-seeds.
    • AgentKeypair.from_secret(secret_seed) loads keys from Stellar S-seeds, 64-char hex strings, or raw 32-byte seeds.
    • AgentKeypair.from_public_key(public_key) allows initialization of verifier-only instances.
    • Full support for raw_public_key, raw_secret_seed, sign(), and verify().
  • Request Signing & Canonicalization (agentguard/signer.py):
    • Deterministic canonical JSON serialization (canonicalize_payload) ensuring identical key ordering and compact spacing across runtimes.
    • Anti-replay protection binding: signs ${timestamp}.${canonical_json}.
    • Standardized AgentAuthHeader model and create_auth_headers(...) helper generating:
      • X-Agent-Public-Key
      • X-Agent-Timestamp
      • X-Agent-Signature
      • Authorization: AgentGuard key="...",ts="...",sig="..."
    • Replay-attack prevention validator validate_timestamp(timestamp) enforcing a 5-minute maximum age and clock drift bounds.
  • Custom Error Hierarchy (agentguard/errors.py):
    • Base AgentGuardError, plus AgentKeyError, AgentSigningError, AgentSignatureInvalid, AgentTimestampExpiredError, and SerializationError.
  • Packaging:
    • Modern pyproject.toml targeting Python 3.10+, PEP 561 marker (py.typed), and README.md with a 5-line agent quickstart.

2. TypeScript / Node.js SDK (agentguard-js)

  • Signature Verification (src/verifier.ts):
    • Canonical JSON serializer matching Python’s byte-for-byte output.
    • validateTimestamp(timestamp, options) strictly rejecting timestamps older than 5 minutes (300,000ms) or exceeding forward clock skew tolerance.
    • verifySignature(publicKey, payload, signature, timestamp) and assertSignatureValid(...) supporting hex (128 chars) and base64 formats.
  • Soroban Contract RBAC Client (src/contract.ts):
    • Integrates @stellar/stellar-sdk with fully configurable endpoints (no hardcoded RPC URLs).
    • AgentGuardContract.checkAccess(agentId, role, resourceId) -> Promise<boolean> simulating on-chain check_access.
    • AgentGuardContract.verifyAgent(agentId, role) -> Promise<boolean> simulating on-chain verify_agent.
    • Automatic Retry Engine: Handles transient network failures with up to 3 automatic retries and exponential backoff, differentiating RPC logic failures from transport errors.
    • AgentGuardContract.setDefault(instance) for zero-boilerplate middleware integration.
  • Express Middleware Factory (src/middleware.ts):
    • requireAgentRole(role: string, options?: RequireRoleOptions):
      • Extracts AgentAuthHeader from headers (case-insensitive X-Agent-* or Authorization).
      • Enforces 5-minute replay attack freshness (returns 401 Unauthorized with code: "TIMESTAMP_EXPIRED" if stale).
      • Verifies Ed25519 signature (returns 401 Unauthorized with code: "INVALID_SIGNATURE" if invalid).
      • Queries checkAccess on-chain (returns 403 Forbidden with code: "FORBIDDEN" if unauthorized).
      • Returns 503 Service Unavailable with code: "CONTRACT_READ_ERROR" if RPC network fails after retries.
      • Attaches verified req.agentId, req.agentPublicKey, and req.agentTimestamp on success and calls next().
  • Custom Error Hierarchy (src/errors.ts):
    • AgentGuardError, AgentSignatureInvalid, AgentTimestampExpiredError, ContractReadError, NetworkRetryExhaustedError, AgentUnauthorizedError, and AgentPermissionDeniedError.
  • Dual Build Targets:
    • Compiles to both modern ESM (dist/esm/) and CommonJS (dist/cjs/) with declaration maps (.d.ts).

3. Cross-SDK Interoperability (tests/interop.test.ts)

  • Automated integration test executing agentguard-py to generate an identity, canonically encode a nested dictionary payload, bind an epoch timestamp, and sign it.
  • agentguard-js ingests the payload, timestamp, and signature, verifying cryptographic validity with zero discrepancy.

Test & Coverage Results

agentguard-py

pytest tests --cov=agentguard --cov-report=term-missing
============================= 29 passed in 1.91s ==============================
Name                     Stmts   Miss Branch BrPart  Cover   Missing
--------------------------------------------------------------------
agentguard/__init__.py       6      0      0      0   100%
agentguard/errors.py        15      0      2      0   100%
agentguard/keys.py          92      0     18      0   100%
agentguard/signer.py        57      0      8      0   100%
--------------------------------------------------------------------
TOTAL                      170      0     28      0   100%
Required test coverage of 100.0% reached. Total coverage: 100.00%

mypy agentguard tests: Success: no issues found in 7 source files (strict mode)
ruff check & black: All checks passed.

@p3ris0n
p3ris0n merged commit 9770976 into main Oct 27, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant