identity

package
v1.0.0-alpha.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2026 License: MIT Imports: 11 Imported by: 0

README

Agent Identity Package

DID-based cryptographic identity for AGNTCY integration in SemStreams.

Overview

The identity package provides a complete identity layer for agents participating in the AGNTCY (Internet of Agents) ecosystem. It implements W3C standards for Decentralized Identifiers (DIDs) and Verifiable Credentials (VCs), enabling agents to establish cryptographically-verifiable identities without centralized registries.

Key Features:

  • DID Support: Multiple DID methods (did:key, did:web, did:agntcy)
  • Verifiable Credentials: W3C-compliant credential issuance and verification
  • Provider Abstraction: Pluggable identity providers (local, AGNTCY service)
  • Agent Capabilities: Credential-based capability attestation
  • Delegation: Authority delegation between agents

Architecture

flowchart TD
    subgraph Client["Agent System"]
        Loop["Loop Entity"]
        App["Application"]
    end

    subgraph Identity["Identity Layer"]
        AI["AgentIdentity"]
        DID["DID"]
        VC["VerifiableCredential"]
    end

    subgraph Providers["Identity Providers"]
        Local["LocalProvider<br/>(Dev/Testing)"]
        Agntcy["AgntcyProvider<br/>(Production)"]
    end

    subgraph Standards["W3C Standards"]
        DIDCore["DID Core Spec"]
        VCModel["VC Data Model"]
    end

    Loop -->|has optional| AI
    App -->|creates via| Local
    App -->|creates via| Agntcy

    Local -->|generates| AI
    Agntcy -->|registers| AI

    AI -->|contains| DID
    AI -->|holds| VC

    DID -.implements.-> DIDCore
    VC -.implements.-> VCModel

    Local -->|signs with| KeyPair["Ed25519 Keys"]
    Agntcy -->|integrates| AgntcyService["AGNTCY Directory"]

Core Types

DID (Decentralized Identifier)

Self-sovereign identifier following W3C DID Core specification.

type DID struct {
    Method   string // "key", "web", "agntcy"
    ID       string // Method-specific identifier
    Fragment string // Optional fragment (e.g., key reference)
}

