auth

package module
v2.3.3 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: Apache-2.0, MIT Imports: 29 Imported by: 0

README

go-iden3-auth

Go Reference Go Report Card Test Lint

Library for verification of authorization response messages of communication protocol in JWZ format

go get github.com/iden3/go-iden3-auth/v2

General description:

The goal of iden3auth libraries is to handle authentication messages of communication protocol.

Currently, library implementation includes support of next message types

  1. https://iden3-communication.io/authorization/1.0/request
  2. https://iden3-communication.io/authorization/1.0/response

Auth verification procedure:

  1. JWZ token verification
  2. Zero-knowledge proof verification of request proofs
  3. Query request verification for atomic circuits
  4. Verification of identity and issuer states for atomic circuits
Zero-knowledge proof verification

Groth16 proof are supported by auth library

Verification keys must be provided using KeyLoader interface

Query verification

Proof for each atomic circuit contains public signals that allow extracting user and issuer identifiers, states, signature, challenges, etc.

Circuit public signals marshallers are defined in the go-circuits library.

Verification of user / issuer identity states

The blockchain verification algorithm is used

  1. Gets state from the blockchain (address of id state contract and URL must be provided by the caller of the library):

    1. Empty state is returned - it means that identity state hasn’t been updated or updated state hasn’t been published. We need to compare id and state. If they are different it’s not a genesis state of identity then it’s not valid.
    2. The non-empty state is returned and equals to the state in provided proof which means that the user state is fresh enough and we work with the latest user state.
    3. The non-empty state is returned and it’s not equal to the state that the user has provided. Gets the transition time of the state. The verification party can make a decision if it can accept this state based on that time frame.
  2. Only latest states for user are valid. Any existing issuer state for claim issuance is valid.

Verification of GIST

The blockchain verification algorithm is used

  1. Get GIST from the blockchain (address of id state contract and URL must be provided by the caller of the library):
    1. A non-empty GIST is returned, equal to the GIST is provided by the user, it means the user is using the latest state.
    2. The non-empty GIST is returned and it’s not equal to the GIST is provided by a user. Gets the transition time of the GIST. The verification party can make a decision if it can accept this state based on that time frame.

How to use:

  1. go get https://github.com/iden3/go-iden3-auth/v2

  2. Request generation:

    basic auth:

    var request protocol.AuthorizationRequestMessage
    // if you need'message' to sign (e.g. vote)
    request = auth.CreateAuthorizationRequestWithMessage("test flow", "message to sign","verifier id", "callback url")
    // or if you don't need 'message' to sign
    request = auth.CreateAuthorizationRequest("test flow","verifier id", "callback url")
    

    if you want request specific proof (example):

    var mtpProofRequest protocol.ZeroKnowledgeProofRequest
    mtpProofRequest.ID = 1
    mtpProofRequest.CircuitID = string(circuits.AtomicQueryMTPV2CircuitID)
    mtpProofRequest.Query = map[string]interface{}{
       "allowedIssuers": []string{"*"},
       "credentialSubject": map[string]interface{}{
          "countryCode": map[string]interface{}{
             "$nin": []int{840, 120, 340, 509},
          },
       },
       "context": "https://raw.githubusercontent.com/iden3/claim-schema-vocab/main/schemas/json-ld/kyc-v2.json-ld",
       "type":    "KYCCountryOfResidenceCredential",
    }
    request.Body.Scope = append(request.Body.Scope, mtpProofRequest)       
    
  3. Token verification

    Init Verifier:

    var verificationKeyloader = &loaders.FSKeyLoader{Dir: keyDIR}
    resolver := state.ETHResolver{
       RPCUrl:          <polygon_node_http>,
       ContractAddress: <state_contract_address>,
    }
    
    resolvers := map[string]pubsignals.StateResolver{
       "polygon:mumbai": resolver,
    }
    verifier,err := auth.NewVerifierWithExplicitError(verificationKeyloader, loaders.DefaultSchemaLoader{IpfsURL: "<IPFS NODE HERE>"}, resolvers)
    // or use NewVerifier and check that verifier instance is not nil. IPFS merklization is not worked without setuping global loader
    // verifier := auth.NewVerifier(verificationKeyloader, loaders.DefaultSchemaLoader{IpfsURL: "ipfs.io"}, resolvers)
    
  4. FullVerify:

    authResponse, err := verifier.FullVerify(
       r.Context(), 
       string(tokenBytes),
       authRequest.(protocolAuthorizationRequestMessage), 
       ...VerifyOpt,
    )
    userId = authResponse.from // msg sender
    

    Verify manually if thread id is used a session id to match request with VerifyJWZ / VerifyAuthResponse functions

Notes on prover optimization for x86_64 hardware

See readme in iden3/go-rapidsnark/prover

Contributing

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as below, without any additional terms or conditions.

License

© 2023 0kims Association

This project is licensed under either of

at your option.

Documentation

Index

Constants

View Source
const UniversalResolverURL = "https://dev.uniresolver.io/1.0/identifiers"

UniversalResolverURL is a url for universal resolver

Variables

