zcap-developer-guide

zCap (Authorization Capabilities) Developer’s Guide

CC BY-NC-SA 4.0

A hands-on guide for developers working with zCaps (Authorization Capabilities).

Report issues to this guide’s repo: https://github.com/interop-alliance/zcap-developer-guide

Table of Contents

Motivation

Currently, Authorization Capabilities (zCaps for short) are in an awkward but familiar situation where the deployed state of the art is significantly ahead of the specification.

This implementation guide is meant to fill the gap between the spec and its usage in production.

Introduction

What are Authorization Capabilities? (Aside from a less confusing name for object capabilities.) You can think of them as advanced structured access tokens, with some key features built in, including cryptographic proof of possession, as well as a compact way of chaining proofs together for purposes of delegation.

They are incredibly useful for advanced authorization use cases such as for:

What do we mean by “structured access tokens”? Basically, they’re JSON objects (although they can also be serialized to other formats, such as CBOR) with the following properties, which roughly answer the question of “who can perform what actions with a given resource, given these restrictions”:

Here is a (simplified) example zcap (given in Javascript notation just so we can add comments):

{
  // Unique id for the zcap (optional, but often useful)
  id: 'urn:uuid:b7576396-c032-46eb-9726-2a628a72828d',

  // 'who' - the DID of the agent that is allowed to perform actions
  controller: 'did:key:z6MkpmRaHigFewVnmQtLEYS8Zckb4kJNDJCk3bSFeiJNQfZy',

  // 'can' - which actions (here, HTTP verbs) they're allowed to perform
  allowedAction: ['GET', 'POST'],

  // 'with' - what resource can those actions be performed on
  invocationTarget: 'https://example.com/api/hello'
}

This is a simplified example, in that it’s missing things like expiration, or any sense of who granted that permission in the first place, nor does it have any kind of proof chain.

But hopefully you can already get a sense of what this object is for – you can give it to any app, AI agent, or microservice, that can manage its own keys (that can prove control over the cryptographic key serialized as the did:key DID). And now that app can perform authorized API requests (via http GET and POST actions) to a given API endpoint (here, https://example.com/api/hello). Specifically, it would include the zcap in its API requests, either by stuffing it into HTTP headers in case of REST APIs, or by passing it along as a parameter in case of JSON-RPC or something similar.

And, of course, the requests would need to include a cryptographic proof of control (similar to what DPoP does), so that even if the API requests were intercepted by a third party, the zcaps could not be reused/replayed (as long as the original app did not leak its private keys).

When to Use zCaps (and When Not To)

Limitations and Future Work

Terminology

action, allowed action

A list of operations that the holder of the zcap is allowed to perform on the target, provided they can provide an invocation signature.

agent

Any entity, usually an app (mobile, desktop or web app), an AI agent, or cloud microservice, capable of generating or storing cryptographic material (at least a public/private keypair) so that it can prove cryptographic control over its identifier.

attenuation

Authorization header

An HTTP header typically used to carry request authorizations. See Constructing the Authorization Header.

capability chain, proof chain

caveat

See attenuation.

controller

The DID of the agent authorized to invoke a capability.

data integrity proof

A way to cryptographically sign a structured document (like a JSON object), used for chained delegation proofs. See the Verifiable Credential Data Integrity 1.0 specification for more details.

delegation

Digest header

An HTTP header containing a digest hash of the request body. See Constructing the Digest Header.

DID, Decentralized Identifier

See Decentralized Identifier 1.1 spec

expiration

An optional zcap property with a timestamp determining when a zcap expires. The timestamp is a string, in XML-Schema dateTimeStamp format (web developers may be familiar with this format from the Javascript toISOString() function).

HTTP Signatures

Refers to RFC9421: HTTP Message Signatures, a specification that details how to sign HTTP requests (headers and body). However, see the Current vs Future Deployments section for more discussion.

invocation, capability invocation

The act of invoking a capability at the intended destination (resource server), a combination of presenting the capability, and also proving cryptographic control (usually via a digital signature).

Analogy: a government servant may possess a badge of office in their pocket, but specifically the act of presenting the badge to some other person (and thus proving possession of the badge, even if not cryptographicaly) would be the equivalent of invoking a capability.

key, cryptographic key

Used to sign capability invocations, HTTP headers, and to generate delegation proofs. For zCaps specifically, this is likely to be an asymmetric key pair, using an appropriate elliptic curve such as ed25519.

resource server, RS

A server hosting a resource that’s protected by an authorization capability. For API use cases, it’s the API server itself, for storage use cases, it’s the actual file or database server hosting the individual objects specified in invocationTarget. Note: The RS is ultimately responsible for verifying and enforcing zCaps.

revocation

A way to revoke (make invalid) a given zcap, after it was issued.

root zcap

Using zCaps to make authorization-carrying HTTP requests is done in one of two modes: either using a root capability, or using a delegated capability.

Root zcaps are used in cases where full “admin” access is appropriate. All other zcaps are delegated by the agent holding a root zcap. Delegation is expressed in the proof chain section of a zcap.

See Creating a Root zCap

signer

See Creating a did:key Signer Instance

target, invocation target

zcap

Short for ‘Authorization Capability’. Used generally to refer to a specific capability constructed according to the Authorization Capabilities for Linked Data v0.3 specification. Sometimes used as a general term for a stuctured access token with proof of control and the ability to do delegation chain proofs.

For Object Capability enthusiasts: zCaps are an example of a certificate-based capability, as opposed to platform capabilities such as those used by the OCapN protocol. Don’t worry, though, ‘certificate-based’ just means that it uses a digital signature, you won’t actually have to wrangle x509 certificates.

zCap Lifecycle

Creating and Delegating zCaps

Creating a root zCap

Creating a root zcap is easy:

  1. Choose a URL for which this zcap is intended. This will determine both the invocationTarget and the zcap’s id
  2. Construct the id like so: urn:zcap:root:${encodeURIComponent(url)}
  3. Choose the controller DID
  4. Put it all together using the root zcap template (see below)

Javascript example of how to construct a root zcap, provided you know the URL that it’s intended for, and the DID of the controller:

const ROOT_ZCAP_TEMPLATE = {
  '@context': [
    'https://w3id.org/zcap/v1',
    // Assumes you're using an ed25519 based DID; substitute as appropriate
    'https://w3id.org/security/suites/ed25519-2020/v1'
  ],
  id: 'urn:zcap:root:...',
  controller: 'did:...',
  invocationTarget: 'https://example.com/api/endpoint'
};

const url = 'https://example.com/api/endpoint';
const did = 'did:key:z6MknBxrctS4KsfiBsEaXsfnrnfNYTvDjVpLYYUAN6PX2EfG';
const rootCapability = {
  ...ROOT_ZCAP_TEMPLATE,
  id: `urn:zcap:root:${encodeURIComponent(url)}`,
  controller: did,
  invocationTarget: url
};

Example root zcap:

{
  "@context": [
    "https://w3id.org/zcap/v1", "https://w3id.org/security/suites/ed25519-2020/v1"
  ],
  "id": "urn:zcap:root:https%3A%2F%2Fexample.com%2Fapi",
  "controller": "did:key:z6Mkfeco2NSEPeFV3DkjNSabaCza1EoS3CmqLb1eJ5BriiaR",
  "invocationTarget": "https://example.com/api"
}

Delegating a zCap

import { Ed25519Signature2020 } from '@digitalcredentials/ed25519-signature-2020';
import { ZcapClient } from '@digitalcredentials/ezcap';

const zcapClient = new ZcapClient({
  delegationSigner: capabilityDelegationKey.signer(),
  SuiteClass: Ed25519Signature2020
});

const allowedActions = ['GET']
// DID identifying the entity to delegate to.
const delegatee = 'did:key:...';

const url = 'https://example.com/api/endpoint';

// Pass in the zcap to delegate - either the original root zcap or its descendant
const capability = rootZcap;

const delegatedCapability = await zcapClient.delegate({
  url, capability, targetDelegate: delegatee, allowedActions
});

Example delegated zcap:

{
  "@context": [
    "https://w3id.org/zcap/v1", "https://w3id.org/security/suites/ed25519-2020/v1"
  ],
  "id": "urn:zcap:delegated:z9gLKoFmKHwhxCzmo91Ywnh",
  "parentCapability": "urn:zcap:root:https%3A%2F%2Fexample.com%2Fdocuments",
  "invocationTarget": "https://example.com/documents",
  "controller": "did:key:z6MknBxrctS4KsfiBsEaXsfnrnfNYTvDjVpLYYUAN6PX2EfG",
  "expires": "2022-11-28T20:53:06Z",
  "allowedAction": ["read"],
  "proof": {
    "type": "Ed25519Signature2020",
    "created": "2021-11-28T20:53:06Z",
    "verificationMethod": "did:key:z6Mkfeco2NSEPeFV3DkjNSabaCza1EoS3CmqLb1eJ5BriiaR#z6Mkfeco2NSEPeFV3DkjNSabaCza1EoS3CmqLb1eJ5BriiaR",
    "proofPurpose": "capabilityDelegation",
    "capabilityChain": [
      "urn:zcap:root:https%3A%2F%2Fexample.com%2Fdocuments"
    ],
    "proofValue": "z244yxzRuFMyGfK85QcE6UewEZ3JpGDDTCvBKuxNiwdnxF3AmsSAoVYTBPLvFpYV7SeeWB4tUBGMGTF7pka6xR3av"
  }
}

Requesting zCaps

How does an agent request a zCap? (From the resource server’s controller or similar appropriate entity.)

Example zCap request:

{
    "verifiablePresentationRequest": {
      "interact": {
        "type": "UnmediatedHttpPresentationService2021",
        "serviceEndpoint": "https://example.com/exchanges/tx/12345"
      },
      "query": [
        {
          "type": "ZcapQuery",
          "capabilityQuery": {
            "reason":
              "Example App is requesting the permission to read and write to the Verifiable Credentials and VC Evidence collections.",
            "allowedAction": ["GET", "PUT", "POST"],
            "controller": "did:example:12345",
            "invocationTarget": 
              { "type": "urn:was:collection", "contentType": "application/vc", "name": "VerifiableCredential collection"}
          }
        }
      ]
    }
}

Revoking zCaps

Using zCaps with HTTP Requests

Code Examples

Although this guide goes into the details (below) of how to construct an HTTP request using zCaps for authorization, developers are likely to interact with zCaps using some sort of REST client with a wrapper that constructs the necessary headers.

Javascript example, using a root capability to make requests. Note that to use a root zcap, the client needs to know just two things:

  1. Which cryptographic key type to use (that’s the Ed25519Signature2020 suite)
  2. A signer, which is an abstract handle to a signature function. Signers are either provisioned at config time (with a private key loaded from an environment secret), or, preferably, used via an HSM (Hardware Security Module).
import { Ed25519Signature2020 } from '@digitalcredentials/ed25519-signature-2020'
import { ZcapClient } from '@digitalcredentials/ezcap'

const rootSigner = await loadOrConstructRootSigner()

// Construct a client, pass it the ability to sign requests (via invocationSigner)
const zcapClient = new ZcapClient({
  SuiteClass: Ed25519Signature2020, invocationSigner: rootSigner
})

// You can now perform authorization-carrying requests
const url = 'https://example.com/api/protected-endpoint'

const response = await zcapClient.request({
  url, method: 'GET', action: 'GET'
})
console.log(response)

When using a delegated zcap, you will need to also include it in each request. Example:

const capability = await loadDelegatedCapabilityFromConfig()
const invocationSigner = await loadSignerFromConfig()
const zcapClient = new ZcapClient({
  SuiteClass: Ed25519Signature2020, invocationSigner
})

// You can also include additional custom headers
const response = await zcapClient.request({
  url, capability, headers,
  method: 'POST', action: 'POST', json: { hello: "world" }
})
console.log(response)

Constructing an HTTP Request Algorithm Overview

Note: This section is mostly for the benefit of zCap library implementers. Developers wishing to use zCaps to make requests are encouraged to use existing libraries whenever possible, such as the @digitalcredentials/ezcap Javascript library.

To create an authorized HTTP request by invoking a given zcap, follow this general algorithm:

  1. Construct the Capability-Invocation header
  2. Construct the Digest header if applicable (only if your request has a body/payload – applicable for PUT/POST but not for GET)
  3. Assemble the pseudo-headers and headers to sign: ['(key-id)', '(created)', '(expires)', '(request-target)','host', 'capability-invocation']
    • If request has a body, add 'content-type', 'digest' headers to the above list
  4. Create the signature string (see below for details)
  5. Construct the Authorization header, add the signature and other relevant parameters
  6. Perform the HTTP request, include the Capability-Invocation, Authorization, and (optionally, if request has a body) the Digest headers

Current vs Future Deployments

The Capability-Invocation Header

For root zcap invocations, use the zcap id by itself:

Capability-Invocation: zcap id="urn:zcap:root:https%3A%2F%2Fexample.com%2Fapi"

For delegated (non-root) zcaps, include the full encoded gzip’d capability, as well as the action being invoked.

Example using JS string templates to construct the header for performing a GET action:

const encodedCapability = base64UrlEncode(gzip(JSON.stringify(capability)))

headers['capability-invocation'] = `zcap capability="${encodedCapability}",action="GET"`

JS Example - Capability-Invocation Header

Constructing the Digest Header

Example base64url encoded Digest header:

Digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=

Example Multihash encoded Digest header:

Digest: mh=uEiBfjwT2o6iSqqu922zyc4lEk3c5YNSjJbEF_uRu70ME8Q

Constructing the HTTP Message Signature

Constructing the Authorization Header

Example Authorization header:

Authorization: Signature keyId="...",algorithm="rsa-sha256",headers="...",created="...",expires="...",signature="..."

Verifying zCaps on the Resource Server

Performance Considerations

Caching zCaps by id for Verification

Case Studies

Using zCaps with Encrypted Data Vaults (EDVs)

Using zCaps with Wallet Attached Storage (WAS)

Appendix A: IANA Registration Considerations

Appendix B: Implementations

Appendix C: FAQ

Why Not OAuth 2

Developers familiar with common API authorization schemes might well ask, “how is this better than OAuth 2?”.

What About JSON-LD / Linked Data?

License

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

CC BY-NC-SA 4.0

Examples and code snippets are licensed under the MIT license.