Format: did:method:method-specific-id[#fragment]

Examples:

// Public key-based DID (default for local provider)
did := identity.NewKeyDID("z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK")
// did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK

// DNS-based DID
did := identity.NewWebDID("example.com", "agents", "alice")
// did:web:example.com:agents:alice

// AGNTCY-specific DID
did := identity.NewAgntcyDID("agent-123")
// did:agntcy:agent-123

// Parsing DIDs
did, err := identity.ParseDID("did:key:z123#key-1")
if err != nil {
    log.Fatal(err)
}
fmt.Println(did.Method)   // "key"
fmt.Println(did.ID)       // "z123"
fmt.Println(did.Fragment) // "key-1"

Common Operations:

// String conversion
didStr := did.String() // "did:key:z123"

// Fragment manipulation
withKey := did.WithFragment("key-1")    // Copy with fragment
withoutKey := did.WithoutFragment()     // Copy without fragment

// Comparison
if did1.Equal(did2) {
    // Exact match including fragment
}
if did1.EqualIgnoreFragment(did2) {
    // Match ignoring fragment
}

// Method checking
if did.IsMethod(identity.MethodKey) {
    // This is a did:key
}

// Validation
if err := did.Validate(); err != nil {
    log.Fatal(err)
}
VerifiableCredential

W3C Verifiable Credential for attestations and delegations.

type VerifiableCredential struct {
    Context           []string          // JSON-LD contexts
    ID                string            // Unique credential ID
    Type              []string          // Credential types
    Issuer            string            // Issuer DID
    IssuanceDate      time.Time         // When issued
    ExpirationDate    *time.Time        // Optional expiration
    CredentialSubject json.RawMessage   // Claims
    Proof             *Proof            // Cryptographic proof
    CredentialStatus  *CredentialStatus // Revocation info
}

Credential Types:

  • AgentCapabilityCredential: Attests agent capabilities
  • AgentDelegationCredential: Delegates authority between agents
  • AgentIdentityCredential: Verifies agent identity

Creating Credentials:

// Capability credential
cred, err := identity.NewAgentCapabilityCredential(
    "urn:uuid:"+uuid.New().String(),
    issuerDID.String(),
    agentDID.String(),
    "code-review",
    0.95, // Confidence level
)

// Delegation credential
cred, err := identity.NewAgentDelegationCredential(
    "urn:uuid:"+uuid.New().String(),
    issuerDID.String(),
    delegateDID.String(),
    delegatorDID.String(),
    []string{"deploy", "rollback"},
)

// Generic credential
subject := map[string]any{
    "id": agentDID.String(),
    "skill": "Go development",
}
cred, err := identity.NewVerifiableCredential(
    "urn:uuid:"+uuid.New().String(),
    issuerDID.String(),
    "CustomCredential",
    subject,
)

Working with Credentials:

// Validation
if err := cred.Validate(); err != nil {
    log.Fatal(err)
}

// Expiration check
if cred.IsExpired() {
    log.Println("Credential expired")
}

// Type checking
if cred.HasType(identity.TypeAgentCapabilityCredential) {
    // This is a capability credential
}

// Extract subject
var subject identity.AgentCapabilitySubject
if err := cred.GetSubject(&subject); err != nil {
    log.Fatal(err)
}
fmt.Println(subject.Capability) // "code-review"
fmt.Println(subject.Confidence) // 0.95

// Add expiration
expiry := time.Now().Add(30 * 24 * time.Hour)
credWithExp := cred.WithExpiration(expiry)

// Add proof
proof := &identity.Proof{
    Type:               "Ed25519Signature2020",
    Created:            time.Now().UTC(),
    VerificationMethod: issuerDID.WithFragment("key-1").String(),
    ProofPurpose:       identity.PurposeAssertionMethod,
    ProofValue:         "base64-encoded-signature",
}
credWithProof := cred.WithProof(proof)
AgentIdentity

Complete agent identity combining DID, credentials, and metadata.

type AgentIdentity struct {
    DID          DID                    // Decentralized identifier
    DisplayName  string                 // Human-readable name
    Credentials  []VerifiableCredential // Held credentials
    InternalRole string                 // Local system role
    Created      time.Time              // Creation timestamp
    Updated      time.Time              // Last update
    Metadata     map[string]any         // Additional metadata
}

Creating and Managing Identities:

// Create identity
did := identity.NewKeyDID("z123")
agent := identity.NewAgentIdentity(*did, "Code Reviewer")
agent.InternalRole = "reviewer"

// Add capability credential
capCred, _ := identity.NewAgentCapabilityCredential(
    "urn:uuid:cap-1",
    issuerDID.String(),
    agent.DIDString(),
    "code-review",
    0.9,
)
agent.AddCredential(*capCred)

// Get credentials by type
capCreds := agent.GetCredentialsByType(identity.TypeAgentCapabilityCredential)

// Get only valid (non-expired) credentials
validCreds := agent.GetValidCredentials()

// Check capability
if agent.HasCapability("code-review") {
    fmt.Println("Agent can review code")
}

// Get all capabilities
capabilities := agent.GetCapabilities()
// ["code-review", "testing"]

// Remove credential
if agent.RemoveCredential("urn:uuid:cap-1") {
    fmt.Println("Credential removed")
}

// Metadata
agent.SetMetadata("team", "backend")
if team, ok := agent.GetMetadata("team"); ok {
    fmt.Println(team) // "backend"
}

// Validation
if err := agent.Validate(); err != nil {
    log.Fatal(err)
}

// Role modification
updatedAgent := agent.WithInternalRole("senior-reviewer")

Provider Interface

Providers manage the lifecycle of agent identities.

type Provider interface {
    CreateIdentity(ctx context.Context, opts CreateIdentityOptions) (*AgentIdentity, error)
    ResolveIdentity(ctx context.Context, did DID) (*AgentIdentity, error)
    IssueCredential(ctx context.Context, subject DID, credType string, claims any) (*VerifiableCredential, error)
    VerifyCredential(ctx context.Context, cred *VerifiableCredential) (bool, error)
    UpdateIdentity(ctx context.Context, identity *AgentIdentity) error
    DeleteIdentity(ctx context.Context, did DID) error
}

Provider Implementations

LocalProvider

In-memory provider for development, testing, and single-node deployments.

Features:

  • Local Ed25519 key generation
  • In-memory identity and key storage
  • Self-issued credentials with did:key method
  • No external dependencies

Usage:

// Create provider
provider, err := identity.NewLocalProvider(identity.ProviderConfig{
    ProviderType: "local",
})
if err != nil {
    log.Fatal(err)
}

// Create identity
ctx := context.Background()
agent, err := provider.CreateIdentity(ctx, identity.CreateIdentityOptions{
    DisplayName:         "Code Reviewer",
    InternalRole:        "reviewer",
    InitialCapabilities: []string{"code-review", "testing"},
    Metadata: map[string]any{
        "team": "backend",
    },
})
if err != nil {
    log.Fatal(err)
}

fmt.Println(agent.DIDString())
// did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK

// Resolve identity
resolved, err := provider.ResolveIdentity(ctx, agent.DID)
if err != nil {
    log.Fatal(err)
}

// Issue additional credential
cred, err := provider.IssueCredential(
    ctx,
    agent.DID,
    identity.TypeAgentCapabilityCredential,
    identity.AgentCapabilitySubject{
        ID:         agent.DIDString(),
        Capability: "deployment",
        Confidence: 0.8,
    },
)
if err != nil {
    log.Fatal(err)
}

// Verify credential
valid, err := provider.VerifyCredential(ctx, cred)
if err != nil {
    log.Fatal(err)
}
if !valid {
    log.Fatal("Credential verification failed")
}

// Update identity
agent.DisplayName = "Senior Code Reviewer"
if err := provider.UpdateIdentity(ctx, agent); err != nil {
    log.Fatal(err)
}

// Delete identity
if err := provider.DeleteIdentity(ctx, agent.DID); err != nil {
    log.Fatal(err)
}
AgntcyProvider

Provider for integration with the AGNTCY service (stub implementation).

Configuration:

provider, err := identity.NewAgntcyProvider(identity.ProviderConfig{
    ProviderType: "agntcy",
    AgntcyURL:    "https://directory.agntcy.org",
    IssuerDID:    "did:agntcy:my-org",
})

Status: Stub implementation awaiting AGNTCY SDK integration. All methods currently return ErrProviderNotConfigured.

Future Integration:

  • DID registration in AGNTCY directory
  • Credential issuance via AGNTCY signing service
  • DID resolution from AGNTCY directory
  • Credential revocation status checks
Provider Factory

Create providers dynamically based on configuration:

provider, err := identity.DefaultProviderFactory(identity.ProviderConfig{
    ProviderType: "local", // or "agntcy"
})
if err != nil {
    log.Fatal(err)
}

Supported Provider Types:

  • "local" or "" (empty) - LocalProvider
  • "agntcy" - AgntcyProvider (requires AgntcyURL)

Integration with Agentic Loop

The LoopEntity type includes an optional Identity field for AGNTCY integration:

import (
    "github.com/c360/semstreams/agentic"
    "github.com/c360/semstreams/agentic/identity"
)

// Create identity
provider, _ := identity.NewLocalProvider(identity.ProviderConfig{})
ctx := context.Background()
agentIdentity, _ := provider.CreateIdentity(ctx, identity.CreateIdentityOptions{
    DisplayName:         "Architect Agent",
    InternalRole:        "architect",
    InitialCapabilities: []string{"design", "review"},
})

// Create loop with identity
loop := agentic.LoopEntity{
    ID:       "loop-123",
    Identity: agentIdentity,
    Config: agentic.LoopConfig{
        Role:        "architect",
        Description: "System design and API contracts",
    },
}

// Access identity in loop
if loop.Identity != nil {
    fmt.Println("Agent DID:", loop.Identity.DIDString())

    if loop.Identity.HasCapability("design") {
        // Execute design tasks
    }
}

Common Patterns

Creating Agents with Capabilities
provider, _ := identity.NewLocalProvider(identity.ProviderConfig{})
ctx := context.Background()

// Create developer agent
developer, _ := provider.CreateIdentity(ctx, identity.CreateIdentityOptions{
    DisplayName: "Go Developer",
    InternalRole: "go-developer",
    InitialCapabilities: []string{
        "backend-implementation",
        "unit-testing",
        "api-design",
    },
})

// Create reviewer agent
reviewer, _ := provider.CreateIdentity(ctx, identity.CreateIdentityOptions{
    DisplayName: "Code Reviewer",
    InternalRole: "go-reviewer",
    InitialCapabilities: []string{
        "code-review",
        "performance-analysis",
        "security-audit",
    },
})
Delegating Authority
// Reviewer delegates deployment capability to developer
delegationCred, _ := identity.NewAgentDelegationCredential(
    "urn:uuid:"+uuid.New().String(),
    reviewer.DIDString(),
    developer.DIDString(), // Delegate (receiving authority)
    reviewer.DIDString(),   // Delegator (granting authority)
    []string{"deploy-staging"},
)

// Add delegation credential to developer
developer.AddCredential(*delegationCred)

// Developer can now check delegation
delegations := developer.GetCredentialsByType(identity.TypeAgentDelegationCredential)
for _, cred := range delegations {
    var subject identity.AgentDelegationSubject
    if err := cred.GetSubject(&subject); err == nil {
        fmt.Println("Delegated capabilities:", subject.Capabilities)
    }
}
Capability Verification
// Check if agent has required capability
func canPerformTask(agent *identity.AgentIdentity, task string) bool {
    switch task {
    case "code-review":
        return agent.HasCapability("code-review")
    case "deploy":
        return agent.HasCapability("deployment")
    default:
        return false
    }
}

// Get capability confidence
func getCapabilityConfidence(agent *identity.AgentIdentity, capability string) float64 {
    creds := agent.GetCredentialsByType(identity.TypeAgentCapabilityCredential)
    for _, cred := range creds {
        if cred.IsExpired() {
            continue
        }
        var subject identity.AgentCapabilitySubject
        if err := cred.GetSubject(&subject); err == nil {
            if subject.Capability == capability {
                return subject.Confidence
            }
        }
    }
    return 0.0
}
Credential Lifecycle Management
// Issue time-limited credential
func issueTemporaryAccess(
    provider identity.Provider,
    ctx context.Context,
    agent *identity.AgentIdentity,
    capability string,
    duration time.Duration,
) error {
    cred, err := provider.IssueCredential(
        ctx,
        agent.DID,
        identity.TypeAgentCapabilityCredential,
        identity.AgentCapabilitySubject{
            ID:         agent.DIDString(),
            Capability: capability,
            Confidence: 1.0,
        },
    )
    if err != nil {
        return err
    }

    // Add expiration
    expiry := time.Now().Add(duration)
    credWithExp := cred.WithExpiration(expiry)

    agent.AddCredential(*credWithExp)
    return provider.UpdateIdentity(ctx, agent)
}

// Cleanup expired credentials
func cleanupExpiredCredentials(agent *identity.AgentIdentity) {
    validCreds := agent.GetValidCredentials()
    agent.Credentials = validCreds
    agent.Updated = time.Now().UTC()
}

Error Handling

import "errors"

// Common identity errors
var (
    ErrDisplayNameRequired    = errors.New("display name is required")
    ErrUnknownProviderType    = errors.New("unknown provider type")
    ErrIdentityNotFound       = errors.New("identity not found")
    ErrCredentialInvalid      = errors.New("credential is invalid")
    ErrCredentialExpired      = errors.New("credential has expired")
    ErrSignatureInvalid       = errors.New("signature verification failed")
    ErrKeyNotFound            = errors.New("key not found")
    ErrProviderNotConfigured  = errors.New("provider not configured")
    ErrUnsupportedMethod      = errors.New("unsupported DID method")
)

// Error handling pattern
agent, err := provider.CreateIdentity(ctx, opts)
if err != nil {
    if errors.Is(err, identity.ErrDisplayNameRequired) {
        // Handle validation error
    } else if errors.Is(err, identity.ErrUnsupportedMethod) {
        // Handle unsupported DID method
    } else {
        // Handle other errors
    }
}

// Credential verification
valid, err := provider.VerifyCredential(ctx, cred)
if err != nil {
    if errors.Is(err, identity.ErrCredentialExpired) {
        // Credential expired
    } else if errors.Is(err, identity.ErrSignatureInvalid) {
        // Signature verification failed
    }
}

Testing

Running Tests
# Unit tests
go test -v ./agentic/identity/...

# With race detector
go test -race -v ./agentic/identity/...

# Specific test
go test -v -run TestLocalProvider_CreateIdentity ./agentic/identity/
Test Coverage
# Generate coverage report
go test -coverprofile=coverage.out ./agentic/identity/...
go tool cover -html=coverage.out
Example Test
func TestAgentCapability(t *testing.T) {
    // Setup provider
    provider, err := identity.NewLocalProvider(identity.ProviderConfig{})
    if err != nil {
        t.Fatalf("NewLocalProvider() error = %v", err)
    }

    ctx := context.Background()

    // Create agent with capabilities
    agent, err := provider.CreateIdentity(ctx, identity.CreateIdentityOptions{
        DisplayName:         "Test Agent",
        InitialCapabilities: []string{"testing"},
    })
    if err != nil {
        t.Fatalf("CreateIdentity() error = %v", err)
    }

    // Verify capability
    if !agent.HasCapability("testing") {
        t.Error("expected agent to have 'testing' capability")
    }

    // Verify credential validity
    creds := agent.GetValidCredentials()
    if len(creds) == 0 {
        t.Error("expected at least one valid credential")
    }
}

References

Standards
SemStreams Documentation
External Resources

Security Considerations

Key Management

LocalProvider stores private keys in memory only. For production use:

  • Implement persistent key storage with encryption
  • Use hardware security modules (HSMs) for key protection
  • Rotate keys periodically
  • Implement key backup and recovery procedures
Credential Verification

Always verify credentials before trusting claims:

// Don't trust credentials blindly
valid, err := provider.VerifyCredential(ctx, cred)
if err != nil || !valid {
    return errors.New("credential verification failed")
}

// Check expiration
if cred.IsExpired() {
    return errors.New("credential expired")
}

// Verify issuer is trusted
trustedIssuers := []string{"did:agntcy:my-org", "did:key:trusted-key"}
if !contains(trustedIssuers, cred.Issuer) {
    return errors.New("untrusted issuer")
}
DID Resolution

When resolving DIDs from external sources:

  • Implement DID method-specific resolution logic
  • Verify DID document signatures
  • Check for DID document revocation
  • Cache DID documents with appropriate TTL
Credential Revocation

For production systems, implement credential revocation:

  • Use CredentialStatus field with revocation list URL
  • Check revocation status before accepting credentials
  • Implement status list 2021 or similar revocation mechanism

Future Enhancements

  • Complete AGNTCY service integration in AgntcyProvider
  • Persistent key storage for LocalProvider
  • DID document resolution and verification
  • Credential revocation support (Status List 2021)
  • Additional DID methods (did:peer, did:ethr)
  • Proof generation with actual cryptographic signatures
  • Support for multiple proof formats (JWS, LD Proofs)
  • Credential presentation and selective disclosure
  • Agent reputation scoring based on credential history

Documentation

Overview

Package identity provides DID-based cryptographic identity for AGNTCY integration.

Package identity provides DID-based cryptographic identity for AGNTCY integration.

Overview

This package implements the identity layer for agents in the AGNTCY (Internet of Agents) ecosystem. It provides:

  • DID (Decentralized Identifier) support following W3C DID Core specification
  • Verifiable Credentials for capability and delegation attestation
  • Identity providers for local and AGNTCY-based identity management

DID Support

DIDs are self-sovereign identifiers that don't depend on centralized registries. This package supports multiple DID methods:

  • did:key - Public key based DIDs (default for local provider)
  • did:web - DNS-based DIDs
  • did:agntcy - AGNTCY-specific DIDs

Example:

did, err := identity.ParseDID("did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK")
if err != nil {
    log.Fatal(err)
}
fmt.Println(did.Method) // "key"

Verifiable Credentials

Credentials follow the W3C Verifiable Credentials data model and are used to:

  • Attest agent capabilities (AgentCapabilityCredential)
  • Delegate authority between agents (AgentDelegationCredential)
  • Verify agent identity (AgentIdentityCredential)

Example:

cred, err := identity.NewAgentCapabilityCredential(
    "urn:uuid:123",
    issuerDID,
    agentDID,
    "code-review",
    0.95,
)

Identity Providers

Identity providers manage the lifecycle of agent identities:

LocalProvider: For development and single-node deployments

provider, _ := identity.NewLocalProvider(identity.ProviderConfig{})
identity, _ := provider.CreateIdentity(ctx, identity.CreateIdentityOptions{
    DisplayName: "Code Reviewer",
    InternalRole: "reviewer",
})

AgntcyProvider: For AGNTCY service integration (requires AGNTCY SDK)

provider, _ := identity.NewAgntcyProvider(identity.ProviderConfig{
    AgntcyURL: "https://directory.agntcy.org",
})

Agent Identity

AgentIdentity combines a DID with credentials and metadata:

identity := NewAgentIdentity(did, "Architect Agent")
identity.InternalRole = "architect"
identity.AddCredential(capabilityCredential)

Integration with LoopEntity

LoopEntity includes an optional Identity field for AGNTCY integration:

loop := agentic.LoopEntity{
    ID: "loop-123",
    Identity: &identity.AgentIdentity{
        DID: did,
        DisplayName: "Architect",
    },
}

See Also

Index

Constants

View Source
const (
	// TypeVerifiableCredential is the base type for all VCs.
	TypeVerifiableCredential = "VerifiableCredential"

	// TypeAgentCapabilityCredential is for agent capability attestations.
	TypeAgentCapabilityCredential = "AgentCapabilityCredential"

	// TypeAgentDelegationCredential is for delegation authority.
	TypeAgentDelegationCredential = "AgentDelegationCredential"

	// TypeAgentIdentityCredential is for identity verification.
	TypeAgentIdentityCredential = "AgentIdentityCredential"
)

Common credential types

View Source
const (
	// PurposeAssertionMethod means the proof asserts a claim.
	PurposeAssertionMethod = "assertionMethod"

	// PurposeAuthentication means the proof authenticates the subject.
	PurposeAuthentication = "authentication"

	// PurposeCapabilityDelegation means the proof delegates a capability.
	PurposeCapabilityDelegation = "capabilityDelegation"

	// PurposeCapabilityInvocation means the proof invokes a capability.
	PurposeCapabilityInvocation = "capabilityInvocation"
)

Common proof purposes

View Source
const (
	// MethodKey is the did:key method using public key encoding.
	MethodKey = "key"

	// MethodWeb is the did:web method using DNS domain names.
	MethodWeb = "web"

	// MethodAgntcy is the AGNTCY-specific DID method.
	MethodAgntcy = "agntcy"
)

Common DID methods

Variables

View Source
var (
	// ContextVC is the standard W3C VC context.
	ContextVC = "https://www.w3.org/2018/credentials/v1"

	// ContextAgntcy is the AGNTCY-specific context.
	ContextAgntcy = "https://agntcy.org/credentials/v1"
)

Default context URLs

View Source
var (
	// ErrDisplayNameRequired indicates display name is required.
	ErrDisplayNameRequired = errors.New("display name is required")

	// ErrUnknownProviderType indicates an unknown provider type.
	ErrUnknownProviderType = errors.New("unknown provider type")

	// ErrIdentityNotFound indicates the identity was not found.
	ErrIdentityNotFound = errors.New("identity not found")

	// ErrCredentialInvalid indicates the credential is invalid.
	ErrCredentialInvalid = errors.New("credential is invalid")

	// ErrCredentialExpired indicates the credential has expired.
	ErrCredentialExpired = errors.New("credential has expired")

	// ErrSignatureInvalid indicates the signature verification failed.
	ErrSignatureInvalid = errors.New("signature verification failed")

	// ErrKeyNotFound indicates the key was not found.
	ErrKeyNotFound = errors.New("key not found")

	// ErrProviderNotConfigured indicates the provider is not configured.
	ErrProviderNotConfigured = errors.New("provider not configured")

	// ErrUnsupportedMethod indicates the DID method is not supported.
	ErrUnsupportedMethod = errors.New("unsupported DID method")
)

Identity-related errors

Functions

This section is empty.

Types

type AgentCapabilitySubject

type AgentCapabilitySubject struct {
	// ID is the DID of the agent.
	ID string `json:"id"`

	// Capability is the capability being attested.
	Capability string `json:"capability"`

	// Confidence is the confidence level (0.0-1.0).
	Confidence float64 `json:"confidence,omitempty"`

	// Scope limits where the capability applies.
	Scope string `json:"scope,omitempty"`
}

AgentCapabilitySubject represents the subject of an agent capability credential.

type AgentDelegationSubject

type AgentDelegationSubject struct {
	// ID is the DID of the delegate (agent receiving authority).
	ID string `json:"id"`

	// Delegator is the DID of the delegating agent.
	Delegator string `json:"delegator"`

	// Capabilities are the delegated capabilities.
	Capabilities []string `json:"capabilities"`

	// Scope limits where the delegation applies.
	Scope string `json:"scope,omitempty"`

	// ValidUntil is when the delegation expires.
	ValidUntil *time.Time `json:"validUntil,omitempty"`
}

AgentDelegationSubject represents the subject of an agent delegation credential.

type AgentIdentity

type AgentIdentity struct {
	// DID is the decentralized identifier for this agent.
	DID DID `json:"did"`

	// DisplayName is a human-readable name for the agent.
	DisplayName string `json:"display_name"`

	// Credentials are verifiable credentials held by this agent.
	Credentials []VerifiableCredential `json:"credentials,omitempty"`

	// InternalRole is the agent's role in the local system (preserved for compatibility).
	// Example values: "architect", "editor", "reviewer"
	InternalRole string `json:"internal_role,omitempty"`

	// Created is when this identity was created.
	Created time.Time `json:"created,omitempty"`

	// Updated is when this identity was last updated.
	Updated time.Time `json:"updated,omitempty"`

	// Metadata contains additional identity metadata.
	Metadata map[string]any `json:"metadata,omitempty"`
}

AgentIdentity represents the complete identity of an agent in the AGNTCY ecosystem. It combines a DID with associated credentials and metadata.

func NewAgentIdentity

func NewAgentIdentity(did DID, displayName string) *AgentIdentity

NewAgentIdentity creates a new agent identity.

func (*AgentIdentity) AddCredential

func (ai *AgentIdentity) AddCredential(cred VerifiableCredential)

AddCredential adds a credential to the identity.

func (*AgentIdentity) DIDString

func (ai *AgentIdentity) DIDString() string

DIDString returns the string representation of the agent's DID.

func (*AgentIdentity) GetCapabilities

func (ai *AgentIdentity) GetCapabilities() []string

GetCapabilities returns all capabilities from valid capability credentials.

func (*AgentIdentity) GetCredential

func (ai *AgentIdentity) GetCredential(credID string) *VerifiableCredential

GetCredential returns a credential by ID.

func (*AgentIdentity) GetCredentialsByType

func (ai *AgentIdentity) GetCredentialsByType(credType string) []VerifiableCredential

GetCredentialsByType returns all credentials of the specified type.

func (*AgentIdentity) GetMetadata

func (ai *AgentIdentity) GetMetadata(key string) (any, bool)

GetMetadata gets a metadata value.

func (*AgentIdentity) GetValidCredentials

func (ai *AgentIdentity) GetValidCredentials() []VerifiableCredential

GetValidCredentials returns all non-expired credentials.

func (*AgentIdentity) HasCapability

func (ai *AgentIdentity) HasCapability(capability string) bool

HasCapability checks if the agent has a capability credential for the given capability.

func (*AgentIdentity) RemoveCredential

func (ai *AgentIdentity) RemoveCredential(credID string) bool

RemoveCredential removes a credential by ID.

func (*AgentIdentity) SetMetadata

func (ai *AgentIdentity) SetMetadata(key string, value any)

SetMetadata sets a metadata value.

func (*AgentIdentity) Validate

func (ai *AgentIdentity) Validate() error

Validate checks if the agent identity is valid.

func (*AgentIdentity) WithInternalRole

func (ai *AgentIdentity) WithInternalRole(role string) *AgentIdentity

WithInternalRole returns a copy with the specified internal role.

type AgntcyProvider

type AgntcyProvider struct {
	// contains filtered or unexported fields
}

AgntcyProvider implements Provider using the AGNTCY service. This is a stub implementation - full integration requires the AGNTCY SDK.

func NewAgntcyProvider

func NewAgntcyProvider(config ProviderConfig) (*AgntcyProvider, error)

NewAgntcyProvider creates a new AGNTCY identity provider.

func (*AgntcyProvider) CreateIdentity

CreateIdentity creates a new agent identity via AGNTCY service.

func (*AgntcyProvider) DeleteIdentity

func (p *AgntcyProvider) DeleteIdentity(_ context.Context, _ DID) error

DeleteIdentity removes an identity via AGNTCY service.

func (*AgntcyProvider) IssueCredential

func (p *AgntcyProvider) IssueCredential(_ context.Context, _ DID, _ string, _ any) (*VerifiableCredential, error)

IssueCredential issues a verifiable credential via AGNTCY service.

func (*AgntcyProvider) ResolveIdentity

func (p *AgntcyProvider) ResolveIdentity(_ context.Context, _ DID) (*AgentIdentity, error)

ResolveIdentity resolves a DID to an agent identity via AGNTCY service.

func (*AgntcyProvider) UpdateIdentity

func (p *AgntcyProvider) UpdateIdentity(_ context.Context, _ *AgentIdentity) error

UpdateIdentity updates an existing identity via AGNTCY service.

func (*AgntcyProvider) VerifyCredential

func (p *AgntcyProvider) VerifyCredential(_ context.Context, _ *VerifiableCredential) (bool, error)

VerifyCredential verifies a credential via AGNTCY service.

type CreateIdentityOptions

type CreateIdentityOptions struct {
	// DisplayName is the human-readable name for the agent.
	DisplayName string

	// InternalRole is the agent's role in the local system.
	InternalRole string

	// Method specifies which DID method to use.
	// Defaults to "key" for local provider.
	Method string

	// Metadata contains additional identity metadata.
	Metadata map[string]any

	// InitialCapabilities are capabilities to attest via credentials.
	InitialCapabilities []string
}

CreateIdentityOptions configures identity creation.

func (*CreateIdentityOptions) Validate

func (o *CreateIdentityOptions) Validate() error

Validate validates the options.

type CredentialStatus

type CredentialStatus struct {
	// ID is the URL for checking credential status.
	ID string `json:"id"`

	// Type specifies the status method type.
	Type string `json:"type"`
}

CredentialStatus represents the status of a credential (e.g., revocation).

type DID

type DID struct {
	// Method identifies the DID method (e.g., "web", "key", "agntcy").
	Method string `json:"method"`

	// ID is the method-specific identifier.
	ID string `json:"id"`

	// Fragment is an optional fragment reference (e.g., key reference).
	Fragment string `json:"fragment,omitempty"`
}

DID represents a Decentralized Identifier as specified by W3C DID Core. See: https://www.w3.org/TR/did-core/

func NewAgntcyDID

func NewAgntcyDID(agentID string) *DID

NewAgntcyDID creates a new did:agntcy DID.

func NewKeyDID

func NewKeyDID(multibaseKey string) *DID

NewKeyDID creates a new did:key DID from a public key multibase encoding.

func NewWebDID

func NewWebDID(domain string, paths ...string) *DID

NewWebDID creates a new did:web DID from a domain name. The domain should be URL-encoded for special characters.

func ParseDID

func ParseDID(s string) (*DID, error)

ParseDID parses a DID string into a DID struct. Format: did:method:method-specific-id[#fragment]

func (*DID) Equal

func (d *DID) Equal(other *DID) bool

Equal checks if two DIDs are equal (including fragment).

func (*DID) EqualIgnoreFragment

func (d *DID) EqualIgnoreFragment(other *DID) bool

EqualIgnoreFragment checks if two DIDs are equal ignoring the fragment.

func (*DID) IsMethod

func (d *DID) IsMethod(method string) bool

IsMethod checks if the DID uses the specified method.

func (DID) MarshalText

func (d DID) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*DID) String

func (d *DID) String() string

String returns the canonical string representation of the DID.

func (*DID) UnmarshalText

func (d *DID) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (*DID) Validate

func (d *DID) Validate() error

Validate checks if the DID is valid.

func (*DID) WithFragment

func (d *DID) WithFragment(fragment string) DID

WithFragment returns a copy of the DID with the specified fragment.

func (*DID) WithoutFragment

func (d *DID) WithoutFragment() DID

WithoutFragment returns a copy of the DID without any fragment.

type LocalProvider

type LocalProvider struct {
	// contains filtered or unexported fields
}

LocalProvider implements Provider using local key generation. This is suitable for development, testing, and single-node deployments.

func NewLocalProvider

func NewLocalProvider(config ProviderConfig) (*LocalProvider, error)

NewLocalProvider creates a new local identity provider.

func (*LocalProvider) CreateIdentity

func (p *LocalProvider) CreateIdentity(ctx context.Context, opts CreateIdentityOptions) (*AgentIdentity, error)

CreateIdentity creates a new agent identity with a locally generated DID.

func (*LocalProvider) DeleteIdentity

func (p *LocalProvider) DeleteIdentity(_ context.Context, did DID) error

DeleteIdentity removes an identity.

func (*LocalProvider) GetIssuerDID

func (p *LocalProvider) GetIssuerDID() *DID

GetIssuerDID returns the provider's issuer DID.

func (*LocalProvider) IssueCredential

func (p *LocalProvider) IssueCredential(_ context.Context, _ DID, credType string, claims any) (*VerifiableCredential, error)

IssueCredential issues a verifiable credential for the subject.

func (*LocalProvider) ResolveIdentity

func (p *LocalProvider) ResolveIdentity(_ context.Context, did DID) (*AgentIdentity, error)

ResolveIdentity resolves a DID to an agent identity.

func (*LocalProvider) UpdateIdentity

func (p *LocalProvider) UpdateIdentity(_ context.Context, identity *AgentIdentity) error

UpdateIdentity updates an existing identity.

func (*LocalProvider) VerifyCredential

func (p *LocalProvider) VerifyCredential(_ context.Context, cred *VerifiableCredential) (bool, error)

VerifyCredential verifies a credential's signature and validity.

type Proof

type Proof struct {
	// Type specifies the proof type (e.g., "Ed25519Signature2020").
	Type string `json:"type"`

	// Created is when the proof was created.
	Created time.Time `json:"created"`

	// VerificationMethod is the DID URL of the key used for the proof.
	VerificationMethod string `json:"verificationMethod"`

	// ProofPurpose describes the purpose of the proof.
	ProofPurpose string `json:"proofPurpose"`

	// ProofValue is the actual cryptographic signature.
	ProofValue string `json:"proofValue,omitempty"`

	// JWS is an alternative proof format using JSON Web Signature.
	JWS string `json:"jws,omitempty"`
}

Proof represents a cryptographic proof for a verifiable credential.

type Provider

type Provider interface {
	// CreateIdentity creates a new agent identity.
	CreateIdentity(ctx context.Context, opts CreateIdentityOptions) (*AgentIdentity, error)

	// ResolveIdentity resolves a DID to an agent identity.
	ResolveIdentity(ctx context.Context, did DID) (*AgentIdentity, error)

	// IssueCredential issues a verifiable credential for the subject.
	IssueCredential(ctx context.Context, subject DID, credType string, claims any) (*VerifiableCredential, error)

	// VerifyCredential verifies a credential's signature and validity.
	VerifyCredential(ctx context.Context, cred *VerifiableCredential) (bool, error)

	// UpdateIdentity updates an existing identity.
	UpdateIdentity(ctx context.Context, identity *AgentIdentity) error

	// DeleteIdentity removes an identity.
	DeleteIdentity(ctx context.Context, did DID) error
}

Provider defines the interface for creating and managing agent identities.

type ProviderConfig

type ProviderConfig struct {
	// ProviderType identifies the provider ("local", "agntcy").
	ProviderType string `json:"provider_type"`

	// IssuerDID is the DID used for issuing credentials (for AGNTCY provider).
	IssuerDID string `json:"issuer_did,omitempty"`

	// AgntcyURL is the AGNTCY service URL (for AGNTCY provider).
	AgntcyURL string `json:"agntcy_url,omitempty"`

	// KeyStorePath is the path to store private keys (for local provider).
	KeyStorePath string `json:"key_store_path,omitempty"`
}

ProviderConfig holds configuration for identity providers.

type ProviderFactory

type ProviderFactory func(config ProviderConfig) (Provider, error)

ProviderFactory creates an identity provider based on configuration.

var DefaultProviderFactory ProviderFactory = func(config ProviderConfig) (Provider, error) {
	switch config.ProviderType {
	case "local", "":
		return NewLocalProvider(config)
	case "agntcy":
		return NewAgntcyProvider(config)
	default:
		return nil, ErrUnknownProviderType
	}
}

DefaultProviderFactory creates providers based on provider type.

type VerifiableCredential

type VerifiableCredential struct {
	// Context specifies the JSON-LD context(s).
	Context []string `json:"@context"`

	// ID is the unique identifier for this credential.
	ID string `json:"id"`

	// Type specifies the credential type(s).
	Type []string `json:"type"`

	// Issuer is the DID of the entity that issued this credential.
	Issuer string `json:"issuer"`

	// IssuanceDate is when the credential was issued.
	IssuanceDate time.Time `json:"issuanceDate"`

	// ExpirationDate is when the credential expires (optional).
	ExpirationDate *time.Time `json:"expirationDate,omitempty"`

	// CredentialSubject contains the claims about the subject.
	CredentialSubject json.RawMessage `json:"credentialSubject"`

	// Proof contains the cryptographic proof (optional).
	Proof *Proof `json:"proof,omitempty"`

	// CredentialStatus contains revocation/status information (optional).
	CredentialStatus *CredentialStatus `json:"credentialStatus,omitempty"`
}

VerifiableCredential represents a W3C Verifiable Credential. See: https://www.w3.org/TR/vc-data-model/

func NewAgentCapabilityCredential

func NewAgentCapabilityCredential(id, issuer, agentDID, capability string, confidence float64) (*VerifiableCredential, error)

NewAgentCapabilityCredential creates a new agent capability credential.

func NewAgentDelegationCredential

func NewAgentDelegationCredential(id, issuer, delegateDID, delegatorDID string, capabilities []string) (*VerifiableCredential, error)

NewAgentDelegationCredential creates a new agent delegation credential.

func NewVerifiableCredential

func NewVerifiableCredential(id, issuer string, credType string, subject any) (*VerifiableCredential, error)

NewVerifiableCredential creates a new verifiable credential.

func (*VerifiableCredential) GetSubject

func (vc *VerifiableCredential) GetSubject(v any) error

GetSubject unmarshals the credential subject into the provided value.

func (*VerifiableCredential) HasType

func (vc *VerifiableCredential) HasType(credType string) bool

HasType checks if the credential has the specified type.

func (*VerifiableCredential) IsExpired

func (vc *VerifiableCredential) IsExpired() bool

IsExpired checks if the credential has expired.

func (*VerifiableCredential) SetSubject

func (vc *VerifiableCredential) SetSubject(v any) error

SetSubject marshals and sets the credential subject.

func (*VerifiableCredential) Validate

func (vc *VerifiableCredential) Validate() error

Validate checks if the credential is structurally valid.

func (*VerifiableCredential) WithExpiration

func (vc *VerifiableCredential) WithExpiration(exp time.Time) *VerifiableCredential

WithExpiration returns a copy with the specified expiration date.

func (*VerifiableCredential) WithProof

func (vc *VerifiableCredential) WithProof(proof *Proof) *VerifiableCredential

WithProof returns a copy with the specified proof.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL