credential

package
v0.5.7 Latest Latest
Warning

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

Go to latest
Published: May 20, 2026 License: BSD-2-Clause Imports: 23 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	// ContextV2 is the URL for the W3C Verifiable Credentials Data Model v2.0 context
	ContextV2 = "https://www.w3.org/ns/credentials/v2"

	// ProofTypeDataIntegrity is the type for Data Integrity Proofs
	ProofTypeDataIntegrity = "DataIntegrityProof"
)

Variables

View Source
var (
	ErrMissingContext               = errors.New("@context is required")
	ErrInvalidBaseContext           = errors.New("first @context must be https://www.w3.org/ns/credentials/v2")
	ErrInvalidContext               = errors.New("invalid @context")
	ErrMissingType                  = errors.New("type is required")
	ErrInvalidType                  = errors.New("invalid type")
	ErrMissingVCType                = errors.New("type must include 'VerifiableCredential'")
	ErrInvalidID                    = errors.New("invalid id")
	ErrMissingIssuer                = errors.New("issuer is required")
	ErrInvalidIssuerID              = errors.New("issuer id must be a valid URL")
	ErrMissingValidFrom             = errors.New("validFrom is required")
	ErrInvalidValidFrom             = errors.New("validFrom must be a valid dateTimeStamp")
	ErrInvalidValidUntil            = errors.New("validUntil must be a valid dateTimeStamp")
	ErrValidUntilBeforeValidFrom    = errors.New("validUntil must be after validFrom")
	ErrMissingValidUntil            = errors.New("validUntil not specified")
	ErrMissingCredentialSubject     = errors.New("credentialSubject is required")
	ErrEmptyCredentialSubject       = errors.New("credentialSubject cannot be empty")
	ErrInvalidIssuerFormat          = errors.New("invalid issuer format")
	ErrInvalidProofFormat           = errors.New("invalid proof format")
	ErrMissingProof                 = errors.New("proof is required")
	ErrInvalidCredentialStatusType  = errors.New("credentialStatus must have a type")
	ErrInvalidCredentialSchemaType  = errors.New("credentialSchema must have a type")
	ErrInvalidRefreshServiceType    = errors.New("refreshService must have a type")
	ErrInvalidTermsOfUseType        = errors.New("termsOfUse must have a type")
	ErrInvalidEvidenceType          = errors.New("evidence must have a type")
	ErrInvalidRelatedResource       = errors.New("invalid relatedResource")
	ErrInvalidLanguageValueObject   = errors.New("invalid language value object")
	ErrReservedTypeRedefinition     = errors.New("reserved type cannot be redefined")
	ErrInvalidIssuerDescription     = errors.New("issuer description cannot have extra properties")
	ErrInvalidCredentialDescription = errors.New("credential description cannot have extra properties")
	ErrInvalidNameValueObject       = errors.New("name must be a string or language value object")
	ErrInvalidIssuerName            = errors.New("issuer name must be a string or language value object")
	ErrContextNotArray              = errors.New("@context must be an array")
	ErrTypeNotArray                 = errors.New("type must be an array")
	ErrInvalidTypeValue             = errors.New("type value must be a valid term or URL")
	ErrInvalidIDFormat              = errors.New("id must be a valid URL")
)

Validation errors

View Source
var (
	ErrContextNotFound     = errors.New("context document not found")
	ErrContextHashMismatch = errors.New("context hash does not match expected value")
	ErrInvalidContextURL   = errors.New("invalid context URL")
)

Context errors

View Source
var (
	ErrUnsupportedCryptosuite = errors.New("unsupported cryptographic suite")
	ErrInvalidSignature       = errors.New("invalid signature")
	ErrInvalidProofValue      = errors.New("invalid proof value")
	ErrInvalidKeyFormat       = errors.New("invalid key format")
	ErrSigningFailed          = errors.New("signing failed")
	ErrVerificationFailed     = errors.New("verification failed")
)

Cryptographic errors