View Source
var UniversalDIDResolver = packers.DIDResolverHandlerFunc(func(did string) (*verifiable.DIDDocument, error) {
	didDoc := &verifiable.DIDDocument{}

	resp, err := http.Get(fmt.Sprintf("%s/%s", UniversalResolverURL, did))

	if err != nil {
		return nil, err
	}

	defer func() {
		err := resp.Body.Close()
		if err != nil {
			log.Fatal(err)
		}
	}()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var didMetadata map[string]interface{}

	err = json.Unmarshal(body, &didMetadata)
	if err != nil {
		return nil, err
	}

	doc, ok := didMetadata["didDocument"]

	if !ok {
		return nil, errors.New("did document not found")
	}

	docBts, err := json.Marshal(doc)

	if err != nil {
		return nil, err
	}

	err = json.Unmarshal(docBts, &didDoc)

	if err != nil {
		return nil, err
	}

	return didDoc, nil
})

UniversalDIDResolver is a resolver for universal resolver

Functions

func CreateAuthorizationRequest

func CreateAuthorizationRequest(reason, sender, callbackURL string) protocol.AuthorizationRequestMessage

CreateAuthorizationRequest creates new authorization request message sender - client identifier reason - describes purpose of request callbackURL - url for authorization response

func CreateAuthorizationRequestWithMessage

func CreateAuthorizationRequestWithMessage(reason, message, sender,
	callbackURL string) protocol.AuthorizationRequestMessage

CreateAuthorizationRequestWithMessage creates new authorization request with message for signing with jwz

func CreateContractInvokeRequest

func CreateContractInvokeRequest(
	reason, sender string,
	transactionData protocol.TransactionData,
	zkRequests ...protocol.ZeroKnowledgeProofRequest,
) protocol.ContractInvokeRequestMessage

CreateContractInvokeRequest creates new contract invoke request message reason - describes purpose of request sender - sender identifier transactionData - data for on chain verification zkRequests - zero knowledge proof request(s)

func CreateContractInvokeRequestWithMessage

func CreateContractInvokeRequestWithMessage(
	reason, message, sender string,
	transactionData protocol.TransactionData,
	zkRequests ...protocol.ZeroKnowledgeProofRequest,
) protocol.ContractInvokeRequestMessage

CreateContractInvokeRequestWithMessage creates new contract invoke request message with message

func SetDocumentLoader

func SetDocumentLoader(schemaLoader ld.DocumentLoader)

SetDocumentLoader sets the default schema loader that would be used if other is not set with WithDocumentLoader option. Also, this document loader is set for go-schema-processor library to use it for merklize.

func ValidateAuthRequest added in v2.2.0

func ValidateAuthRequest(request protocol.AuthorizationRequestMessage) error

ValidateAuthRequest verifies auth request message

func VerifyState

func VerifyState(ctx context.Context, id, s *big.Int, opts state.ExtendedVerificationsOptions) error

VerifyState allows to verify state without binding to verifier instance

Types

type Verifier

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

Verifier is a struct for auth instance

func NewVerifier

func NewVerifier(
	keyLoader loaders.VerificationKeyLoader,
	resolver map[string]pubsignals.StateResolver,
	opts ...VerifierOption,
) (*Verifier, error)

NewVerifier returns setup instance of auth library

func (*Verifier) FullVerify

FullVerify performs verification of jwz token and auth request

func (*Verifier) SetPackageManager

func (v *Verifier) SetPackageManager(manager iden3comm.PackageManager)

SetPackageManager sets the package manager for the VerifierBuilder.

func (*Verifier) SetPacker

func (v *Verifier) SetPacker(packer iden3comm.Packer) error

SetPacker sets the custom packer manager for the VerifierBuilder.

func (*Verifier) SetupAuthV2ZKPPacker

func (v *Verifier) SetupAuthV2ZKPPacker() error

SetupAuthV2ZKPPacker sets the custom packer manager for the VerifierBuilder.

func (*Verifier) SetupJWSPacker

func (v *Verifier) SetupJWSPacker(didResolver packers.DIDResolverHandlerFunc) error

SetupJWSPacker sets the JWS packer for the VerifierBuilder.

func (*Verifier) VerifyAuthResponse

VerifyAuthResponse performs verification of auth response based on auth request

func (*Verifier) VerifyJWZ

func (v *Verifier) VerifyJWZ(
	ctx context.Context,
	token string,
	opts ...pubsignals.VerifyOpt,
) (t *jwz.Token, err error)

VerifyJWZ performs verification of jwz token

type VerifierOption

type VerifierOption func(opts *verifierOpts)

VerifierOption is a function to set options for Verifier instance

func WithDIDResolver

func WithDIDResolver(resolver packers.DIDResolverHandlerFunc) VerifierOption

WithDIDResolver sets the DID resolver for Verifier instance. The default value is UniversalDIDResolver.

func WithDocumentLoader

func WithDocumentLoader(docLoader ld.DocumentLoader) VerifierOption

WithDocumentLoader sets the document loader for Verifier instance

func WithIPFSClient

func WithIPFSClient(ipfsCli *shell.Shell) VerifierOption

WithIPFSClient sets the IPFS client for document loader of Verifier instance. If document loader is set with WithDocumentLoader function, this option is ignored.

func WithIPFSGateway

func WithIPFSGateway(ipfsGW string) VerifierOption

WithIPFSGateway sets the IPFS gateway for document loader of Verifier instance. If document loader is set with WithDocumentLoader function, this option is ignored. If WithIPFSClient is set, this option is ignored also.

Directories

Path Synopsis
mock
Package mock_state is a generated GoMock package.
Package mock_state is a generated GoMock package.

Jump to

Keyboard shortcuts

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