Documentation
¶
Overview ¶
Package common contains shared types and helpers used across the VCVerifier codebase. This file defines the data model and helpers for W3C Bitstring Status List / StatusList2021 credentials referenced from a Verifiable Credential's `credentialStatus` field, as well as the IETF OAuth 2.0 Token Status List format (draft-ietf-oauth-status-list).
References:
Index ¶
- Constants
- Variables
- func BuildUrlString(address string, path string) string
- func DecodeBitstring(encoded string) ([]byte, error)
- func DecodeIETFBitstring(encoded string) ([]byte, error)
- func IsIETFStatusSet(bitstring []byte, index uint64, bitsPerStatus int) (bool, error)
- func IsStatusSet(bitstring []byte, index uint64, statusSize int) (bool, error)
- func ParseCredentialDates(raw JSONObject) (validFrom, validUntil *time.Time)
- func ParseSDJWT(combined string, verifyFunc func([]byte) ([]byte, error)) (map[string]interface{}, error)
- func ResetGlobalCache()
- type AllCaches
- type Cache
- type Clock
- type Credential
- type CredentialContents
- type CustomFields
- type DiskFileAccessor
- type FileAccessor
- type HttpClient
- type IETFStatusEntry
- type IETFStatusList
- type Issuer
- type JSONObject
- type JwtTokenSigner
- type LDProof
- type LDSigner
- type LinkedDataProofContext
- type OpenIDProviderMetadata
- type Presentation
- func (p *Presentation) AddCredentials(credentials ...*Credential)
- func (p *Presentation) AddLinkedDataProof(ctx *LinkedDataProofContext) error
- func (p *Presentation) Credentials() []*Credential
- func (p *Presentation) HolderKey() interface{}
- func (p *Presentation) MarshalJSON() ([]byte, error)
- func (p *Presentation) RawToken() []byte
- func (p *Presentation) SetHolderKey(key interface{})
- func (p *Presentation) SetRawToken(token []byte)
- type PresentationOpt
- type RealClock
- type StatusListCredential
- type StatusListEntry
- type Subject
- type TokenSigner
- type TypedID
Constants ¶
const ( // ContextCredentialsV1 is the W3C VC Data Model v1.1 context URI. ContextCredentialsV1 = "https://www.w3.org/2018/credentials/v1" // ContextCredentialsV2 is the W3C VC Data Model v2.0 context URI. ContextCredentialsV2 = "https://www.w3.org/ns/credentials/v2" // TypeVerifiableCredential is the base type for all Verifiable Credentials. TypeVerifiableCredential = "VerifiableCredential" // TypeVerifiablePresentation is the base type for all Verifiable Presentations. TypeVerifiablePresentation = "VerifiablePresentation" // JSONLDKeyContext is the JSON-LD @context key. JSONLDKeyContext = "@context" // JSONLDKeyType is the JSON-LD type key. JSONLDKeyType = "type" // JSONLDKeyID is the JSON-LD id key. JSONLDKeyID = "id" // VCKeyIssuer is the issuer key in a VC JSON representation. VCKeyIssuer = "issuer" // VCKeyCredentialSubject is the credentialSubject key in a VC JSON representation. VCKeyCredentialSubject = "credentialSubject" // VCKeyValidFrom is the validFrom key (VC Data Model 2.0). VCKeyValidFrom = "validFrom" // VCKeyValidUntil is the validUntil key (VC Data Model 2.0). VCKeyValidUntil = "validUntil" // VCKeyCredentialStatus is the credentialStatus key. VCKeyCredentialStatus = "credentialStatus" // VCKeyCredentialSchema is the credentialSchema key. VCKeyCredentialSchema = "credentialSchema" // VCKeyEvidence is the evidence key. VCKeyEvidence = "evidence" // VCKeyTermsOfUse is the termsOfUse key. VCKeyTermsOfUse = "termsOfUse" // VCKeyRefreshService is the refreshService key. VCKeyRefreshService = "refreshService" // VPKeyHolder is the holder key in a VP JSON representation. VPKeyHolder = "holder" // VPKeyVerifiableCredential is the verifiableCredential key in a VP JSON representation. VPKeyVerifiableCredential = "verifiableCredential" // VPKeyProof is the proof key in a VP/VC JSON representation. VPKeyProof = "proof" // VCKeyIssuanceDate is the issuanceDate key (VC Data Model 1.1). VCKeyIssuanceDate = "issuanceDate" // VCKeyExpirationDate is the expirationDate key (VC Data Model 1.1). VCKeyExpirationDate = "expirationDate" // VCKeyIssued is the issued key (legacy VC date field). VCKeyIssued = "issued" )
W3C Verifiable Credentials Data Model constants See https://www.w3.org/TR/vc-data-model-2.0/
const ( JWTClaimIss = "iss" // Issuer JWTClaimSub = "sub" // Subject JWTClaimJti = "jti" // JWT ID JWTClaimNbf = "nbf" // Not Before JWTClaimIat = "iat" // Issued At JWTClaimExp = "exp" // Expiration Time )
JWT standard claim keys (RFC 7519).
const ( JWTClaimVC = "vc" // VC claim in a JWT-encoded Verifiable Credential JWTClaimVP = "vp" // VP claim in a JWT-encoded Verifiable Presentation JWTClaimVct = "vct" // Verifiable Credential Type (SD-JWT VC) JWTClaimCnf = "cnf" // Confirmation method (RFC 7800, used for cryptographic holder binding) CnfKeyJWK = "jwk" // JWK key within the cnf claim (RFC 7800 §3.2) )
JWT-VC/VP specific claim keys.
const ( // TypeBitstringStatusListEntry is the `type` value of a credential's // `credentialStatus` entry that references a BitstringStatusListCredential. TypeBitstringStatusListEntry = "BitstringStatusListEntry" // TypeBitstringStatusListCredential is the `type` value of a status-list // credential that carries an encoded bitstring. TypeBitstringStatusListCredential = "BitstringStatusListCredential" // TypeStatusList2021Entry is the legacy StatusList2021 entry type. TypeStatusList2021Entry = "StatusList2021Entry" // TypeStatusList2021Credential is the legacy StatusList2021 credential type. TypeStatusList2021Credential = "StatusList2021Credential" )
Type names for status-list entries and status-list credentials as defined by the W3C Bitstring Status List and the legacy StatusList2021 specifications.
const ( // StatusListKeyEncodedList is the key on a status-list credential's // `credentialSubject` that carries the base64url-encoded, gzip-compressed // bitstring. StatusListKeyEncodedList = "encodedList" // StatusListKeyStatusPurpose is the key on a status-list credential's // `credentialSubject` that carries the purpose of the list (e.g. // "revocation" or "suspension"). StatusListKeyStatusPurpose = "statusPurpose" // StatusListEntryKeyType is the JSON-LD type key for a status-list entry. StatusListEntryKeyType = "type" // StatusListEntryKeyStatusListIndex is the key holding the index (as a // numeric string or number) into the referenced bitstring. StatusListEntryKeyStatusListIndex = "statusListIndex" // StatusListEntryKeyStatusListCredential is the URL key pointing at the // status-list credential to fetch. StatusListEntryKeyStatusListCredential = "statusListCredential" // StatusListEntryKeyStatusPurpose is the purpose declared on the entry // (must match the purpose of the fetched status-list credential). StatusListEntryKeyStatusPurpose = "statusPurpose" // StatusListEntryKeyStatusSize is the optional bit size per status on the // entry. Defaults to DefaultStatusSizeBits. StatusListEntryKeyStatusSize = "statusSize" )
JSON field keys used by status-list credentials and status-list entries.
const ( // IETFStatusClaimKey is the top-level key inside credentialSubject that // carries the IETF status reference. IETFStatusClaimKey = "status" // IETFStatusListKey is the nested key inside the status object. IETFStatusListKey = "status_list" // IETFStatusListIdx is the index key inside the status_list object. IETFStatusListIdx = "idx" // IETFStatusListURI is the URI key inside the status_list object. IETFStatusListURI = "uri" // IETFStatusListBits is the bits-per-status key in a fetched status list JWT payload. IETFStatusListBits = "bits" // IETFStatusListLst is the encoded-list key in a fetched status list JWT payload. IETFStatusListLst = "lst" // ContentTypeStatusListJWT is the Accept / Content-Type header for // IETF Token Status List JWT responses. ContentTypeStatusListJWT = "application/statuslist+jwt" )
IETF Token Status List constants — keys and types used by the OAuth 2.0 Token Status List specification (draft-ietf-oauth-status-list).
const ( // DefaultStatusSizeBits is the number of bits per status when an entry // does not declare `statusSize`. DefaultStatusSizeBits = 1 // BitsPerByte is the number of bits in a single byte. BitsPerByte = 8 )
Numeric defaults for status-list encoding.
const ( LDProofKeyCreated = "created" LDProofKeyVerificationMethod = "verificationMethod" )
Linked Data Proof JSON keys.
const ( JWSHeaderAlg = "alg" JWSHeaderB64 = "b64" JWSHeaderCrit = "crit" )
JWS header keys.
const ( LDNormFormatNQuads = "application/n-quads" LDNormAlgorithmURDNA = "URDNA2015" )
Linked Data normalization constants.
const ( SDJWTSeparator = "~" SDJWTClaimSd = "_sd" SDJWTClaimSdAlg = "_sd_alg" SDJWTAlgSHA256 = "sha-256" SDJWTJWTSeparator = "." )
const CacheExpiry = 60
const TYPE_ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token"
const TYPE_CODE = "authorization_code"
const TYPE_REFRESH_TOKEN = "refresh_token"
TYPE_REFRESH_TOKEN is the OAuth2 grant type for exchanging a refresh token for a new access token (RFC 6749 Section 1.5).
const TYPE_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange"
const TYPE_VP_TOKEN = "vp_token"
const TYPE_VP_TOKEN_SUBJECT = "urn:eu:oidf:vp_token"
Variables ¶
var ( // ErrorStatusListEntryMalformed is returned by ParseStatusListEntries when a // credential's `credentialStatus` value is of an unexpected shape or a // required field is missing or has the wrong type. ErrorStatusListEntryMalformed = errors.New("malformed credentialStatus entry") // ErrorStatusListBitstringDecode is returned by DecodeBitstring when the // encoded value cannot be base64url-decoded or gzip-inflated. ErrorStatusListBitstringDecode = errors.New("failed to decode status-list bitstring") // ErrorStatusListIndexOutOfRange is returned by IsStatusSet when the index // falls outside the range represented by the decoded bitstring. ErrorStatusListIndexOutOfRange = errors.New("status-list index out of range") // ErrorStatusListInvalidStatusSize is returned by IsStatusSet when // statusSize is not a positive integer. ErrorStatusListInvalidStatusSize = errors.New("invalid status-list statusSize") )
Typed errors returned by the helpers in this file. They are exported so callers can match against them using `errors.Is`.
var ( ErrorLDProofMarshal = errors.New("failed_to_marshal_presentation") ErrorLDProofUnmarshal = errors.New("failed_to_unmarshal_presentation") ErrorLDProofCanonDoc = errors.New("failed_to_canonicalize_document") ErrorLDProofCanonProof = errors.New("failed_to_canonicalize_proof_options") ErrorLDProofSign = errors.New("failed_to_sign") )
var ( ErrorInvalidDisclosure = errors.New("invalid_sd_jwt_disclosure") ErrorMissingSdAlg = errors.New("_sd_alg must be present in SD-JWT") ErrorUnsupportedSdAlg = errors.New("unsupported _sd_alg") ErrorInvalidSDJWTFormat = errors.New("invalid SD-JWT format") )
var GlobalCache = initCache()
Functions ¶
func BuildUrlString ¶
func DecodeBitstring ¶
DecodeBitstring returns the raw bitstring bytes referenced by a status-list credential. The input is the value carried on the credential's `credentialSubject.encodedList` field: a base64url-encoded, gzip-compressed byte sequence.
The returned slice is the inflated payload. Individual bits can be read with IsStatusSet.
func DecodeIETFBitstring ¶
DecodeIETFBitstring decodes an IETF Token Status List bitstring. The input is base64url-encoded, zlib (DEFLATE) compressed — note that this differs from the W3C format which uses gzip compression.
func IsIETFStatusSet ¶
IsIETFStatusSet reports whether the status value at the given index is non-zero in the IETF Token Status List bitstring. The IETF format uses LSB-first bit ordering within each byte, unlike the W3C format which uses MSB-first.
func IsStatusSet ¶
IsStatusSet reports whether the bit at the given status index is set in the provided bitstring. The bit ordering follows the W3C Bitstring Status List specification: bits are numbered from the most significant bit (bit 0) to the least significant bit (bit 7) within each byte, and bytes are read left-to-right.
Indexing uses `statusSize` bits per status. When statusSize > 1 the function currently returns true if ANY bit in the group is set — this matches the common "revoked / suspended" semantics where a non-zero group flags the credential. Callers requiring full multi-bit values should build on DecodeBitstring directly.
Returns ErrorStatusListIndexOutOfRange when the requested group is not covered by `bitstring`, and ErrorStatusListInvalidStatusSize when `statusSize` is not a positive integer.
func ParseCredentialDates ¶
func ParseCredentialDates(raw JSONObject) (validFrom, validUntil *time.Time)
ParseCredentialDates extracts validFrom/validUntil (VC Data Model 2.0) from a raw VC JSON object, falling back to their VC Data Model 1.0/1.1 equivalents issuanceDate/ expirationDate when the 2.0 properties are absent.
func ParseSDJWT ¶
func ParseSDJWT(combined string, verifyFunc func([]byte) ([]byte, error)) (map[string]interface{}, error)
ParseSDJWT parses an SD-JWT combined format token and returns the reconstructed claims. The combined format is: <issuer-JWT>~<disclosure1>~<disclosure2>~...~[<KB-JWT>] A plain JWT (without ~ separators) is also accepted per the SD-JWT spec.
verifyFunc is called with the raw issuer JWT bytes and should return the payload if signature verification succeeds. If verifyFunc is nil, the payload is extracted without verification.
func ResetGlobalCache ¶
func ResetGlobalCache()
Types ¶
type Credential ¶
type Credential struct {
// contains filtered or unexported fields
}
Credential represents a Verifiable Credential.
func CreateCredential ¶
func CreateCredential(contents CredentialContents, customFields CustomFields) (*Credential, error)
CreateCredential constructs a Credential from CredentialContents and custom fields.
func ParseCredentialJSON ¶
func ParseCredentialJSON(data []byte) (*Credential, error)
ParseCredentialJSON parses a Verifiable Credential from its JSON representation.
func (*Credential) Contents ¶
func (c *Credential) Contents() CredentialContents
Contents returns the structured content of the credential.
func (*Credential) CustomFields ¶
func (c *Credential) CustomFields() CustomFields
CustomFields returns the custom fields of the credential.
func (*Credential) MarshalJSON ¶
func (c *Credential) MarshalJSON() ([]byte, error)
MarshalJSON serializes the credential to JSON bytes.
func (*Credential) SetRawJSON ¶
func (c *Credential) SetRawJSON(raw JSONObject)
SetRawJSON stores a pre-built raw JSON map to be returned by ToRawJSON().
func (*Credential) ToRawJSON ¶
func (c *Credential) ToRawJSON() JSONObject
ToRawJSON converts the credential to a JSON map representation. Custom fields from the subject are placed at the top level of credentialSubject.
type CredentialContents ¶
type CredentialContents struct {
Context []string
ID string
Types []string
Issuer *Issuer
Subject []Subject
ValidFrom *time.Time
ValidUntil *time.Time
Status *TypedID
Schemas []TypedID
Evidence []interface{}
TermsOfUse []TypedID
RefreshService []TypedID
}
CredentialContents contains the structured content of a Verifiable Credential. Fields align with the W3C VC Data Model 2.0 specification.
type CustomFields ¶
type CustomFields map[string]interface{}
CustomFields holds additional fields beyond the standard VC fields.
type DiskFileAccessor ¶
type DiskFileAccessor struct{}
type FileAccessor ¶
type HttpClient ¶
basic interface for a generic http client
type IETFStatusEntry ¶
type IETFStatusEntry struct {
// Idx is the zero-based index into the status list bitstring.
Idx uint64
// URI is the URL of the status list resource to fetch.
URI string
}
IETFStatusEntry represents a parsed status reference from the IETF OAuth 2.0 Token Status List format. The entry is extracted from `credentialSubject.status.status_list` with fields `idx` and `uri`.
func ParseIETFStatusEntry ¶
func ParseIETFStatusEntry(credentialSubject map[string]interface{}) (IETFStatusEntry, bool)
ParseIETFStatusEntry extracts an IETFStatusEntry from the `credentialSubject` map of a Verifiable Credential. The expected structure is: `{ "status": { "status_list": { "idx": N, "uri": "..." } } }`.
Returns (entry, true) on success, or (zero, false) when the required structure is absent or malformed.
type IETFStatusList ¶
type IETFStatusList struct {
// Bits is the number of bits per status entry (e.g. 1, 2, 4, 8).
Bits int
// Lst is the base64url-encoded, zlib-compressed bitstring.
Lst string
}
IETFStatusList represents the decoded payload of a fetched IETF Token Status List JWT. The `lst` field is the base64url-encoded, zlib-compressed bitstring; `bits` declares the number of bits per status entry.
type Issuer ¶
type Issuer struct {
ID string
}
Issuer identifies the entity that issued a Verifiable Credential.
type JSONObject ¶
type JSONObject = map[string]interface{}
JSONObject is an alias for a generic JSON map.
type JwtTokenSigner ¶
type JwtTokenSigner struct{}
func (JwtTokenSigner) Sign ¶
func (JwtTokenSigner) Sign(t jwt.Token, options ...jwt.SignOption) ([]byte, error)
type LDProof ¶
type LDProof struct {
Type string `json:"type"`
Created string `json:"created"`
VerificationMethod string `json:"verificationMethod"`
JWS string `json:"jws"`
}
LDProof represents a Linked Data Proof attached to a Verifiable Presentation.
type LinkedDataProofContext ¶
type LinkedDataProofContext struct {
Created *time.Time
SignatureType string
Algorithm string // JWS algorithm name (e.g., "PS256")
VerificationMethod string
Signer LDSigner
DocumentLoader ld.DocumentLoader
}
LinkedDataProofContext holds parameters for creating a JsonWebSignature2020 LD-proof.
type OpenIDProviderMetadata ¶
type OpenIDProviderMetadata struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
PresentationDefinitionEndpoint string `json:"presentation_definition_endpoint,omitempty"`
JwksUri string `json:"jwks_uri"`
ScopesSupported []string `json:"scopes_supported"`
ResponseTypesSupported []string `json:"response_types_supported"`
ResponseModeSupported []string `json:"response_mode_supported,omitempty"`
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
SubjectTypesSupported []string `json:"subject_types_supported"`
IdTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
RequestObjectSigningAlgValuesSupported []string `json:"request_object_signing_alg_values_supported,omitempty"`
RequestParameterSupported bool `json:"request_parameter_supported,omitempty"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
}
type Presentation ¶
type Presentation struct {
Context []string
ID string
Type []string
Holder string
Proof *LDProof
// contains filtered or unexported fields
}
Presentation represents a Verifiable Presentation.
func NewPresentation ¶
func NewPresentation(opts ...PresentationOpt) (*Presentation, error)
NewPresentation creates a new Presentation with the given options applied.
func (*Presentation) AddCredentials ¶
func (p *Presentation) AddCredentials(credentials ...*Credential)
AddCredentials appends one or more credentials to the presentation.
func (*Presentation) AddLinkedDataProof ¶
func (p *Presentation) AddLinkedDataProof(ctx *LinkedDataProofContext) error
AddLinkedDataProof creates a JsonWebSignature2020 linked data proof and attaches it to the presentation.
func (*Presentation) Credentials ¶
func (p *Presentation) Credentials() []*Credential
Credentials returns the credentials contained in the presentation.
func (*Presentation) HolderKey ¶
func (p *Presentation) HolderKey() interface{}
HolderKey returns the public key that signed the VP JWT, if available.
func (*Presentation) MarshalJSON ¶
func (p *Presentation) MarshalJSON() ([]byte, error)
MarshalJSON serializes the presentation to JSON bytes.
func (*Presentation) RawToken ¶
func (p *Presentation) RawToken() []byte
RawToken returns the original VP JWT bytes, if available.
func (*Presentation) SetHolderKey ¶
func (p *Presentation) SetHolderKey(key interface{})
SetHolderKey stores the public key that signed the VP JWT.
func (*Presentation) SetRawToken ¶
func (p *Presentation) SetRawToken(token []byte)
SetRawToken stores the original VP JWT bytes for deferred verification.
type PresentationOpt ¶
type PresentationOpt func(*Presentation)
PresentationOpt is a functional option for configuring a Presentation.
func WithCredentials ¶
func WithCredentials(credentials ...*Credential) PresentationOpt
WithCredentials returns a PresentationOpt that adds credentials to a presentation.
type StatusListCredential ¶
type StatusListCredential struct {
// EncodedList is the base64url-encoded, gzip-compressed bitstring as it
// appears on the status-list credential's `credentialSubject.encodedList`
// field.
EncodedList string
// StatusPurpose is the purpose declared by the status-list credential
// (e.g. "revocation" or "suspension"). Callers must ensure this matches
// the purpose declared on the referencing status-list entry.
StatusPurpose string
}
StatusListCredential is a lightweight, decoded view of a status-list credential. The encoded bitstring is kept verbatim on the struct; use DecodeBitstring to obtain the raw bytes.
type StatusListEntry ¶
type StatusListEntry struct {
// ID is the optional `id` of the entry.
ID string
// Type is the JSON-LD type value of the entry (e.g.
// "BitstringStatusListEntry"). Empty when the source object omitted the
// field.
Type string
// StatusPurpose describes what the referenced bit represents (for example
// "revocation" or "suspension"). Empty when the source object omitted the
// field.
StatusPurpose string
// StatusListCredential is the URL of the status-list credential to fetch.
StatusListCredential string
// StatusListIndex is the zero-based bit index into the decoded bitstring.
StatusListIndex uint64
// StatusSize is the number of bits per status. Defaults to
// DefaultStatusSizeBits when not declared on the entry.
StatusSize int
}
StatusListEntry represents a parsed `credentialStatus` entry pointing at a Bitstring Status List or StatusList2021 credential.
func ParseStatusListEntries ¶
func ParseStatusListEntries(raw interface{}) ([]StatusListEntry, error)
ParseStatusListEntries converts the raw value found under a credential's `credentialStatus` field into a slice of StatusListEntry values.
The W3C VC Data Model 2.0 allows `credentialStatus` to be either a single object or an array of objects, so this helper accepts both shapes. A nil or missing value returns an empty slice with a nil error — callers treat "no status entries" as "nothing to check".
A non-nil error is returned if the value is of an unexpected shape or if a required field on any entry cannot be parsed into its target type.