View Source
var (
	ErrRDFCanonicalizationFailed = errors.New("RDF canonicalization failed")
	ErrInvalidRDFDataset         = errors.New("invalid RDF dataset")
	ErrBlankNodeRandomization    = errors.New("blank node randomization failed")
)

RDF errors

View Source
var (
	ErrInvalidJSONPointer = errors.New("invalid JSON pointer")
	ErrMandatoryPointer   = errors.New("mandatory pointer cannot be disclosed selectively")
	ErrInvalidSelection   = errors.New("invalid selection")
	ErrDerivedProofFailed = errors.New("derived proof creation failed")
)

Selective disclosure errors

Functions

func NewJSONLDOptions

func NewJSONLDOptions(base string) *ld.JsonLdOptions

NewJSONLDOptions creates a new JsonLdOptions with the global document loader configured

func ValidateCredential

func ValidateCredential(cred map[string]any) error

ValidateCredential performs structural validation on a Verifiable Credential Deprecated: Use NewValidator(log).ValidateCredential(cred) instead

func ValidatePresentation

func ValidatePresentation(vp map[string]any) error

ValidatePresentation performs structural validation on a Verifiable Presentation Deprecated: Use NewValidator(log).ValidatePresentation(vp) instead

Types

type CachingDocumentLoader

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

CachingDocumentLoader is a document loader that caches contexts in memory and preloads common contexts to avoid network requests

func GetGlobalLoader

func GetGlobalLoader() *CachingDocumentLoader

GetGlobalLoader returns the singleton caching document loader

func NewCachingDocumentLoader

func NewCachingDocumentLoader() *CachingDocumentLoader

NewCachingDocumentLoader creates a new caching document loader

func (*CachingDocumentLoader) AddContext

func (l *CachingDocumentLoader) AddContext(url string, content string)

AddContext adds a context to the cache manually

func (*CachingDocumentLoader) LoadDocument

func (l *CachingDocumentLoader) LoadDocument(url string) (*ld.RemoteDocument, error)

LoadDocument implements ld.DocumentLoader

type RDFCredential

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

RDFCredential represents a verifiable credential as an RDF dataset This avoids JSON marshaling issues and works directly with canonical RDF

func NewRDFCredentialFromJSON

func NewRDFCredentialFromJSON(jsonData []byte, options *ld.JsonLdOptions) (*RDFCredential, error)

NewRDFCredentialFromJSON parses a JSON-LD credential into an RDF dataset

func (*RDFCredential) CanonicalForm

func (rc *RDFCredential) CanonicalForm() (string, error)

CanonicalForm returns the canonical N-Quads representation This implements URDNA2015 normalization per W3C spec

func (*RDFCredential) CanonicalHash

func (rc *RDFCredential) CanonicalHash() (string, error)

CanonicalHash returns the SHA-256 hash of the canonical form

func (*RDFCredential) Context

func (rc *RDFCredential) Context() (any, error)

Context returns the @context from the original JSON

func (*RDFCredential) CredentialWithoutProof

func (rc *RDFCredential) CredentialWithoutProof() (*RDFCredential, error)

CredentialWithoutProof returns the credential as RDF without the proof object This is needed for signature verification

func (*RDFCredential) CredentialWithoutProofForTypes

func (rc *RDFCredential) CredentialWithoutProofForTypes(targetTypes ...string) (*RDFCredential, error)

CredentialWithoutProofForTypes returns the credential as RDF without the proof object attached to nodes of the specified types. If no types are provided, all proofs are removed.

func (*RDFCredential) Dataset

func (rc *RDFCredential) Dataset() *ld.RDFDataset

Dataset returns the underlying RDF dataset

func (*RDFCredential) MarshalJSON

func (rc *RDFCredential) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler to convert the RDF credential back to JSON-LD

func (*RDFCredential) NQuads

func (rc *RDFCredential) NQuads() (string, error)

NQuads returns the N-Quads representation without normalization This preserves the blank node identifiers from the input

func (*RDFCredential) NormalizeVerifiableCredentialGraph

func (rc *RDFCredential) NormalizeVerifiableCredentialGraph() error

NormalizeVerifiableCredentialGraph fixes an issue where json-gold puts VerifiableCredential in the default graph instead of a named graph when @context: null is used in the definition. This function moves the VC quads to a new named graph to match the expected structure.

func (*RDFCredential) OriginalJSON

func (rc *RDFCredential) OriginalJSON() string

OriginalJSON returns the original JSON input

func (*RDFCredential) ProofObject

func (rc *RDFCredential) ProofObject() (*RDFCredential, error)

ProofObject extracts the proof object as separate RDF

func (*RDFCredential) ToCompactJSON

func (rc *RDFCredential) ToCompactJSON() ([]byte, error)

ToCompactJSON returns the credential as compact JSON-LD using the original context. This is useful when you need to work with JSON pointers or preserve the original structure. If original JSON is available, it returns that directly (preserving the exact structure). Otherwise, it falls back to expanding and then compacting.

func (*RDFCredential) ToJSON

func (rc *RDFCredential) ToJSON() ([]byte, error)

ToJSON is a helper that calls MarshalJSON Deprecated: Use json.Marshal instead

type Validator

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

Validator performs structural validation on Verifiable Credentials and Presentations

func NewValidator

func NewValidator(log *logger.Log) *Validator

NewValidator creates a new Validator

Example
package main

import (
	"fmt"

	"github.com/SUNET/vc/pkg/logger"
	"github.com/SUNET/vc/pkg/vc20/credential"
)

func main() {
	log := logger.NewSimple("test")
	v := credential.NewValidator(log)
	fmt.Printf("%T\n", v)
}
Output:
*credential.Validator

func (*Validator) ValidateCredential

func (v *Validator) ValidateCredential(cred map[string]any) error

ValidateCredential performs structural validation on a Verifiable Credential to ensure compliance with W3C VC Data Model 2.0

Example
package main

import (
	"fmt"

	"github.com/SUNET/vc/pkg/logger"
	"github.com/SUNET/vc/pkg/vc20/credential"
)

func main() {
	log := logger.NewSimple("test")
	v := credential.NewValidator(log)

	// A minimal valid W3C VC 2.0 credential
	cred := map[string]any{
		"@context": []any{
			"https://www.w3.org/ns/credentials/v2",
		},
		"type":              []any{"VerifiableCredential"},
		"issuer":            "did:example:issuer",
		"credentialSubject": map[string]any{"id": "did:example:subject"},
	}

	err := v.ValidateCredential(cred)
	fmt.Println("valid credential:", err)
}
Output:
valid credential: <nil>
Example (MissingContext)
package main

import (
	"fmt"

	"github.com/SUNET/vc/pkg/logger"
	"github.com/SUNET/vc/pkg/vc20/credential"
)

func main() {
	log := logger.NewSimple("test")
	v := credential.NewValidator(log)

	// Missing @context
	cred := map[string]any{
		"type":              []any{"VerifiableCredential"},
		"issuer":            "did:example:issuer",
		"credentialSubject": map[string]any{"id": "did:example:subject"},
	}

	err := v.ValidateCredential(cred)
	fmt.Println(err)
}
Output:
missing @context

func (*Validator) ValidatePresentation

func (v *Validator) ValidatePresentation(vp map[string]any) error

ValidatePresentation performs structural validation on a Verifiable Presentation

Example
package main

import (
	"fmt"

	"github.com/SUNET/vc/pkg/logger"
	"github.com/SUNET/vc/pkg/vc20/credential"
)

func main() {
	log := logger.NewSimple("test")
	v := credential.NewValidator(log)

	// A minimal valid W3C VC 2.0 presentation
	vp := map[string]any{
		"@context": []any{
			"https://www.w3.org/ns/credentials/v2",
		},
		"type": []any{"VerifiablePresentation"},
	}

	err := v.ValidatePresentation(vp)
	fmt.Println("valid presentation:", err)
}
Output:
valid presentation: <nil>

Jump to

Keyboard shortcuts

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