├── .codecov.yaml ├── .github └── workflows │ ├── build.yml │ ├── publish.yaml │ └── sonar.yml ├── .gitignore ├── .golangci.yml ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── cmd ├── orb-cli │ ├── acceptlistcmd │ │ ├── acceptlist.go │ │ ├── acceptlist_test.go │ │ ├── getcmd.go │ │ ├── getcmd_test.go │ │ ├── updatecmd.go │ │ └── updatecmd_test.go │ ├── allowedoriginscmd │ │ ├── allowedorigins.go │ │ ├── allowedorigins_test.go │ │ ├── getcmd.go │ │ ├── getcmd_test.go │ │ ├── updatecmd.go │ │ └── updatecmd_test.go │ ├── common │ │ ├── activitypubclient.go │ │ ├── activitypubclient_test.go │ │ ├── common.go │ │ └── common_test.go │ ├── createdidcmd │ │ ├── createdid.go │ │ └── createdid_test.go │ ├── deactivatedidcmd │ │ ├── deactivatedid.go │ │ └── deactivatedid_test.go │ ├── followcmd │ │ ├── follow.go │ │ └── follow_test.go │ ├── go.mod │ ├── go.sum │ ├── ipfskeygencmd │ │ ├── keygen.go │ │ └── keygen_test.go │ ├── ipnshostmetagencmd │ │ ├── ipnshostmetagencmd.go │ │ └── ipnshostmetagencmd_test.go │ ├── ipnshostmetauploadcmd │ │ ├── ipnshostmetauploadcmd.go │ │ └── ipnshostmetauploadcmd_test.go │ ├── logcmd │ │ ├── getcmd.go │ │ ├── getcmd_test.go │ │ ├── log.go │ │ ├── log_test.go │ │ ├── updatecmd.go │ │ └── updatecmd_test.go │ ├── logmonitorcmd │ │ ├── getcmd.go │ │ ├── getcmd_test.go │ │ ├── logmonitor.go │ │ ├── logmonitor_test.go │ │ ├── updatecmd.go │ │ └── updatecmd_test.go │ ├── main.go │ ├── main_test.go │ ├── policycmd │ │ ├── getcmd.go │ │ ├── getcmd_test.go │ │ ├── policy.go │ │ ├── policy_test.go │ │ ├── updatecmd.go │ │ └── updatecmd_test.go │ ├── recoverdidcmd │ │ ├── recoverdid.go │ │ └── recoverdid_test.go │ ├── resolvedidcmd │ │ ├── resolvedid.go │ │ └── resolvedid_test.go │ ├── updatedidcmd │ │ ├── updatedid.go │ │ └── updatedid_test.go │ ├── vctcmd │ │ ├── vct.go │ │ ├── vct_test.go │ │ ├── verifycmd.go │ │ └── verifycmd_test.go │ └── witnesscmd │ │ ├── witness.go │ │ └── witness_test.go ├── orb-driver │ ├── go.mod │ ├── go.sum │ ├── main.go │ ├── main_test.go │ └── startcmd │ │ ├── start.go │ │ └── start_test.go └── orb-server │ ├── go.mod │ ├── go.sum │ ├── main.go │ ├── main_test.go │ └── startcmd │ ├── log.go │ ├── log_test.go │ ├── params.go │ ├── params_test.go │ ├── start.go │ └── start_test.go ├── go.mod ├── go.sum ├── images ├── orb-driver │ └── Dockerfile ├── orb-test │ └── Dockerfile └── orb │ └── Dockerfile ├── internal └── pkg │ ├── cmdutil │ ├── cmdutil.go │ └── cmdutil_test.go │ ├── ldcontext │ ├── ldcontext.go │ ├── ldcontext_test.go │ └── payload │ │ ├── activity-anchors-v1.json │ │ └── activity-streams.json │ ├── log │ ├── common.go │ ├── common_test.go │ ├── fields.go │ ├── fields_test.go │ └── mocks │ │ └── logfieldencoder.go │ └── tlsutil │ ├── certpool.go │ ├── certpool_test.go │ ├── tlsutil.go │ └── tlsutil_test.go ├── pkg ├── activitypub │ ├── client │ │ ├── client.go │ │ ├── client_test.go │ │ ├── mocks │ │ │ ├── authtokenmgr.gen.go │ │ │ ├── httpclient.gen.go │ │ │ └── httpsigner.gen.go │ │ ├── transport │ │ │ ├── transport.go │ │ │ └── transport_test.go │ │ └── util.go │ ├── httpsig │ │ ├── algorithm.go │ │ ├── algorithm_test.go │ │ ├── signer.go │ │ ├── signer_test.go │ │ ├── verifier.go │ │ └── verifier_test.go │ ├── mocks │ │ ├── acceptlistmgr.gen.go │ │ ├── activityiterator.gen.go │ │ ├── authtokenmgr.gen.go │ │ ├── httpsigverifier.gen.go │ │ ├── httptransport.gen.go │ │ └── keyresolver.gen.go │ ├── resthandler │ │ ├── acceptlisthandler.go │ │ ├── acceptlisthandler_test.go │ │ ├── activityhandler.go │ │ ├── activityhandler_test.go │ │ ├── authhandler.go │ │ ├── authhandler_test.go │ │ ├── openapi.go │ │ ├── outboxhandler.go │ │ ├── outboxhandler_test.go │ │ ├── referencehandler.go │ │ ├── referencehandler_test.go │ │ ├── resthandler.go │ │ ├── resthandler_test.go │ │ ├── serviceshandler.go │ │ └── serviceshandler_test.go │ ├── service │ │ ├── acceptlist │ │ │ ├── acceptlist.go │ │ │ └── acceptlist_test.go │ │ ├── activityhandler │ │ │ ├── acceptlistauthhandler.go │ │ │ ├── acceptlistauthhandler_test.go │ │ │ ├── activityhandler.go │ │ │ ├── activityhandler_test.go │ │ │ ├── inboxhandler.go │ │ │ └── outboxhandler.go │ │ ├── anchorsynctask │ │ │ ├── activitysynctask.go │ │ │ ├── activitysynctask_test.go │ │ │ ├── syncstore.go │ │ │ └── syncstore_test.go │ │ ├── inbox │ │ │ ├── httpsubscriber │ │ │ │ ├── httpsubscriber.go │ │ │ │ └── httpsubscriber_test.go │ │ │ ├── inbox.go │ │ │ └── inbox_test.go │ │ ├── mocks │ │ │ ├── acceptlistmgr.gen.go │ │ │ ├── activities.go │ │ │ ├── activityhandler.gen.go │ │ │ ├── activityiterator.gen.go │ │ │ ├── activitystore.gen.go │ │ │ ├── mockacceptfollowhandler.go │ │ │ ├── mockactivitypubclient.go │ │ │ ├── mockanchoreventackhandler.go │ │ │ ├── mockanchoreventhandler.go │ │ │ ├── mockfollowerauth.go │ │ │ ├── mockoutbox.go │ │ │ ├── mockproofhandler.go │ │ │ ├── mockpubsub.go │ │ │ ├── mocksubscriber.go │ │ │ ├── mockundofollowhandler.go │ │ │ ├── mockwitnesshandler.go │ │ │ ├── referenceiterator.gen.go │ │ │ ├── sigfnatureverifier.gen.go │ │ │ ├── taskmgr.go │ │ │ └── webfingerresolver.go │ │ ├── outbox │ │ │ ├── outbox.go │ │ │ └── outbox_test.go │ │ ├── service.go │ │ ├── service_test.go │ │ └── spi │ │ │ └── spi.go │ ├── store │ │ ├── ariesstore │ │ │ ├── ariesstore.go │ │ │ ├── ariesstore_internal_test.go │ │ │ └── ariesstore_test.go │ │ ├── memstore │ │ │ ├── iterator.go │ │ │ ├── iterator_test.go │ │ │ ├── memstore.go │ │ │ └── memstore_test.go │ │ ├── mocks │ │ │ └── referenceiterator.gen.go │ │ ├── spi │ │ │ ├── spi.go │ │ │ └── spi_test.go │ │ └── storeutil │ │ │ ├── storeutil.go │ │ │ └── storeutil_test.go │ └── vocab │ │ ├── activitytype.go │ │ ├── activitytype_test.go │ │ ├── actortype.go │ │ ├── actortype_test.go │ │ ├── anchoreventtype.go │ │ ├── anchoreventtype_test.go │ │ ├── collection.go │ │ ├── collection_test.go │ │ ├── collectionpage.go │ │ ├── collectionpage_test.go │ │ ├── contextproperty.go │ │ ├── contextproperty_test.go │ │ ├── linktype.go │ │ ├── linktype_test.go │ │ ├── objectproperty.go │ │ ├── objectproperty_test.go │ │ ├── objecttype.go │ │ ├── objecttype_test.go │ │ ├── options.go │ │ ├── options_test.go │ │ ├── tagproperty.go │ │ ├── tagproperty_test.go │ │ ├── typeproperty.go │ │ ├── typeproperty_test.go │ │ ├── urlproperty.go │ │ ├── urlproperty_test.go │ │ ├── util.go │ │ ├── util_test.go │ │ ├── vocab.go │ │ └── vocab_test.go ├── anchor │ ├── allowedorigins │ │ ├── allowedoriginsmgr │ │ │ ├── allowedoriginsmgr.go │ │ │ └── allowedoriginsmgr_test.go │ │ └── allowedoriginsrest │ │ │ ├── allowedoriginshandler.go │ │ │ └── allowedoriginshandler_test.go │ ├── anchorlinkset │ │ ├── anchorlinkset.go │ │ ├── anchorlinkset_test.go │ │ ├── generator │ │ │ ├── didorbgenerator │ │ │ │ ├── didorbgenerator.go │ │ │ │ └── didorbgenerator_test.go │ │ │ ├── didorbtestgenerator │ │ │ │ ├── didorbtestgenerator.go │ │ │ │ └── didorbtestgenerator_test.go │ │ │ ├── generatorregistry.go │ │ │ ├── generatorregistry_test.go │ │ │ └── samplegenerator │ │ │ │ └── samplegenerator.go │ │ └── vcresthandler │ │ │ ├── openapi.go │ │ │ ├── resthandler.go │ │ │ └── resthandler_test.go │ ├── builder │ │ ├── builder.go │ │ └── builder_test.go │ ├── graph │ │ ├── graph.go │ │ └── graph_test.go │ ├── handler │ │ ├── acknowlegement │ │ │ ├── acknowledgement.go │ │ │ └── acknowledgement_test.go │ │ ├── credential │ │ │ ├── handler.go │ │ │ └── handler_test.go │ │ ├── mocks │ │ │ ├── anchorindexstatus.gen.go │ │ │ ├── anchorlinkstore.gen.go │ │ │ └── witnessstore.gen.go │ │ └── proof │ │ │ ├── handler.go │ │ │ └── handler_test.go │ ├── info │ │ └── info.go │ ├── linkstore │ │ ├── linkstore.go │ │ └── linkstore_test.go │ ├── mocks │ │ ├── allowedoriginsmgr.gen.go │ │ └── anchorPublisher.gen.go │ ├── multierror │ │ ├── multierror.go │ │ └── multierror_test.go │ ├── subject │ │ └── model.go │ ├── util │ │ ├── anchordata.go │ │ ├── anchordata_test.go │ │ ├── util.go │ │ └── util_test.go │ ├── vcpubsub │ │ ├── publisher.go │ │ ├── subscriber.go │ │ └── vcpubsub_test.go │ ├── witness │ │ ├── policy │ │ │ ├── config │ │ │ │ ├── parser.go │ │ │ │ ├── parser_test.go │ │ │ │ ├── policystore.go │ │ │ │ └── policystore_test.go │ │ │ ├── inspector │ │ │ │ ├── inspector.go │ │ │ │ └── inspector_test.go │ │ │ ├── logfields.go │ │ │ ├── logfields_test.go │ │ │ ├── mocks │ │ │ │ ├── policystore.gen.go │ │ │ │ └── witnessstore.gen.go │ │ │ ├── policy.go │ │ │ ├── policy_test.go │ │ │ ├── resthandler │ │ │ │ ├── configurator.go │ │ │ │ ├── configurator_test.go │ │ │ │ ├── openapi.go │ │ │ │ ├── retriever.go │ │ │ │ └── retriever_test.go │ │ │ └── selector │ │ │ │ └── random │ │ │ │ ├── selector.go │ │ │ │ └── selector_test.go │ │ └── proof │ │ │ ├── proof.go │ │ │ └── proof_test.go │ └── writer │ │ ├── mocks │ │ └── webfingerclient.gen.go │ │ ├── writer.go │ │ └── writer_test.go ├── cache │ ├── cache.go │ └── cache_test.go ├── cas │ ├── extendedcasclient │ │ └── extendedcasclient.go │ ├── ipfs │ │ ├── ipfs.go │ │ ├── ipfs_test.go │ │ └── mocks │ │ │ └── ipfsclient.gen.go │ └── resolver │ │ ├── mocks │ │ └── casclient.gen.go │ │ ├── resolver.go │ │ └── resolver_test.go ├── config │ ├── client │ │ ├── client.go │ │ └── client_test.go │ └── config.go ├── context │ ├── common │ │ └── provider.go │ ├── context.go │ ├── context_test.go │ ├── mocks │ │ ├── DataExpiryService.gen.go │ │ └── pubsub.gen.go │ ├── opqueue │ │ ├── opqueue.go │ │ └── opqueue_test.go │ └── protocol │ │ ├── client │ │ ├── client.go │ │ └── client_test.go │ │ └── provider │ │ ├── provider.go │ │ └── provider_test.go ├── datauri │ ├── datauri.go │ └── datauri_test.go ├── didanchor │ ├── memdidanchor │ │ ├── store.go │ │ └── store_test.go │ └── refs.go ├── discovery │ ├── did │ │ ├── local │ │ │ ├── discovery.go │ │ │ └── discovery_test.go │ │ ├── mocks │ │ │ ├── didPublisher.gen.go │ │ │ └── endpointClient.gen.go │ │ └── noop │ │ │ ├── noop.go │ │ │ └── noop_test.go │ └── endpoint │ │ ├── client │ │ ├── client.go │ │ ├── client_test.go │ │ └── models │ │ │ └── endpoint.go │ │ └── restapi │ │ ├── anchorinfo.go │ │ ├── anchorinfo_test.go │ │ ├── mocks │ │ └── webresolver.gen.go │ │ ├── model.go │ │ ├── openapi.go │ │ ├── operations.go │ │ └── operations_test.go ├── document │ ├── didresolver │ │ ├── mocks │ │ │ ├── orbresolver.gen.go │ │ │ └── webresolver.gen.go │ │ ├── resolvehandler.go │ │ └── resolvehandler_test.go │ ├── mocks │ │ ├── discovery.gen.go │ │ ├── dochandler.gen.go │ │ ├── endpointclient.gen.go │ │ ├── operationprocessor.gen.go │ │ └── remoteresolver.gen.go │ ├── remoteresolver │ │ ├── remoteresolver.go │ │ └── remoteresolver_test.go │ ├── resolvehandler │ │ ├── openapi.go │ │ ├── resolvehandler.go │ │ └── resolvehandler_test.go │ ├── updatehandler │ │ ├── decorator │ │ │ ├── decorator.go │ │ │ └── decorator_test.go │ │ ├── mocks │ │ │ └── dochandler.gen.go │ │ ├── openapi.go │ │ ├── updatehandler.go │ │ └── updatehandler_test.go │ ├── util │ │ ├── util.go │ │ └── util_test.go │ └── webresolver │ │ ├── mocks │ │ └── orbresolver.gen.go │ │ ├── resolvehandler.go │ │ └── resolvehandler_test.go ├── driver │ └── restapi │ │ ├── operations.go │ │ └── operations_test.go ├── errors │ ├── errors.go │ └── errors_test.go ├── hashlink │ ├── hashlink.go │ └── hashlink_test.go ├── healthcheck │ ├── healthcheck.go │ └── healthcheck_test.go ├── httpserver │ ├── auth │ │ ├── authwrapper.go │ │ ├── authwrapper_test.go │ │ ├── signature │ │ │ ├── authwrapper.go │ │ │ ├── authwrapper_test.go │ │ │ └── mocks │ │ │ │ └── httphandler.gen.go │ │ ├── tokenverifier.go │ │ └── tokenverifier_test.go │ ├── maintenance │ │ ├── mode.go │ │ └── mode_test.go │ ├── server.go │ └── server_test.go ├── internal │ ├── aptestutil │ │ └── aptestutil.go │ ├── cacheutil │ │ ├── cacheutil.go │ │ └── cacheutil_test.go │ └── testutil │ │ ├── mongodbtestutil │ │ └── mongodbtestutil.go │ │ ├── rabbitmqtestutil │ │ └── rabbitmqtestutil.go │ │ ├── testutil.go │ │ └── tracer.go ├── lifecycle │ ├── lifecycle.go │ └── lifecycle_test.go ├── linkset │ ├── linkset.go │ └── linkset_test.go ├── mocks │ ├── anchorgraph.gen.go │ ├── anchorlinkstore.gen.go │ ├── configretriever.gen.go │ ├── domainResolver.gen.go │ ├── expiryservice.gen.go │ ├── metricsprovider.go │ ├── operationstore.go │ ├── protocol.go │ └── pubsub.gen.go ├── multihash │ ├── multihash.go │ └── multihash_test.go ├── nodeinfo │ ├── handler.go │ ├── handler_test.go │ ├── metadata.go │ ├── model.go │ ├── nodeinforetriever.gen.go │ ├── openapi.go │ ├── service.go │ └── service_test.go ├── observability │ ├── loglevels │ │ ├── loglevels.go │ │ ├── loglevels_test.go │ │ └── openapi.go │ ├── metrics │ │ ├── noop │ │ │ ├── provider.go │ │ │ └── provider_test.go │ │ ├── prometheus │ │ │ ├── handler.go │ │ │ ├── handler_test.go │ │ │ ├── mocks │ │ │ │ └── httpserver.gen.go │ │ │ ├── openapi.go │ │ │ ├── provider.go │ │ │ └── provider_test.go │ │ └── provider.go │ └── tracing │ │ ├── mocks │ │ └── pubsub.gen.go │ │ ├── otelamqp │ │ ├── otelamqp.go │ │ └── otelamqp_test.go │ │ ├── tracing.go │ │ └── tracing_test.go ├── observer │ ├── mocks │ │ └── monitoring.gen.go │ ├── observer.go │ ├── observer_test.go │ ├── pubsub.go │ └── pubsub_test.go ├── orbclient │ ├── aoprovider │ │ ├── anchororiginprovider.go │ │ └── anchororiginprovider_test.go │ ├── doctransformer │ │ ├── transformer.go │ │ └── transformer_test.go │ ├── mocks │ │ └── clientversionprovider.gen.go │ ├── protocol │ │ ├── nsprovider │ │ │ ├── namespaceprovider.go │ │ │ └── namespaceprovider_test.go │ │ └── verprovider │ │ │ ├── versionprovider.go │ │ │ └── versionprovider_test.go │ └── resolutionverifier │ │ ├── resolutionverifier.go │ │ └── resolutionverifier_test.go ├── protocolversion │ ├── clientregistry │ │ ├── clientregistry.go │ │ ├── clientregistry_test.go │ │ ├── mocks │ │ │ └── clientfactory.gen.go │ │ ├── testversions.go │ │ └── versions.go │ ├── common │ │ ├── version.go │ │ └── version_test.go │ ├── factoryregistry │ │ ├── factoryregistry.go │ │ ├── factoryregistry_test.go │ │ ├── mocks │ │ │ └── protocolfactory.gen.go │ │ ├── testversions.go │ │ └── versions.go │ ├── mocks │ │ ├── allowedoriginstore.go │ │ ├── anchorgraph.gen.go │ │ ├── casclient.gen.go │ │ ├── casresolver.gen.go │ │ └── operationstore.gen.go │ └── versions │ │ ├── common │ │ ├── protocol.go │ │ └── protocol_test.go │ │ ├── test │ │ └── v_test │ │ │ ├── client │ │ │ ├── client.go │ │ │ └── client_test.go │ │ │ ├── config │ │ │ ├── protocol.go │ │ │ └── protocol_test.go │ │ │ └── factory │ │ │ ├── factory.go │ │ │ └── factory_test.go │ │ └── v1_0 │ │ ├── client │ │ ├── client.go │ │ └── client_test.go │ │ ├── config │ │ ├── protocol.go │ │ └── protocol_test.go │ │ └── factory │ │ ├── factory.go │ │ └── factory_test.go ├── pubsub │ ├── amqp │ │ ├── amqppubsub.go │ │ ├── amqppubsub_test.go │ │ ├── marshaler.go │ │ ├── marshaler_test.go │ │ ├── pooledsubscriber.go │ │ ├── pooledsubscriber_test.go │ │ ├── publisherpool.go │ │ └── publisherpool_test.go │ ├── mempubsub │ │ ├── mempubsub.go │ │ └── mempubsub_test.go │ ├── pubsub.go │ ├── pubsub_test.go │ ├── spi │ │ └── spi.go │ └── wmlogger │ │ ├── mocks │ │ └── logger.gen.go │ │ ├── wmlogger.go │ │ └── wmlogger_test.go ├── resolver │ └── resource │ │ ├── registry │ │ ├── didanchorinfo │ │ │ ├── didanchorinfo.go │ │ │ ├── didanchorinfo_test.go │ │ │ └── mocks │ │ │ │ └── operationprocessor.gen.go │ │ ├── registry.go │ │ └── registry_test.go │ │ ├── resolver.go │ │ └── resolver_test.go ├── store │ ├── anchorlink │ │ ├── store.go │ │ └── store_test.go │ ├── anchorstatus │ │ ├── store.go │ │ └── store_test.go │ ├── cas │ │ ├── cas.go │ │ └── cas_test.go │ ├── didanchor │ │ ├── store.go │ │ └── store_test.go │ ├── expiry │ │ ├── expiry.go │ │ └── expiry_test.go │ ├── logentry │ │ ├── store.go │ │ └── store_test.go │ ├── logmonitor │ │ ├── store.go │ │ └── store_test.go │ ├── mocks │ │ ├── iterator.gen.go │ │ ├── mongodbiterator.gen.go │ │ ├── mongodbprovider.gen.go │ │ ├── mongodbstore.gen.go │ │ ├── provider.gen.go │ │ └── store.gen.go │ ├── operation │ │ ├── store.go │ │ ├── store_test.go │ │ └── unpublished │ │ │ ├── store.go │ │ │ └── store_test.go │ ├── publickey │ │ ├── publickeystore.go │ │ └── publickeystore_test.go │ ├── store.go │ ├── store_test.go │ ├── witness │ │ ├── witness.go │ │ └── witness_test.go │ └── wrapper │ │ ├── provider.go │ │ ├── provider_test.go │ │ ├── store.go │ │ └── store_test.go ├── taskmgr │ ├── taskmgr.go │ └── taskmgr_test.go ├── util │ ├── util.go │ └── util_test.go ├── vcsigner │ ├── signer.go │ └── signer_test.go ├── vct │ ├── logmonitoring │ │ ├── handler │ │ │ ├── handler.go │ │ │ └── handler_test.go │ │ ├── monitor.go │ │ ├── monitor_test.go │ │ ├── resthandler │ │ │ ├── retriever.go │ │ │ ├── retriever_test.go │ │ │ ├── update.go │ │ │ └── update_test.go │ │ └── verifier │ │ │ ├── verifier.go │ │ │ └── verifier_test.go │ ├── proofmonitoring │ │ ├── monitoring.go │ │ └── monitoring_test.go │ ├── resthandler │ │ ├── configurator.go │ │ ├── configurator_test.go │ │ ├── openapi.go │ │ ├── retriever.go │ │ └── retriever_test.go │ ├── vct.go │ └── vct_test.go ├── versions │ └── 1_0 │ │ ├── operationparser │ │ ├── parser.go │ │ ├── parser_test.go │ │ └── validators │ │ │ ├── anchororigin │ │ │ ├── validator.go │ │ │ └── validator_test.go │ │ │ └── anchortime │ │ │ ├── validator.go │ │ │ └── validator_test.go │ │ └── txnprocessor │ │ ├── txnprocessor.go │ │ └── txnprocessor_test.go ├── webcas │ ├── openapi.go │ ├── webcas.go │ ├── webcas_internal_test.go │ └── webcas_test.go └── webfinger │ ├── client │ ├── client.go │ └── client_test.go │ └── model │ └── model.go ├── samples ├── docker │ ├── contexts │ │ └── ld-contexts.json │ ├── docker-compose-dev-vct.yml │ └── docker-compose-dev.yml └── tutorial │ ├── README.md │ ├── cli.sh │ ├── contexts │ └── ld-contexts.json │ ├── create_publickeys.json │ ├── create_services.json │ ├── create_services2.json │ ├── docker-compose-cli.yml │ ├── jwk1.json │ ├── jwk2.json │ ├── jwk3.json │ ├── jwk4.json │ ├── nextupdate_publickey.pem │ ├── recover_publickey.pem │ ├── update_privatekey.pem │ ├── update_publickey.pem │ └── update_publickeys.json ├── scripts ├── build-cli.sh ├── check_license.sh ├── check_lint.sh ├── generate_test_keys.sh ├── integration_cas_ipfs.sh ├── integration_cas_local.sh ├── integration_versions_maintenance.sh └── unit.sh └── test └── bdd ├── bddtests_test.go ├── cli_steps.go ├── common_steps.go ├── compose.go ├── context.go ├── did_orb_steps.go ├── docker.go ├── docker_steps.go ├── driver_steps.go ├── features ├── activitypub.feature ├── create-dids-to-file.feature ├── did-orb.feature ├── did-sidetree.feature ├── loglevels.feature ├── nodeinfo.feature ├── onboard-recovery.feature ├── orb-cli.feature ├── orb-driver.feature ├── orb-stress.feature └── versions.feature ├── fixtures ├── .env ├── aws-config │ └── init │ │ └── seed.yaml ├── did-keys │ ├── create │ │ ├── key1_jwk.json │ │ ├── key2_jwk.json │ │ └── publickeys.json │ ├── recover │ │ ├── key1_jwk.json │ │ └── publickeys.json │ └── update │ │ ├── key2_jwk.json │ │ ├── key3_jwk.json │ │ └── publickeys.json ├── did-services │ ├── create │ │ └── services.json │ ├── recover │ │ └── services.json │ └── update │ │ └── services.json ├── docker-compose-testver.yml ├── docker-compose.yml ├── nginx-config │ └── nginx.conf ├── prometheus-config │ └── prometheus.yml ├── rabbitmq-config │ └── rabbitmq.conf ├── testdata │ ├── create_activity.json │ ├── keys │ │ ├── domain1 │ │ │ ├── private-key.pem │ │ │ └── public-key.pem │ │ ├── domain2 │ │ │ ├── private-key.pem │ │ │ └── public-key.pem │ │ └── domain3 │ │ │ ├── private-key.pem │ │ │ └── public-key.pem │ └── offer_activity.json └── uni-resolver-web │ └── config.json ├── go.mod ├── go.sum ├── httpclient.go ├── kmssigner.go ├── state.go ├── stress_steps.go ├── utils.go └── workerpool.go /.codecov.yaml: -------------------------------------------------------------------------------- 1 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | coverage: 6 | status: 7 | project: 8 | default: 9 | target: 80% 10 | patch: 11 | default: 12 | target: 85% 13 | only_pulls: true 14 | 15 | ignore: 16 | - "test/bdd" # ignore bdd tests 17 | - "pkg/mocks" # ignore mocks 18 | - "**/*.gen.go" # ignore generated files 19 | -------------------------------------------------------------------------------- /.github/workflows/sonar.yml: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | 7 | name: Sonar 8 | on: 9 | workflow_run: 10 | workflows: [Build] 11 | types: [requested] 12 | jobs: 13 | sonarcloud: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | with: 18 | # Disabling shallow clone is recommended for improving relevancy of reporting 19 | fetch-depth: 0 20 | - name: SonarCloud Scan 21 | uses: sonarsource/sonarcloud-github-action@master 22 | with: 23 | args: > 24 | -Dsonar.organization=trustbloc 25 | -Dsonar.projectKey=trustbloc_orb 26 | -Dsonar.scm.revision=${{ github.event.workflow_run.head_sha }} 27 | -Dsonar.pullrequest.key=${{ github.event.workflow_run.pull_requests[0].number }} 28 | -Dsonar.pullrequest.branch=${{ github.event.workflow_run.pull_requests[0].head.ref }} 29 | -Dsonar.pullrequest.base=${{ github.event.workflow_run.pull_requests[0].base.ref }} 30 | env: 31 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 32 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | coverage.out 15 | swagger 16 | 17 | # IDE generated files 18 | .idea/ 19 | 20 | # OS generated files 21 | .DS_Store 22 | 23 | docs/build 24 | git log 25 | 26 | docker-compose.log 27 | 28 | .build 29 | 30 | test/bdd/fixtures/keys 31 | 32 | test/bdd/fixtures/data 33 | test/bdd/fixtures/export 34 | 35 | /coverage.txt 36 | /cmd/orb-cli/ipfskeygencmd/k1.key 37 | 38 | test/bdd/website 39 | test/bdd/OrbBDDTestKey.key 40 | /test/bdd/fixtures/mongodbbackup/ 41 | /test/bdd/fixtures/dids.txt 42 | /test/bdd/fixtures/specs/openAPI.yml 43 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trustbloc/orb/b105f1edbf5cef63995c90b9e854b433fc279ff8/Dockerfile -------------------------------------------------------------------------------- /cmd/orb-cli/acceptlistcmd/acceptlist.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package acceptlistcmd 8 | 9 | import ( 10 | "errors" 11 | 12 | "github.com/spf13/cobra" 13 | ) 14 | 15 | const ( 16 | urlFlagName = "url" 17 | urlFlagUsage = "The URL of the accept list REST endpoint." + 18 | " Alternatively, this can be set with the following environment variable: " + urlEnvKey 19 | urlEnvKey = "ORB_CLI_URL" 20 | 21 | actorFlagName = "actor" 22 | actorFlagUsage = "The service URI to add to/remove from the accept list. Multiple URIs may be specified," + 23 | " for example, --actor --actor ." + 24 | " Alternatively, this can be set with the following environment variable as a comma-separated list of URIs: " + 25 | actorEnvKey 26 | actorEnvKey = "ORB_CLI_ACTOR" 27 | 28 | typeFlagName = "type" 29 | typeFlagUsage = "Accept list type (follow or invite-witness)." + 30 | " Alternatively, this can be set with the following environment variable: " + typeEnvKey 31 | typeEnvKey = "ORB_CLI_ACCEPT_TYPE" 32 | ) 33 | 34 | // GetCmd returns the Cobra acceptlist command. 35 | func GetCmd() *cobra.Command { 36 | cmd := &cobra.Command{ 37 | Use: "acceptlist", 38 | Short: "Manages accept lists.", 39 | Long: "Manages accept lists for 'Follow' and 'Invite' witness authorization handlers.", 40 | SilenceUsage: true, 41 | RunE: func(cmd *cobra.Command, args []string) error { 42 | return errors.New("expecting subcommand add, remove, or get") 43 | }, 44 | } 45 | 46 | cmd.AddCommand( 47 | newAddCmd(), 48 | newRemoveCmd(), 49 | newGetCmd(), 50 | ) 51 | 52 | return cmd 53 | } 54 | -------------------------------------------------------------------------------- /cmd/orb-cli/acceptlistcmd/acceptlist_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package acceptlistcmd 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestAcceptListCmd(t *testing.T) { 16 | t.Run("test missing subcommand", func(t *testing.T) { 17 | err := GetCmd().Execute() 18 | require.Error(t, err) 19 | require.Contains(t, err.Error(), "expecting subcommand add, remove, or get") 20 | }) 21 | } 22 | -------------------------------------------------------------------------------- /cmd/orb-cli/acceptlistcmd/getcmd.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package acceptlistcmd 8 | 9 | import ( 10 | "fmt" 11 | "net/http" 12 | "net/url" 13 | 14 | "github.com/spf13/cobra" 15 | 16 | "github.com/trustbloc/orb/cmd/orb-cli/common" 17 | "github.com/trustbloc/orb/internal/pkg/cmdutil" 18 | ) 19 | 20 | func newGetCmd() *cobra.Command { 21 | cmd := &cobra.Command{ 22 | Use: "get", 23 | Short: "Retrieves accept lists.", 24 | Long: "Retrieves accept lists used by the 'Follow' and 'Invite' witness authorization handlers.", 25 | SilenceUsage: true, 26 | RunE: func(cmd *cobra.Command, args []string) error { 27 | return executeGet(cmd) 28 | }, 29 | } 30 | 31 | common.AddCommonFlags(cmd) 32 | 33 | cmd.Flags().StringP(urlFlagName, "", "", urlFlagUsage) 34 | cmd.Flags().StringP(typeFlagName, "", "", typeFlagUsage) 35 | 36 | return cmd 37 | } 38 | 39 | func executeGet(cmd *cobra.Command) error { 40 | u, err := cmdutil.GetUserSetVarFromString(cmd, urlFlagName, urlEnvKey, false) 41 | if err != nil { 42 | return err 43 | } 44 | 45 | _, err = url.Parse(u) 46 | if err != nil { 47 | return fmt.Errorf("invalid URL %s: %w", u, err) 48 | } 49 | 50 | acceptType, err := cmdutil.GetUserSetVarFromString(cmd, typeFlagName, typeEnvKey, true) 51 | if err != nil { 52 | return err 53 | } 54 | 55 | if acceptType != "" { 56 | u = fmt.Sprintf("%s?type=%s", u, acceptType) 57 | } 58 | 59 | resp, err := common.SendHTTPRequest(cmd, nil, http.MethodGet, u) 60 | if err != nil { 61 | return err 62 | } 63 | 64 | fmt.Println(string(resp)) 65 | 66 | return nil 67 | } 68 | -------------------------------------------------------------------------------- /cmd/orb-cli/acceptlistcmd/getcmd_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package acceptlistcmd 8 | 9 | import ( 10 | "fmt" 11 | "net/http" 12 | "net/http/httptest" 13 | "testing" 14 | 15 | "github.com/stretchr/testify/require" 16 | ) 17 | 18 | func TestGetCmd(t *testing.T) { 19 | t.Run("test missing url arg", func(t *testing.T) { 20 | cmd := GetCmd() 21 | cmd.SetArgs([]string{"get"}) 22 | 23 | err := cmd.Execute() 24 | 25 | require.Error(t, err) 26 | require.Equal(t, 27 | "Neither url (command line flag) nor ORB_CLI_URL (environment variable) have been set.", 28 | err.Error()) 29 | }) 30 | 31 | t.Run("test invalid url arg", func(t *testing.T) { 32 | cmd := GetCmd() 33 | 34 | args := []string{"get"} 35 | args = append(args, urlArg(":invalid")...) 36 | cmd.SetArgs(args) 37 | 38 | err := cmd.Execute() 39 | 40 | require.Error(t, err) 41 | require.Contains(t, err.Error(), "invalid URL") 42 | }) 43 | 44 | t.Run("success", func(t *testing.T) { 45 | serv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 46 | _, err := fmt.Fprint(w, "d1") 47 | require.NoError(t, err) 48 | })) 49 | 50 | cmd := GetCmd() 51 | 52 | args := []string{"get"} 53 | args = append(args, urlArg(serv.URL)...) 54 | args = append(args, typeArg("follow")...) 55 | cmd.SetArgs(args) 56 | 57 | cmd.SetArgs(args) 58 | err := cmd.Execute() 59 | 60 | require.NoError(t, err) 61 | }) 62 | } 63 | -------------------------------------------------------------------------------- /cmd/orb-cli/allowedoriginscmd/allowedorigins.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package allowedoriginscmd 8 | 9 | import ( 10 | "errors" 11 | 12 | "github.com/spf13/cobra" 13 | ) 14 | 15 | const ( 16 | urlFlagName = "url" 17 | urlFlagUsage = "The URL of the allowed origins REST endpoint." + 18 | " Alternatively, this can be set with the following environment variable: " + urlEnvKey 19 | urlEnvKey = "ORB_CLI_URL" 20 | 21 | originFlagName = "anchororigin" 22 | originFlagUsage = "The URI to add to/remove from the allowed anchor origins list. Multiple URIs may be specified," + 23 | " for example, --anchororigin --anchororigin ." + 24 | " Alternatively, this can be set with the following environment variable as a comma-separated list of URIs: " + 25 | originsEnvKey 26 | originsEnvKey = "ORB_CLI_ANCHOR_ORIGINS" 27 | ) 28 | 29 | // GetCmd returns the Cobra acceptlist command. 30 | func GetCmd() *cobra.Command { 31 | cmd := &cobra.Command{ 32 | Use: "allowedorigins", 33 | Short: "Manages allowed anchor origins.", 34 | SilenceUsage: true, 35 | RunE: func(cmd *cobra.Command, args []string) error { 36 | return errors.New("expecting subcommand add, remove, or get") 37 | }, 38 | } 39 | 40 | cmd.AddCommand( 41 | newAddCmd(), 42 | newRemoveCmd(), 43 | newGetCmd(), 44 | ) 45 | 46 | return cmd 47 | } 48 | -------------------------------------------------------------------------------- /cmd/orb-cli/allowedoriginscmd/allowedorigins_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package allowedoriginscmd 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestAcceptListCmd(t *testing.T) { 16 | t.Run("test missing subcommand", func(t *testing.T) { 17 | err := GetCmd().Execute() 18 | require.Error(t, err) 19 | require.Contains(t, err.Error(), "expecting subcommand add, remove, or get") 20 | }) 21 | } 22 | -------------------------------------------------------------------------------- /cmd/orb-cli/allowedoriginscmd/getcmd.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package allowedoriginscmd 8 | 9 | import ( 10 | "fmt" 11 | "net/http" 12 | "net/url" 13 | 14 | "github.com/spf13/cobra" 15 | 16 | "github.com/trustbloc/orb/cmd/orb-cli/common" 17 | "github.com/trustbloc/orb/internal/pkg/cmdutil" 18 | ) 19 | 20 | func newGetCmd() *cobra.Command { 21 | cmd := &cobra.Command{ 22 | Use: "get", 23 | Short: "Retrieves allowed anchor origins.", 24 | SilenceUsage: true, 25 | RunE: func(cmd *cobra.Command, args []string) error { 26 | return executeGet(cmd) 27 | }, 28 | } 29 | 30 | common.AddCommonFlags(cmd) 31 | 32 | cmd.Flags().StringP(urlFlagName, "", "", urlFlagUsage) 33 | 34 | return cmd 35 | } 36 | 37 | func executeGet(cmd *cobra.Command) error { 38 | u, err := cmdutil.GetUserSetVarFromString(cmd, urlFlagName, urlEnvKey, false) 39 | if err != nil { 40 | return err 41 | } 42 | 43 | _, err = url.Parse(u) 44 | if err != nil { 45 | return fmt.Errorf("invalid URL %s: %w", u, err) 46 | } 47 | 48 | resp, err := common.SendHTTPRequest(cmd, nil, http.MethodGet, u) 49 | if err != nil { 50 | return err 51 | } 52 | 53 | fmt.Println(string(resp)) 54 | 55 | return nil 56 | } 57 | -------------------------------------------------------------------------------- /cmd/orb-cli/allowedoriginscmd/getcmd_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package allowedoriginscmd 8 | 9 | import ( 10 | "fmt" 11 | "net/http" 12 | "net/http/httptest" 13 | "testing" 14 | 15 | "github.com/stretchr/testify/require" 16 | ) 17 | 18 | func TestGetCmd(t *testing.T) { 19 | t.Run("test missing url arg", func(t *testing.T) { 20 | cmd := GetCmd() 21 | cmd.SetArgs([]string{"get"}) 22 | 23 | err := cmd.Execute() 24 | 25 | require.Error(t, err) 26 | require.Equal(t, 27 | "Neither url (command line flag) nor ORB_CLI_URL (environment variable) have been set.", 28 | err.Error()) 29 | }) 30 | 31 | t.Run("test invalid url arg", func(t *testing.T) { 32 | cmd := GetCmd() 33 | 34 | args := []string{"get"} 35 | args = append(args, urlArg(":invalid")...) 36 | cmd.SetArgs(args) 37 | 38 | err := cmd.Execute() 39 | 40 | require.Error(t, err) 41 | require.Contains(t, err.Error(), "invalid URL") 42 | }) 43 | 44 | t.Run("success", func(t *testing.T) { 45 | serv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 46 | _, err := fmt.Fprint(w, "d1") 47 | require.NoError(t, err) 48 | })) 49 | 50 | cmd := GetCmd() 51 | 52 | args := []string{"get"} 53 | args = append(args, urlArg(serv.URL)...) 54 | cmd.SetArgs(args) 55 | 56 | cmd.SetArgs(args) 57 | err := cmd.Execute() 58 | 59 | require.NoError(t, err) 60 | }) 61 | } 62 | -------------------------------------------------------------------------------- /cmd/orb-cli/logcmd/getcmd.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package logcmd 8 | 9 | import ( 10 | "fmt" 11 | "net/http" 12 | "net/url" 13 | 14 | "github.com/spf13/cobra" 15 | 16 | "github.com/trustbloc/orb/cmd/orb-cli/common" 17 | "github.com/trustbloc/orb/internal/pkg/cmdutil" 18 | ) 19 | 20 | func newGetCmd() *cobra.Command { 21 | cmd := &cobra.Command{ 22 | Use: "get", 23 | Short: "Retrieves the domain log.", 24 | Long: `Retrieves the domain log. For example: log get --url https://orb.domain1.com/log`, 25 | SilenceUsage: true, 26 | RunE: func(cmd *cobra.Command, args []string) error { 27 | return executeGet(cmd) 28 | }, 29 | } 30 | 31 | common.AddCommonFlags(cmd) 32 | 33 | cmd.Flags().StringP(urlFlagName, "", "", urlFlagUsage) 34 | 35 | return cmd 36 | } 37 | 38 | func executeGet(cmd *cobra.Command) error { 39 | u, err := cmdutil.GetUserSetVarFromString(cmd, urlFlagName, urlEnvKey, false) 40 | if err != nil { 41 | return err 42 | } 43 | 44 | _, err = url.Parse(u) 45 | if err != nil { 46 | return fmt.Errorf("invalid URL %s: %w", u, err) 47 | } 48 | 49 | resp, err := common.SendHTTPRequest(cmd, nil, http.MethodGet, u) 50 | if err != nil { 51 | return err 52 | } 53 | 54 | fmt.Println(string(resp)) 55 | 56 | return nil 57 | } 58 | -------------------------------------------------------------------------------- /cmd/orb-cli/logcmd/getcmd_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package logcmd 8 | 9 | import ( 10 | "fmt" 11 | "net/http" 12 | "net/http/httptest" 13 | "testing" 14 | 15 | "github.com/stretchr/testify/require" 16 | ) 17 | 18 | func TestGetCmd(t *testing.T) { 19 | t.Run("test missing url arg", func(t *testing.T) { 20 | cmd := GetCmd() 21 | cmd.SetArgs([]string{"get"}) 22 | 23 | err := cmd.Execute() 24 | 25 | require.Error(t, err) 26 | require.Equal(t, 27 | "Neither url (command line flag) nor ORB_CLI_URL (environment variable) have been set.", 28 | err.Error()) 29 | }) 30 | 31 | t.Run("test invalid url arg", func(t *testing.T) { 32 | cmd := GetCmd() 33 | 34 | args := []string{"get"} 35 | args = append(args, urlArg(":invalid")...) 36 | cmd.SetArgs(args) 37 | 38 | err := cmd.Execute() 39 | 40 | require.Error(t, err) 41 | require.Contains(t, err.Error(), "invalid URL") 42 | }) 43 | 44 | t.Run("success", func(t *testing.T) { 45 | serv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 46 | _, err := fmt.Fprint(w, "d1") 47 | require.NoError(t, err) 48 | })) 49 | 50 | cmd := GetCmd() 51 | 52 | args := []string{"get"} 53 | args = append(args, urlArg(serv.URL)...) 54 | cmd.SetArgs(args) 55 | 56 | cmd.SetArgs(args) 57 | err := cmd.Execute() 58 | 59 | require.NoError(t, err) 60 | }) 61 | } 62 | -------------------------------------------------------------------------------- /cmd/orb-cli/logcmd/log.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package logcmd 8 | 9 | import ( 10 | "errors" 11 | "time" 12 | 13 | "github.com/spf13/cobra" 14 | ) 15 | 16 | const ( 17 | defaultMaxRetry = 10 18 | defaultWaitTime = 1 * time.Second 19 | ) 20 | 21 | const ( 22 | urlFlagName = "url" 23 | urlEnvKey = "ORB_CLI_URL" 24 | urlFlagUsage = "The URL of the log REST endpoint." + 25 | " Alternatively, this can be set with the following environment variable: " + urlEnvKey 26 | 27 | logFlagName = "log" 28 | typeEnvKey = "ORB_CLI_LOG" 29 | logFlagUsage = `The domain log. For example "https://vct.com/log".` + 30 | " Alternatively, this can be set with the following environment variable: " + typeEnvKey 31 | 32 | maxRetryFlagName = "max-retry" 33 | maxRetryEnvKey = "ORB_CLI_MAX_RETRY" 34 | maxRetryFlagUsage = "max retry to check if follow cmd is succeed default value is 10" + 35 | " Alternatively, this can be set with the following environment variable: " + maxRetryEnvKey 36 | 37 | waitTimeFlagName = "wait-time" 38 | waitTimeEnvKey = "ORB_CLI_WAIT_TIME" 39 | waitTimeFlagUsage = "wait time between retries default value is 1s" + 40 | " Alternatively, this can be set with the following environment variable: " + waitTimeEnvKey 41 | ) 42 | 43 | // GetCmd returns the Cobra log command. 44 | func GetCmd() *cobra.Command { 45 | cmd := &cobra.Command{ 46 | Use: "log", 47 | Short: "Manages the domain log.", 48 | SilenceUsage: true, 49 | RunE: func(cmd *cobra.Command, args []string) error { 50 | return errors.New("expecting subcommand update or get") 51 | }, 52 | } 53 | 54 | cmd.AddCommand( 55 | newUpdateCmd(), 56 | newGetCmd(), 57 | ) 58 | 59 | return cmd 60 | } 61 | -------------------------------------------------------------------------------- /cmd/orb-cli/logcmd/log_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package logcmd 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestLogCmd(t *testing.T) { 16 | t.Run("test missing subcommand", func(t *testing.T) { 17 | err := GetCmd().Execute() 18 | require.Error(t, err) 19 | require.Contains(t, err.Error(), "expecting subcommand update or get") 20 | }) 21 | } 22 | -------------------------------------------------------------------------------- /cmd/orb-cli/logmonitorcmd/getcmd.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package logmonitorcmd 8 | 9 | import ( 10 | "fmt" 11 | "net/http" 12 | "net/url" 13 | 14 | "github.com/spf13/cobra" 15 | 16 | "github.com/trustbloc/orb/cmd/orb-cli/common" 17 | "github.com/trustbloc/orb/internal/pkg/cmdutil" 18 | ) 19 | 20 | func newGetCmd() *cobra.Command { 21 | cmd := &cobra.Command{ 22 | Use: "get", 23 | Short: "Retrieves active/inactive log lists.", 24 | Long: "Retrieves active/inactive log lists.", 25 | SilenceUsage: true, 26 | RunE: func(cmd *cobra.Command, args []string) error { 27 | return executeGet(cmd) 28 | }, 29 | } 30 | 31 | common.AddCommonFlags(cmd) 32 | 33 | cmd.Flags().StringP(urlFlagName, "", "", urlFlagUsage) 34 | cmd.Flags().StringP(statusFlagName, "", "", statusFlagUsage) 35 | 36 | return cmd 37 | } 38 | 39 | func executeGet(cmd *cobra.Command) error { 40 | u, err := cmdutil.GetUserSetVarFromString(cmd, urlFlagName, urlEnvKey, false) 41 | if err != nil { 42 | return err 43 | } 44 | 45 | _, err = url.Parse(u) 46 | if err != nil { 47 | return fmt.Errorf("invalid URL %s: %w", u, err) 48 | } 49 | 50 | status, err := cmdutil.GetUserSetVarFromString(cmd, statusFlagName, statusEnvKey, true) 51 | if err != nil { 52 | return err 53 | } 54 | 55 | if status != "" { 56 | u = fmt.Sprintf("%s?status=%s", u, status) 57 | } 58 | 59 | resp, err := common.SendHTTPRequest(cmd, nil, http.MethodGet, u) 60 | if err != nil { 61 | return err 62 | } 63 | 64 | fmt.Println(string(resp)) 65 | 66 | return nil 67 | } 68 | -------------------------------------------------------------------------------- /cmd/orb-cli/logmonitorcmd/getcmd_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package logmonitorcmd 8 | 9 | import ( 10 | "fmt" 11 | "net/http" 12 | "net/http/httptest" 13 | "testing" 14 | 15 | "github.com/stretchr/testify/require" 16 | ) 17 | 18 | func TestGetCmd(t *testing.T) { 19 | t.Run("test missing url arg", func(t *testing.T) { 20 | cmd := GetCmd() 21 | cmd.SetArgs([]string{"get"}) 22 | 23 | err := cmd.Execute() 24 | 25 | require.Error(t, err) 26 | require.Equal(t, 27 | "Neither url (command line flag) nor ORB_CLI_URL (environment variable) have been set.", 28 | err.Error()) 29 | }) 30 | 31 | t.Run("test invalid url arg", func(t *testing.T) { 32 | cmd := GetCmd() 33 | 34 | args := []string{"get"} 35 | args = append(args, urlArg(":invalid")...) 36 | cmd.SetArgs(args) 37 | 38 | err := cmd.Execute() 39 | 40 | require.Error(t, err) 41 | require.Contains(t, err.Error(), "invalid URL") 42 | }) 43 | 44 | t.Run("success", func(t *testing.T) { 45 | serv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 46 | _, err := fmt.Fprint(w, "d1") 47 | require.NoError(t, err) 48 | })) 49 | 50 | cmd := GetCmd() 51 | 52 | args := []string{"get"} 53 | args = append(args, urlArg(serv.URL)...) 54 | args = append(args, statusArg("active")...) 55 | cmd.SetArgs(args) 56 | 57 | cmd.SetArgs(args) 58 | err := cmd.Execute() 59 | 60 | require.NoError(t, err) 61 | }) 62 | } 63 | -------------------------------------------------------------------------------- /cmd/orb-cli/logmonitorcmd/logmonitor.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package logmonitorcmd 8 | 9 | import ( 10 | "errors" 11 | 12 | "github.com/spf13/cobra" 13 | ) 14 | 15 | const ( 16 | urlFlagName = "url" 17 | urlFlagUsage = "The URL of the log monitor REST endpoint." + 18 | " Alternatively, this can be set with the following environment variable: " + urlEnvKey 19 | urlEnvKey = "ORB_CLI_URL" 20 | 21 | logFlagName = "log" 22 | logsFlagUsage = "A comma-separated list of log URIs to activate/deactivate." + 23 | " Alternatively, this can be set with the following environment variable: " + logsEnvKey 24 | logsEnvKey = "ORB_CLI_LOG" 25 | 26 | statusFlagName = "status" 27 | statusFlagUsage = "Filter by log status for log monitor active/inactive list." + 28 | " Alternatively, this can be set with the following environment variable: " + statusEnvKey 29 | statusEnvKey = "ORB_CLI_STATUS" 30 | ) 31 | 32 | // GetCmd returns the Cobra logmonitor command. 33 | func GetCmd() *cobra.Command { 34 | cmd := &cobra.Command{ 35 | Use: "logmonitor", 36 | Short: "Manages activating/deactivating logs for monitoring.", 37 | Long: "Manages activating/deactivating logs for monitoring.", 38 | SilenceUsage: true, 39 | RunE: func(cmd *cobra.Command, args []string) error { 40 | return errors.New("expecting subcommand activate, deactivate, or get") 41 | }, 42 | } 43 | 44 | cmd.AddCommand( 45 | newActivateCmd(), 46 | newDeactivateCmd(), 47 | newGetCmd(), 48 | ) 49 | 50 | return cmd 51 | } 52 | -------------------------------------------------------------------------------- /cmd/orb-cli/logmonitorcmd/logmonitor_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package logmonitorcmd 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestLogMonitorCmd(t *testing.T) { 16 | t.Run("test missing subcommand", func(t *testing.T) { 17 | err := GetCmd().Execute() 18 | require.Error(t, err) 19 | require.Contains(t, err.Error(), "expecting subcommand activate, deactivate, or get") 20 | }) 21 | } 22 | -------------------------------------------------------------------------------- /cmd/orb-cli/main_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package main 7 | 8 | import ( 9 | "os" 10 | "testing" 11 | ) 12 | 13 | // Correct behavior is for main to finish with exit code 0. 14 | // This test fails otherwise. However, this can't be checked by the unit test framework. The *testing.T argument is 15 | // only there so that this test gets picked up by the framework but otherwise we don't need it. 16 | func TestWithoutUserAgs(_ *testing.T) { 17 | setUpArgs() 18 | main() 19 | } 20 | 21 | // Strips out the extra args that the unit test framework adds. 22 | // This allows main() to execute as if it was called directly from the command line. 23 | func setUpArgs() { 24 | os.Args = os.Args[:1] 25 | } 26 | -------------------------------------------------------------------------------- /cmd/orb-cli/policycmd/getcmd.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package policycmd 8 | 9 | import ( 10 | "fmt" 11 | "net/http" 12 | "net/url" 13 | 14 | "github.com/spf13/cobra" 15 | 16 | "github.com/trustbloc/orb/cmd/orb-cli/common" 17 | "github.com/trustbloc/orb/internal/pkg/cmdutil" 18 | ) 19 | 20 | func newGetCmd() *cobra.Command { 21 | cmd := &cobra.Command{ 22 | Use: "get", 23 | Short: "Retrieves the witness policy.", 24 | Long: `Retrieves the witness policy. For example: policy get --url https://orb.domain1.com/policy`, 25 | SilenceUsage: true, 26 | RunE: func(cmd *cobra.Command, args []string) error { 27 | return executeGet(cmd) 28 | }, 29 | } 30 | 31 | common.AddCommonFlags(cmd) 32 | 33 | cmd.Flags().StringP(urlFlagName, "", "", urlFlagUsage) 34 | 35 | return cmd 36 | } 37 | 38 | func executeGet(cmd *cobra.Command) error { 39 | u, err := cmdutil.GetUserSetVarFromString(cmd, urlFlagName, urlEnvKey, false) 40 | if err != nil { 41 | return err 42 | } 43 | 44 | _, err = url.Parse(u) 45 | if err != nil { 46 | return fmt.Errorf("invalid URL %s: %w", u, err) 47 | } 48 | 49 | resp, err := common.SendHTTPRequest(cmd, nil, http.MethodGet, u) 50 | if err != nil { 51 | return err 52 | } 53 | 54 | fmt.Println(string(resp)) 55 | 56 | return nil 57 | } 58 | -------------------------------------------------------------------------------- /cmd/orb-cli/policycmd/getcmd_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package policycmd 8 | 9 | import ( 10 | "fmt" 11 | "net/http" 12 | "net/http/httptest" 13 | "testing" 14 | 15 | "github.com/stretchr/testify/require" 16 | ) 17 | 18 | func TestGetCmd(t *testing.T) { 19 | t.Run("test missing url arg", func(t *testing.T) { 20 | cmd := GetCmd() 21 | cmd.SetArgs([]string{"get"}) 22 | 23 | err := cmd.Execute() 24 | 25 | require.Error(t, err) 26 | require.Equal(t, 27 | "Neither url (command line flag) nor ORB_CLI_URL (environment variable) have been set.", 28 | err.Error()) 29 | }) 30 | 31 | t.Run("test invalid url arg", func(t *testing.T) { 32 | cmd := GetCmd() 33 | 34 | args := []string{"get"} 35 | args = append(args, urlArg(":invalid")...) 36 | cmd.SetArgs(args) 37 | 38 | err := cmd.Execute() 39 | 40 | require.Error(t, err) 41 | require.Contains(t, err.Error(), "invalid URL") 42 | }) 43 | 44 | t.Run("success", func(t *testing.T) { 45 | serv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 46 | _, err := fmt.Fprint(w, "d1") 47 | require.NoError(t, err) 48 | })) 49 | 50 | cmd := GetCmd() 51 | 52 | args := []string{"get"} 53 | args = append(args, urlArg(serv.URL)...) 54 | cmd.SetArgs(args) 55 | 56 | cmd.SetArgs(args) 57 | err := cmd.Execute() 58 | 59 | require.NoError(t, err) 60 | }) 61 | } 62 | -------------------------------------------------------------------------------- /cmd/orb-cli/policycmd/policy.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package policycmd 8 | 9 | import ( 10 | "errors" 11 | 12 | "github.com/spf13/cobra" 13 | ) 14 | 15 | const ( 16 | urlFlagName = "url" 17 | urlEnvKey = "ORB_CLI_URL" 18 | urlFlagUsage = "The URL of the witness policy REST endpoint." + 19 | " Alternatively, this can be set with the following environment variable: " + urlEnvKey 20 | 21 | policyFlagName = "policy" 22 | policyEnvKey = "ORB_CLI_POLICY" 23 | policyFlagUsage = `The witness policy. For example "MinPercent(100,batch) AND OutOf(1,system)".` + 24 | " Alternatively, this can be set with the following environment variable: " + policyEnvKey 25 | ) 26 | 27 | // GetCmd returns the Cobra policy command. 28 | func GetCmd() *cobra.Command { 29 | cmd := &cobra.Command{ 30 | Use: "policy", 31 | Short: "Manages the witness policy.", 32 | SilenceUsage: true, 33 | RunE: func(cmd *cobra.Command, args []string) error { 34 | return errors.New("expecting subcommand update or get") 35 | }, 36 | } 37 | 38 | cmd.AddCommand( 39 | newUpdateCmd(), 40 | newGetCmd(), 41 | ) 42 | 43 | return cmd 44 | } 45 | -------------------------------------------------------------------------------- /cmd/orb-cli/policycmd/policy_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package policycmd 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestPolicyCmd(t *testing.T) { 16 | t.Run("test missing subcommand", func(t *testing.T) { 17 | err := GetCmd().Execute() 18 | require.Error(t, err) 19 | require.Contains(t, err.Error(), "expecting subcommand update or get") 20 | }) 21 | } 22 | -------------------------------------------------------------------------------- /cmd/orb-cli/policycmd/updatecmd.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package policycmd 8 | 9 | import ( 10 | "fmt" 11 | "net/http" 12 | "net/url" 13 | 14 | "github.com/spf13/cobra" 15 | 16 | "github.com/trustbloc/orb/cmd/orb-cli/common" 17 | "github.com/trustbloc/orb/internal/pkg/cmdutil" 18 | ) 19 | 20 | func newUpdateCmd() *cobra.Command { 21 | cmd := &cobra.Command{ 22 | Use: "update", 23 | Short: "Updates the witness policy.", 24 | Long: `Updates the witness policy. For example: policy update ` + 25 | `--policy "MinPercent(100,batch) AND OutOf(1,system)" --url https://orb.domain1.com/policy`, 26 | SilenceUsage: true, 27 | RunE: func(cmd *cobra.Command, args []string) error { 28 | return executeUpdate(cmd) 29 | }, 30 | } 31 | 32 | addUpdateFlags(cmd) 33 | 34 | return cmd 35 | } 36 | 37 | func executeUpdate(cmd *cobra.Command) error { 38 | u, policy, err := getUpdateArgs(cmd) 39 | if err != nil { 40 | return err 41 | } 42 | 43 | _, err = common.SendHTTPRequest(cmd, []byte(policy), http.MethodPost, u) 44 | if err != nil { 45 | return err 46 | } 47 | 48 | fmt.Println("Witness policy has successfully been updated.") 49 | 50 | return nil 51 | } 52 | 53 | func addUpdateFlags(cmd *cobra.Command) { 54 | common.AddCommonFlags(cmd) 55 | 56 | cmd.Flags().StringP(urlFlagName, "", "", urlFlagUsage) 57 | cmd.Flags().StringP(policyFlagName, "", "", policyFlagUsage) 58 | } 59 | 60 | func getUpdateArgs(cmd *cobra.Command) (u, policy string, err error) { 61 | u, err = cmdutil.GetUserSetVarFromString(cmd, urlFlagName, urlEnvKey, false) 62 | if err != nil { 63 | return "", "", err 64 | } 65 | 66 | _, err = url.Parse(u) 67 | if err != nil { 68 | return "", "", fmt.Errorf("invalid URL %s: %w", u, err) 69 | } 70 | 71 | policy, err = cmdutil.GetUserSetVarFromString(cmd, policyFlagName, policyEnvKey, false) 72 | if err != nil { 73 | return "", "", err 74 | } 75 | 76 | return u, policy, nil 77 | } 78 | -------------------------------------------------------------------------------- /cmd/orb-cli/vctcmd/vct.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package vctcmd 8 | 9 | import ( 10 | "errors" 11 | 12 | "github.com/spf13/cobra" 13 | ) 14 | 15 | const ( 16 | casURLFlagName = "cas-url" 17 | casURLEnvKey = "ORB_CAS_URL" 18 | casURLFlagUsage = "The URL of the CAS endpoint." + 19 | " Alternatively, this can be set with the following environment variable: " + casURLEnvKey 20 | 21 | anchorHashFlagName = "anchor" 22 | anchorHashEnvKey = "ORB_CLI_ANCHOR" 23 | anchorHashFlagUsage = `The hash of the anchor linkset.` + 24 | " Alternatively, this can be set with the following environment variable: " + anchorHashEnvKey 25 | 26 | verboseFlagName = "verbose" 27 | verboseEnvKey = "ORB_CLI_VERBOSE" 28 | verboseFlagUsage = `Sets verbose mode, i.e. additional information is output..` + 29 | " Alternatively, this can be set with the following environment variable: " + verboseEnvKey 30 | 31 | vctAuthTokenFlagName = "vct-auth-token" //nolint:gosec 32 | vctAuthTokenFlagUsage = "VCT auth token." + 33 | " Alternatively, this can be set with the following environment variable: " + vctAuthTokenEnvKey 34 | vctAuthTokenEnvKey = "ORB_CLI_VCT_AUTH_TOKEN" //nolint:gosec 35 | ) 36 | 37 | // GetCmd returns the Cobra policy command. 38 | func GetCmd() *cobra.Command { 39 | cmd := &cobra.Command{ 40 | Use: "vct", 41 | Short: "Examines the VCT log.", 42 | SilenceUsage: true, 43 | RunE: func(cmd *cobra.Command, args []string) error { 44 | return errors.New("expecting subcommand: verify") 45 | }, 46 | } 47 | 48 | cmd.AddCommand( 49 | newVerifyCmd(&clientProvider{}), 50 | ) 51 | 52 | return cmd 53 | } 54 | -------------------------------------------------------------------------------- /cmd/orb-cli/vctcmd/vct_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package vctcmd 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestVCTCmd(t *testing.T) { 16 | t.Run("test missing subcommand", func(t *testing.T) { 17 | err := GetCmd().Execute() 18 | require.Error(t, err) 19 | require.Contains(t, err.Error(), "expecting subcommand: verify") 20 | }) 21 | } 22 | -------------------------------------------------------------------------------- /cmd/orb-driver/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package main 7 | 8 | import ( 9 | "log" 10 | 11 | "github.com/spf13/cobra" 12 | 13 | "github.com/trustbloc/orb/cmd/orb-driver/startcmd" 14 | ) 15 | 16 | func main() { 17 | rootCmd := &cobra.Command{ 18 | Use: "orb driver", 19 | Run: func(cmd *cobra.Command, args []string) { 20 | cmd.HelpFunc()(cmd, args) 21 | }, 22 | } 23 | 24 | rootCmd.AddCommand(startcmd.GetStartCmd()) 25 | 26 | if err := rootCmd.Execute(); err != nil { 27 | log.Fatalf("Failed to run rp: %s", err.Error()) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /cmd/orb-driver/main_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package main 7 | 8 | import ( 9 | "os" 10 | "testing" 11 | ) 12 | 13 | // Correct behavior is for main to finish with exit code 0. 14 | // This test fails otherwise. However, this can't be checked by the unit test framework. The *testing.T argument is 15 | // only there so that this test gets picked up by the framework but otherwise we don't need it. 16 | func TestWithoutUserAgs(_ *testing.T) { 17 | setUpArgs() 18 | main() 19 | } 20 | 21 | // Strips out the extra args that the unit test framework adds. 22 | // This allows main() to execute as if it was called directly from the command line. 23 | func setUpArgs() { 24 | os.Args = os.Args[:1] 25 | } 26 | -------------------------------------------------------------------------------- /cmd/orb-server/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | // Package main Orb. 8 | // 9 | // Terms Of Service: 10 | // 11 | // Schemes: http 12 | // Version: 1.0 13 | // License: SPDX-License-Identifier: Apache-2.0 14 | // 15 | // swagger:meta 16 | package main 17 | 18 | import ( 19 | "github.com/spf13/cobra" 20 | "github.com/trustbloc/logutil-go/pkg/log" 21 | 22 | "github.com/trustbloc/orb/cmd/orb-server/startcmd" 23 | ) 24 | 25 | var logger = log.New("orb-server") 26 | 27 | func main() { 28 | rootCmd := &cobra.Command{ 29 | Use: "orb-server", 30 | Run: func(cmd *cobra.Command, args []string) { 31 | cmd.HelpFunc()(cmd, args) 32 | }, 33 | } 34 | 35 | rootCmd.AddCommand(startcmd.GetStartCmd()) 36 | 37 | if err := rootCmd.Execute(); err != nil { 38 | logger.Fatal("Failed to run Orb server.", log.WithError(err)) 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /cmd/orb-server/main_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package main 7 | 8 | import ( 9 | "os" 10 | "testing" 11 | ) 12 | 13 | // Correct behaviour is for main to finish with exit code 0. 14 | // This test fails otherwise. However, this can't be checked by the unit test framework. The *testing.T argument is 15 | // only there so that this test gets picked up by the framework but otherwise we don't need it. 16 | func TestWithoutUserAgs(_ *testing.T) { 17 | setUpArgs() 18 | main() 19 | } 20 | 21 | // Strips out the extra args that the unit test framework adds 22 | // This allows main() to execute as if it was called directly from the command line 23 | func setUpArgs() { 24 | os.Args = os.Args[:1] 25 | } 26 | -------------------------------------------------------------------------------- /cmd/orb-server/startcmd/log.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package startcmd 8 | 9 | import ( 10 | "github.com/trustbloc/logutil-go/pkg/log" 11 | 12 | logfields "github.com/trustbloc/orb/internal/pkg/log" 13 | ) 14 | 15 | const ( 16 | // LogLevelFlagName is the flag name used for setting the default log level. 17 | LogLevelFlagName = "log-level" 18 | // LogLevelEnvKey is the env var name used for setting the default log level. 19 | LogLevelEnvKey = "LOG_LEVEL" 20 | // LogLevelFlagShorthand is the shorthand flag name used for setting the default log level. 21 | LogLevelFlagShorthand = "l" 22 | // LogLevelPrefixFlagUsage is the usage text for the log level flag. 23 | LogLevelPrefixFlagUsage = "Sets logging levels for individual modules as well as the default level. `+" + 24 | "`The format of the string is as follows: module1=level1:module2=level2:defaultLevel. `+" + 25 | "`Supported levels are: CRITICAL, ERROR, WARNING, INFO, DEBUG." + 26 | "`Example: metrics=INFO:nodeinfo=WARNING:activitypub_store=INFO:DEBUG. `+" + 27 | `Defaults to info if not set. Setting to debug may adversely impact performance. Alternatively, this can be ` + 28 | "set with the following environment variable: " + LogLevelEnvKey 29 | ) 30 | 31 | const ( 32 | logSpecErrorMsg = `Invalid log spec. It needs to be in the following format: "ModuleName1=Level1` + 33 | `:ModuleName2=Level2:ModuleNameN=LevelN:AllOtherModuleDefaultLevel" 34 | Valid log levels: critical,error,warn,info,debug 35 | Error: %s` 36 | ) 37 | 38 | // setLogLevels sets the log levels for individual modules as well as the default level. 39 | func setLogLevels(logger *log.Log, logSpec string) { 40 | if err := log.SetSpec(logSpec); err != nil { 41 | logger.Warn(logSpecErrorMsg, log.WithError(err)) 42 | 43 | log.SetDefaultLevel(log.INFO) 44 | } else { 45 | logger.Info("Successfully set log levels", logfields.WithLogSpec(log.GetSpec())) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /cmd/orb-server/startcmd/log_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package startcmd 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | "github.com/trustbloc/logutil-go/pkg/log" 14 | ) 15 | 16 | const testLogModuleName = "test" 17 | 18 | var testLogger = log.New(testLogModuleName) 19 | 20 | func TestSetLogLevel(t *testing.T) { 21 | t.Run("Success", func(t *testing.T) { 22 | defer resetLoggingLevels() 23 | 24 | setLogLevels(testLogger, "debug") 25 | 26 | require.Equal(t, log.DEBUG, log.GetLevel("")) 27 | }) 28 | 29 | t.Run("Log spec -> Success", func(t *testing.T) { 30 | defer resetLoggingLevels() 31 | 32 | setLogLevels(testLogger, "module1=debug:module2=error:warning") 33 | 34 | require.Equal(t, log.WARNING, log.GetLevel("")) 35 | require.Equal(t, log.DEBUG, log.GetLevel("module1")) 36 | require.Equal(t, log.ERROR, log.GetLevel("module2")) 37 | }) 38 | 39 | t.Run("Invalid log level", func(t *testing.T) { 40 | defer resetLoggingLevels() 41 | 42 | setLogLevels(testLogger, "mango") 43 | 44 | // Should remain unchanged 45 | require.Equal(t, log.INFO, log.GetLevel("")) 46 | }) 47 | } 48 | 49 | func resetLoggingLevels() { 50 | log.SetDefaultLevel(log.INFO) 51 | log.SetLevel("module1", log.INFO) 52 | log.SetLevel("module2", log.INFO) 53 | log.SetLevel("module3", log.INFO) 54 | } 55 | -------------------------------------------------------------------------------- /images/orb-driver/Dockerfile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | 7 | ARG GO_VER 8 | ARG ALPINE_VER 9 | ARG BUILDPLATFORM 10 | 11 | FROM --platform=${BUILDPLATFORM:-linux/amd64} golang:${GO_VER}-alpine${ALPINE_VER} as builder 12 | 13 | RUN apk update && apk add git && apk add ca-certificates 14 | RUN apk add --no-cache \ 15 | gcc \ 16 | musl-dev \ 17 | git \ 18 | libtool \ 19 | bash \ 20 | make; 21 | 22 | RUN adduser -D -g '' appuser 23 | COPY . $GOPATH/src/github.com/trustbloc/orb/ 24 | WORKDIR $GOPATH/src/github.com/trustbloc/orb/ 25 | 26 | ARG TARGETOS 27 | ARG TARGETARCH 28 | ARG GO_TAGS 29 | ARG GOPROXY 30 | 31 | RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} GO_TAGS=${GO_TAGS} GOPROXY=${GOPROXY} make orb-driver 32 | 33 | FROM scratch 34 | 35 | LABEL org.opencontainers.image.source https://github.com/trustbloc/orb 36 | 37 | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 38 | COPY --from=builder /etc/passwd /etc/passwd 39 | COPY --from=builder /go/src/github.com/trustbloc/orb/.build/bin/orb-driver /usr/bin/orb-driver 40 | USER appuser 41 | 42 | ENTRYPOINT ["/usr/bin/orb-driver"] 43 | -------------------------------------------------------------------------------- /images/orb-test/Dockerfile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | 7 | ARG GO_VER 8 | ARG ALPINE_VER 9 | ARG BUILDPLATFORM 10 | 11 | FROM --platform=${BUILDPLATFORM:-linux/amd64} golang:${GO_VER}-alpine${ALPINE_VER} as builder 12 | 13 | RUN apk update && apk add git && apk add ca-certificates 14 | RUN apk add --no-cache \ 15 | gcc \ 16 | musl-dev \ 17 | git \ 18 | libtool \ 19 | bash \ 20 | make; 21 | 22 | RUN adduser -D -g '' appuser 23 | COPY . $GOPATH/src/github.com/trustbloc/orb/ 24 | WORKDIR $GOPATH/src/github.com/trustbloc/orb/ 25 | 26 | ARG TARGETOS 27 | ARG TARGETARCH 28 | ARG GO_TAGS 29 | ARG GO_LDFLAGS 30 | ARG GOPROXY 31 | 32 | RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} GO_TAGS=testver GO_LDFLAGS=${GO_LDFLAGS} GOPROXY=${GOPROXY} make orb-test 33 | 34 | FROM scratch 35 | 36 | LABEL org.opencontainers.image.source https://github.com/trustbloc/orb-test 37 | 38 | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 39 | COPY --from=builder /etc/passwd /etc/passwd 40 | COPY --from=builder /go/src/github.com/trustbloc/orb/.build/bin/orb-test /usr/bin/orb 41 | USER appuser 42 | 43 | ENTRYPOINT ["/usr/bin/orb"] 44 | -------------------------------------------------------------------------------- /images/orb/Dockerfile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | 7 | ARG GO_VER 8 | ARG ALPINE_VER 9 | ARG BUILDPLATFORM 10 | 11 | FROM --platform=${BUILDPLATFORM:-linux/amd64} golang:${GO_VER}-alpine${ALPINE_VER} as builder 12 | 13 | RUN apk update && apk add git && apk add ca-certificates 14 | RUN apk add --no-cache \ 15 | gcc \ 16 | musl-dev \ 17 | git \ 18 | libtool \ 19 | bash \ 20 | make; 21 | 22 | RUN adduser -D -g '' appuser 23 | COPY . $GOPATH/src/github.com/trustbloc/orb/ 24 | WORKDIR $GOPATH/src/github.com/trustbloc/orb/ 25 | 26 | ARG TARGETOS 27 | ARG TARGETARCH 28 | ARG GO_TAGS 29 | ARG GO_LDFLAGS 30 | ARG GOPROXY 31 | 32 | RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} GO_TAGS=${GO_TAGS} GO_LDFLAGS=${GO_LDFLAGS} GOPROXY=${GOPROXY} make orb 33 | 34 | FROM scratch 35 | 36 | LABEL org.opencontainers.image.source https://github.com/trustbloc/orb 37 | 38 | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 39 | COPY --from=builder /etc/passwd /etc/passwd 40 | COPY --from=builder /go/src/github.com/trustbloc/orb/.build/bin/orb /usr/bin/orb 41 | USER appuser 42 | 43 | ENTRYPOINT ["/usr/bin/orb"] 44 | -------------------------------------------------------------------------------- /internal/pkg/ldcontext/ldcontext.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package ldcontext 8 | 9 | import ( 10 | "embed" 11 | "encoding/json" 12 | "os" 13 | "sync" 14 | 15 | "github.com/hyperledger/aries-framework-go/pkg/doc/ldcontext" 16 | ) 17 | 18 | const payloadDir = "payload" 19 | 20 | var ( 21 | //go:embed payload/*.json 22 | fs embed.FS 23 | 24 | contexts []ldcontext.Document 25 | once sync.Once 26 | errOnce error 27 | ) 28 | 29 | // GetAll returns all predefined contexts. 30 | func GetAll() ([]ldcontext.Document, error) { 31 | once.Do(func() { 32 | var entries []os.DirEntry 33 | 34 | entries, errOnce = fs.ReadDir(payloadDir) 35 | if errOnce != nil { 36 | return 37 | } 38 | 39 | for _, entry := range entries { 40 | var file os.FileInfo 41 | file, errOnce = entry.Info() 42 | if errOnce != nil { 43 | return 44 | } 45 | 46 | var content []byte 47 | // Do not use os.PathSeparator here, we are using go:embed to load files. 48 | // The path separator is a forward slash, even on Windows systems. 49 | content, errOnce = fs.ReadFile(payloadDir + "/" + file.Name()) 50 | if errOnce != nil { 51 | return 52 | } 53 | 54 | var doc ldcontext.Document 55 | 56 | errOnce = json.Unmarshal(content, &doc) 57 | if errOnce != nil { 58 | return 59 | } 60 | 61 | contexts = append(contexts, doc) 62 | } 63 | }) 64 | 65 | return append(contexts[:0:0], contexts...), errOnce 66 | } 67 | 68 | // MustGetAll returns all predefined contexts. 69 | func MustGetAll() []ldcontext.Document { 70 | docs, err := GetAll() 71 | if err != nil { 72 | panic(err) 73 | } 74 | 75 | return docs 76 | } 77 | -------------------------------------------------------------------------------- /internal/pkg/ldcontext/ldcontext_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package ldcontext_test 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | 14 | "github.com/trustbloc/orb/internal/pkg/ldcontext" 15 | ) 16 | 17 | func TestMustGetAll(t *testing.T) { 18 | res := ldcontext.MustGetAll() 19 | require.Len(t, res, 2) 20 | require.Equal(t, "https://w3id.org/activityanchors/v1", res[0].URL) 21 | require.Equal(t, "https://www.w3.org/ns/activitystreams", res[1].URL) 22 | } 23 | -------------------------------------------------------------------------------- /internal/pkg/ldcontext/payload/activity-anchors-v1.json: -------------------------------------------------------------------------------- 1 | { 2 | "url": "https://w3id.org/activityanchors/v1", 3 | "content": { 4 | "@context": { 5 | "@version": 1.1, 6 | "@protected": true, 7 | "AnchorEvent": { 8 | "@id": "https://w3id.org/activityanchors#AnchorEvent", 9 | "@context": { 10 | "@version": 1.1, 11 | "@protected": true, 12 | "id": "@id", 13 | "type": "@type" 14 | } 15 | }, 16 | "AnchorReceipt": { 17 | "@id": "https://w3id.org/activityanchors#AnchorReceipt", 18 | "@context": { 19 | "@version": 1.1, 20 | "@protected": true, 21 | "id": "@id", 22 | "type": "@type" 23 | } 24 | }, 25 | "AnchorCredential": { 26 | "@id": "https://w3id.org/activityanchors#AnchorCredential", 27 | "@context": { 28 | "@version": 1.1, 29 | "@protected": true, 30 | "id": "@id", 31 | "type": "@type" 32 | } 33 | }, 34 | "AnchorLink": { 35 | "@id": "https://w3id.org/activityanchors#AnchorLink", 36 | "@context": { 37 | "@version": 1.1, 38 | "@protected": true, 39 | "type": "@type", 40 | "href": "https://w3id.org/activityanchors#href", 41 | "anchor": "https://w3id.org/activityanchors#anchor", 42 | "profile": "https://w3id.org/activityanchors#profile", 43 | "rel": "https://w3id.org/activityanchors#rel" 44 | } 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /internal/pkg/log/common.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package log 8 | 9 | import ( 10 | "github.com/trustbloc/logutil-go/pkg/log" 11 | "go.uber.org/zap" 12 | ) 13 | 14 | // InvalidParameterValue outputs an 'invalid parameter' log to the given logger. 15 | func InvalidParameterValue(l *log.Log, param string, err error) { 16 | l.WithOptions(zap.AddCallerSkip(1)).Error("Invalid parameter value", WithParameter(param), log.WithError(err)) 17 | } 18 | 19 | // CloseIteratorError outputs a 'close iterator' error log to the given logger. 20 | func CloseIteratorError(l *log.Log, err error) { 21 | l.WithOptions(zap.AddCallerSkip(1)).Warn("Error closing iterator", log.WithError(err)) 22 | } 23 | 24 | // CloseResponseBodyError outputs a 'close response body' error log to the given logger. 25 | func CloseResponseBodyError(l *log.Log, err error) { 26 | l.WithOptions(zap.AddCallerSkip(1)).Warn("Error closing response body", log.WithError(err)) 27 | } 28 | 29 | // ReadRequestBodyError outputs a 'read response body' error log to the given logger. 30 | func ReadRequestBodyError(l *log.Log, err error) { 31 | l.WithOptions(zap.AddCallerSkip(1)).Error("Error reading request body", log.WithError(err)) 32 | } 33 | 34 | // WriteResponseBodyError outputs a 'write response body' error log to the given logger. 35 | func WriteResponseBodyError(l *log.Log, err error) { 36 | l.WithOptions(zap.AddCallerSkip(1)).Error("Error writing response body", log.WithError(err)) 37 | } 38 | 39 | // WroteResponse outputs a 'wrote response' log to the given logger. 40 | func WroteResponse(l *log.Log, data []byte) { 41 | l.WithOptions(zap.AddCallerSkip(1)).Debug("Wrote response", log.WithResponse(data)) 42 | } 43 | -------------------------------------------------------------------------------- /internal/pkg/tlsutil/tlsutil.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package tlsutil 7 | 8 | import ( 9 | "crypto/x509" 10 | "encoding/pem" 11 | "fmt" 12 | "os" 13 | "path" 14 | ) 15 | 16 | // GetCertPool get cert pool. 17 | func GetCertPool(useSystemCertPool bool, tlsCACerts []string) (*x509.CertPool, error) { 18 | certPool, err := NewCertPool(useSystemCertPool) 19 | if err != nil { 20 | return nil, fmt.Errorf("failed to create new cert pool: %w", err) 21 | } 22 | 23 | for _, v := range tlsCACerts { 24 | bytes, errRead := os.ReadFile(path.Clean(v)) 25 | if errRead != nil { 26 | return nil, fmt.Errorf("failed to read cert: %w", errRead) 27 | } 28 | 29 | block, _ := pem.Decode(bytes) 30 | if block == nil { 31 | return nil, fmt.Errorf("failed to decode pem") 32 | } 33 | 34 | cert, errParse := x509.ParseCertificate(block.Bytes) 35 | if errParse != nil { 36 | return nil, fmt.Errorf("failed to parse cert: %w", errParse) 37 | } 38 | 39 | certPool.Add(cert) 40 | } 41 | 42 | return certPool.Get() 43 | } 44 | -------------------------------------------------------------------------------- /pkg/activitypub/client/util.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package client 8 | 9 | import ( 10 | "errors" 11 | "net/url" 12 | 13 | "github.com/trustbloc/orb/pkg/activitypub/vocab" 14 | ) 15 | 16 | // ReadReferences reads the references from the given iterator up to a maximum number 17 | // specified by maxItems. If maxItems <= 0 then all references are read. 18 | func ReadReferences(it ReferenceIterator, maxItems int) ([]*url.URL, error) { 19 | var refs []*url.URL 20 | 21 | for maxItems <= 0 || len(refs) < maxItems { 22 | ref, err := it.Next() 23 | if err != nil { 24 | if errors.Is(err, ErrNotFound) { 25 | break 26 | } 27 | 28 | return nil, err 29 | } 30 | 31 | refs = append(refs, ref) 32 | } 33 | 34 | return refs, nil 35 | } 36 | 37 | // ReadActivities reads the activities from the given iterator up to a maximum number 38 | // specified by maxItems. If maxItems <= 0 then all activities are read. 39 | func ReadActivities(it ActivityIterator, maxItems int) ([]*vocab.ActivityType, error) { 40 | var activities []*vocab.ActivityType 41 | 42 | for maxItems <= 0 || len(activities) < maxItems { 43 | activity, err := it.Next() 44 | if err != nil { 45 | if errors.Is(err, ErrNotFound) { 46 | break 47 | } 48 | 49 | return nil, err 50 | } 51 | 52 | activities = append(activities, activity) 53 | } 54 | 55 | return activities, nil 56 | } 57 | -------------------------------------------------------------------------------- /pkg/activitypub/httpsig/signer_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package httpsig 8 | 9 | import ( 10 | "bytes" 11 | "errors" 12 | "net/http" 13 | "testing" 14 | 15 | mockcrypto "github.com/hyperledger/aries-framework-go/pkg/mock/crypto" 16 | mockkms "github.com/hyperledger/aries-framework-go/pkg/mock/kms" 17 | "github.com/stretchr/testify/require" 18 | ) 19 | 20 | func TestSigner(t *testing.T) { 21 | const keyID = "123456" 22 | 23 | t.Run("GET", func(t *testing.T) { 24 | s := NewSigner(DefaultGetSignerConfig(), &mockcrypto.Crypto{}, &mockkms.KeyManager{}, keyID) 25 | 26 | req, err := http.NewRequest(http.MethodGet, "https://domain1.com", http.NoBody) 27 | require.NoError(t, err) 28 | 29 | require.NoError(t, s.SignRequest("pubKeyID", req)) 30 | 31 | require.NotEmpty(t, req.Header[dateHeader]) 32 | require.NotEmpty(t, req.Header["Signature"]) 33 | }) 34 | 35 | t.Run("POST", func(t *testing.T) { 36 | s := NewSigner(DefaultPostSignerConfig(), &mockcrypto.Crypto{}, &mockkms.KeyManager{}, keyID) 37 | 38 | payload := []byte("payload") 39 | 40 | req, err := http.NewRequest(http.MethodPost, "https://domain1.com", bytes.NewBuffer(payload)) 41 | require.NoError(t, err) 42 | 43 | require.NoError(t, s.SignRequest("pubKeyID", req)) 44 | 45 | require.NotEmpty(t, req.Header[dateHeader]) 46 | require.NotEmpty(t, req.Header["Digest"]) 47 | require.NotEmpty(t, req.Header["Signature"]) 48 | }) 49 | 50 | t.Run("Signer error", func(t *testing.T) { 51 | errExpected := errors.New("injected KMS error") 52 | 53 | s := NewSigner(SignerConfig{}, &mockcrypto.Crypto{}, &mockkms.KeyManager{GetKeyErr: errExpected}, keyID) 54 | 55 | payload := []byte("payload") 56 | 57 | req, err := http.NewRequest(http.MethodPost, "https://domain1.com", bytes.NewBuffer(payload)) 58 | require.NoError(t, err) 59 | 60 | err = s.SignRequest("pubKeyID", req) 61 | require.Error(t, err) 62 | require.Contains(t, err.Error(), err.Error()) 63 | }) 64 | } 65 | -------------------------------------------------------------------------------- /pkg/activitypub/service/activityhandler/acceptlistauthhandler_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package activityhandler 8 | 9 | import ( 10 | "errors" 11 | "net/url" 12 | "testing" 13 | 14 | "github.com/stretchr/testify/require" 15 | 16 | "github.com/trustbloc/orb/pkg/activitypub/service/mocks" 17 | "github.com/trustbloc/orb/pkg/activitypub/vocab" 18 | ) 19 | 20 | //go:generate counterfeiter -o ../mocks/acceptlistmgr.gen.go --fake-name AcceptListMgr . acceptListMgr 21 | 22 | func TestAcceptListAuthHandler_AuthorizeActor(t *testing.T) { 23 | service1 := vocab.MustParseURL("https://domain1.com/services/orb") 24 | 25 | t.Run("Unauthorized", func(t *testing.T) { 26 | mgr := &mocks.AcceptListMgr{} 27 | 28 | h := NewAcceptListAuthHandler(FollowType, mgr) 29 | require.NotNil(t, h) 30 | 31 | actor := vocab.NewService(service1) 32 | 33 | ok, err := h.AuthorizeActor(actor) 34 | require.NoError(t, err) 35 | require.False(t, ok) 36 | }) 37 | 38 | t.Run("Authorized", func(t *testing.T) { 39 | mgr := &mocks.AcceptListMgr{} 40 | 41 | mgr.GetReturns([]*url.URL{service1}, nil) 42 | 43 | h := NewAcceptListAuthHandler(FollowType, mgr) 44 | require.NotNil(t, h) 45 | 46 | actor := vocab.NewService(service1) 47 | 48 | ok, err := h.AuthorizeActor(actor) 49 | require.NoError(t, err) 50 | require.True(t, ok) 51 | }) 52 | 53 | t.Run("Error", func(t *testing.T) { 54 | mgr := &mocks.AcceptListMgr{} 55 | 56 | errExpected := errors.New("injected accept list manager error") 57 | mgr.GetReturns(nil, errExpected) 58 | 59 | h := NewAcceptListAuthHandler(FollowType, mgr) 60 | require.NotNil(t, h) 61 | 62 | actor := vocab.NewService(service1) 63 | 64 | ok, err := h.AuthorizeActor(actor) 65 | require.Error(t, err) 66 | require.Contains(t, err.Error(), errExpected.Error()) 67 | require.False(t, ok) 68 | }) 69 | } 70 | -------------------------------------------------------------------------------- /pkg/activitypub/service/mocks/activities.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | import ( 10 | "github.com/trustbloc/orb/pkg/activitypub/vocab" 11 | ) 12 | 13 | // Activities contains a slice of ActivityType. 14 | type Activities []*vocab.ActivityType 15 | 16 | // QueryByType returns the activities that match the given types. 17 | func (a Activities) QueryByType(types ...vocab.Type) Activities { 18 | var result Activities 19 | 20 | for _, activity := range a { 21 | if activity.Type().Is(types...) { 22 | result = append(result, activity) 23 | } 24 | } 25 | 26 | return result 27 | } 28 | -------------------------------------------------------------------------------- /pkg/activitypub/service/mocks/mockacceptfollowhandler.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | import ( 10 | "net/url" 11 | ) 12 | 13 | // AcceptFollowHandler implements a mock accept follow handler. 14 | type AcceptFollowHandler struct { 15 | err error 16 | } 17 | 18 | // NewAcceptFollowHandler returns a mock accept follow handler. 19 | func NewAcceptFollowHandler() *AcceptFollowHandler { 20 | return &AcceptFollowHandler{} 21 | } 22 | 23 | // WithError injects an error. 24 | func (m *AcceptFollowHandler) WithError(err error) *AcceptFollowHandler { 25 | m.err = err 26 | 27 | return m 28 | } 29 | 30 | // Accept accepts/rejects follow request. 31 | func (m *AcceptFollowHandler) Accept(actor *url.URL) error { 32 | return m.err 33 | } 34 | -------------------------------------------------------------------------------- /pkg/activitypub/service/mocks/mockanchoreventackhandler.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | import ( 10 | "net/url" 11 | "sync" 12 | ) 13 | 14 | // AnchorEventAcknowledgementHandler implements a mock anchor event acknowledgement handler. 15 | type AnchorEventAcknowledgementHandler struct { 16 | mutex sync.Mutex 17 | err error 18 | anchors []*url.URL 19 | } 20 | 21 | // NewAnchorEventAcknowledgementHandler returns a mock handler. 22 | func NewAnchorEventAcknowledgementHandler() *AnchorEventAcknowledgementHandler { 23 | return &AnchorEventAcknowledgementHandler{} 24 | } 25 | 26 | // WithError injects an error. 27 | func (m *AnchorEventAcknowledgementHandler) WithError(err error) *AnchorEventAcknowledgementHandler { 28 | m.err = err 29 | 30 | return m 31 | } 32 | 33 | // AnchorEventAcknowledged handles the acknowledgement of a successful anchor event processed from an Orb server. 34 | func (m *AnchorEventAcknowledgementHandler) AnchorEventAcknowledged(_, anchorRef *url.URL, _ []*url.URL) error { 35 | m.mutex.Lock() 36 | defer m.mutex.Unlock() 37 | 38 | m.anchors = append(m.anchors, anchorRef) 39 | 40 | return m.err 41 | } 42 | 43 | // UndoAnchorEventAcknowledgement undoes the acknowledgement of an anchor event processed from an Orb server. 44 | func (m *AnchorEventAcknowledgementHandler) UndoAnchorEventAcknowledgement(_, anchorRef *url.URL, _ []*url.URL) error { 45 | m.mutex.Lock() 46 | defer m.mutex.Unlock() 47 | 48 | for i, anchor := range m.anchors { 49 | if anchor.String() == anchorRef.String() { 50 | m.anchors = append(m.anchors[0:i], m.anchors[i+1:]...) 51 | } 52 | } 53 | 54 | return m.err 55 | } 56 | 57 | // Anchors returns the anchors that were added to this mock. 58 | func (m *AnchorEventAcknowledgementHandler) Anchors() []*url.URL { 59 | m.mutex.Lock() 60 | defer m.mutex.Unlock() 61 | 62 | return m.anchors 63 | } 64 | -------------------------------------------------------------------------------- /pkg/activitypub/service/mocks/mockanchoreventhandler.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | import ( 10 | "context" 11 | "net/url" 12 | "sync" 13 | 14 | "github.com/trustbloc/orb/pkg/activitypub/vocab" 15 | ) 16 | 17 | // AnchorEventHandler is a mock anchor event handler. 18 | type AnchorEventHandler struct { 19 | mutex sync.Mutex 20 | anchorCreds map[string]*vocab.AnchorEventType 21 | err error 22 | } 23 | 24 | // NewAnchorEventHandler returns a mock anchor event handler. 25 | func NewAnchorEventHandler() *AnchorEventHandler { 26 | return &AnchorEventHandler{ 27 | anchorCreds: make(map[string]*vocab.AnchorEventType), 28 | } 29 | } 30 | 31 | // WithError injects an error into the mock handler. 32 | func (m *AnchorEventHandler) WithError(err error) *AnchorEventHandler { 33 | m.err = err 34 | 35 | return m 36 | } 37 | 38 | // HandleAnchorEvent stores the anchor event or returns an error if it was set. 39 | func (m *AnchorEventHandler) HandleAnchorEvent(ctx context.Context, actor, hl, source *url.URL, anchorEvent *vocab.AnchorEventType) error { 40 | if m.err != nil { 41 | return m.err 42 | } 43 | 44 | m.mutex.Lock() 45 | defer m.mutex.Unlock() 46 | 47 | m.anchorCreds[hl.String()] = anchorEvent 48 | 49 | return nil 50 | } 51 | 52 | // AnchorEvent returns the anchor credential by ID or nil if it doesn't exist. 53 | func (m *AnchorEventHandler) AnchorEvent(hl string) (*vocab.AnchorEventType, bool) { 54 | m.mutex.Lock() 55 | defer m.mutex.Unlock() 56 | 57 | value, ok := m.anchorCreds[hl] 58 | 59 | return value, ok 60 | } 61 | -------------------------------------------------------------------------------- /pkg/activitypub/service/mocks/mockfollowerauth.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | import ( 10 | "github.com/trustbloc/orb/pkg/activitypub/vocab" 11 | ) 12 | 13 | // ActorAuth implements a mock actor authorization handler. 14 | type ActorAuth struct { 15 | accept bool 16 | err error 17 | } 18 | 19 | // NewActorAuth returns a mock actor authorization. 20 | func NewActorAuth() *ActorAuth { 21 | return &ActorAuth{} 22 | } 23 | 24 | // WithAccept ensures that the request is accepted. 25 | func (m *ActorAuth) WithAccept() *ActorAuth { 26 | m.accept = true 27 | 28 | return m 29 | } 30 | 31 | // WithReject ensures that the request is rejected. 32 | func (m *ActorAuth) WithReject() *ActorAuth { 33 | m.accept = false 34 | 35 | return m 36 | } 37 | 38 | // WithError injects an error into the handler. 39 | func (m *ActorAuth) WithError(err error) *ActorAuth { 40 | m.err = err 41 | 42 | return m 43 | } 44 | 45 | // AuthorizeActor is a mock implementation that returns the injected values. 46 | func (m *ActorAuth) AuthorizeActor(follower *vocab.ActorType) (bool, error) { 47 | return m.accept, m.err 48 | } 49 | -------------------------------------------------------------------------------- /pkg/activitypub/service/mocks/mockoutbox.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | import ( 10 | "context" 11 | "net/url" 12 | "sync" 13 | 14 | "github.com/trustbloc/orb/pkg/activitypub/vocab" 15 | "github.com/trustbloc/orb/pkg/lifecycle" 16 | ) 17 | 18 | // Outbox implements a mock Outbox. 19 | type Outbox struct { 20 | mutex sync.RWMutex 21 | activities Activities 22 | err error 23 | activityID *url.URL 24 | } 25 | 26 | // NewOutbox returns a mock outbox. 27 | func NewOutbox() *Outbox { 28 | return &Outbox{} 29 | } 30 | 31 | // WithError injects an error into the mock outbox. 32 | func (m *Outbox) WithError(err error) *Outbox { 33 | m.err = err 34 | 35 | return m 36 | } 37 | 38 | // WithActivityID sets the ID of the posted activity. 39 | func (m *Outbox) WithActivityID(id *url.URL) *Outbox { 40 | m.activityID = id 41 | 42 | return m 43 | } 44 | 45 | // Activities returns the activities that were posted to the outbox. 46 | func (m *Outbox) Activities() Activities { 47 | m.mutex.RLock() 48 | defer m.mutex.RUnlock() 49 | 50 | return m.activities 51 | } 52 | 53 | // Post post an activity to the outbox. The activity is simply stored 54 | // so that it may be retrieved by the Activies function. 55 | func (m *Outbox) Post(ctx context.Context, activity *vocab.ActivityType, exclude ...*url.URL) (*url.URL, error) { 56 | if m.err != nil { 57 | return nil, m.err 58 | } 59 | 60 | m.mutex.Lock() 61 | defer m.mutex.Unlock() 62 | 63 | m.activities = append(m.activities, activity) 64 | 65 | return m.activityID, nil 66 | } 67 | 68 | // Start does nothing. 69 | func (m *Outbox) Start() { 70 | } 71 | 72 | // Stop does nothing. 73 | func (m *Outbox) Stop() { 74 | } 75 | 76 | // State always returns StateStarted. 77 | func (m *Outbox) State() lifecycle.State { 78 | return lifecycle.StateStarted 79 | } 80 | -------------------------------------------------------------------------------- /pkg/activitypub/service/mocks/mockproofhandler.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | import ( 10 | "context" 11 | "net/url" 12 | "sync" 13 | "time" 14 | ) 15 | 16 | // ProofHandler implements a mock proof handler. 17 | type ProofHandler struct { 18 | mutex sync.Mutex 19 | proofs map[string][]byte 20 | err error 21 | } 22 | 23 | // NewProofHandler returns a mock proof handler. 24 | func NewProofHandler() *ProofHandler { 25 | return &ProofHandler{ 26 | proofs: make(map[string][]byte), 27 | } 28 | } 29 | 30 | // WithError injects an error. 31 | func (m *ProofHandler) WithError(err error) *ProofHandler { 32 | m.err = err 33 | 34 | return m 35 | } 36 | 37 | // HandleProof store the proof and returns any injected error. 38 | func (m *ProofHandler) HandleProof(ctx context.Context, witness *url.URL, anchorCredID string, endTime time.Time, proof []byte) error { 39 | m.mutex.Lock() 40 | defer m.mutex.Unlock() 41 | 42 | m.proofs[anchorCredID] = proof 43 | 44 | return m.err 45 | } 46 | 47 | // Proof returns the stored proof for the givin ID. 48 | func (m *ProofHandler) Proof(objID string) []byte { 49 | m.mutex.Lock() 50 | defer m.mutex.Unlock() 51 | 52 | return m.proofs[objID] 53 | } 54 | -------------------------------------------------------------------------------- /pkg/activitypub/service/mocks/mocksubscriber.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | import ( 10 | "sync" 11 | 12 | "github.com/trustbloc/orb/pkg/activitypub/vocab" 13 | ) 14 | 15 | // Subscriber implements a mock activity subscriber. 16 | type Subscriber struct { 17 | activityChan <-chan *vocab.ActivityType 18 | mutex sync.Mutex 19 | activities []*vocab.ActivityType 20 | } 21 | 22 | // NewSubscriber returns a new mock activity subscriber. 23 | func NewSubscriber(activityChan <-chan *vocab.ActivityType) *Subscriber { 24 | s := &Subscriber{ 25 | activityChan: activityChan, 26 | } 27 | 28 | go s.listen() 29 | 30 | return s 31 | } 32 | 33 | // Activities returns the activities that were received by the subscriber. 34 | func (m *Subscriber) Activities() []*vocab.ActivityType { 35 | m.mutex.Lock() 36 | defer m.mutex.Unlock() 37 | 38 | return m.activities 39 | } 40 | 41 | func (m *Subscriber) listen() { 42 | for activity := range m.activityChan { 43 | m.add(activity) 44 | } 45 | } 46 | 47 | func (m *Subscriber) add(activity *vocab.ActivityType) { 48 | m.mutex.Lock() 49 | defer m.mutex.Unlock() 50 | 51 | m.activities = append(m.activities, activity) 52 | } 53 | -------------------------------------------------------------------------------- /pkg/activitypub/service/mocks/mockundofollowhandler.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | import ( 10 | "net/url" 11 | ) 12 | 13 | // UndoFollowHandler implements a mock undo follow handler. 14 | type UndoFollowHandler struct { 15 | err error 16 | } 17 | 18 | // NewUndoFollowHandler returns a mock undo follow handler. 19 | func NewUndoFollowHandler() *UndoFollowHandler { 20 | return &UndoFollowHandler{} 21 | } 22 | 23 | // WithError injects an error. 24 | func (m *UndoFollowHandler) WithError(err error) *UndoFollowHandler { 25 | m.err = err 26 | 27 | return m 28 | } 29 | 30 | // Undo removes follow request. 31 | func (m *UndoFollowHandler) Undo(actor *url.URL) error { 32 | return m.err 33 | } 34 | -------------------------------------------------------------------------------- /pkg/activitypub/service/mocks/mockwitnesshandler.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | import ( 10 | "sync" 11 | ) 12 | 13 | // WitnessHandler implements a mock witness handler. 14 | type WitnessHandler struct { 15 | mutex sync.Mutex 16 | err error 17 | proof []byte 18 | anchorCreds [][]byte 19 | } 20 | 21 | // NewWitnessHandler returns a mock witness handler. 22 | func NewWitnessHandler() *WitnessHandler { 23 | return &WitnessHandler{} 24 | } 25 | 26 | // WithProof sets the proof to be returned from the witness handler. 27 | func (m *WitnessHandler) WithProof(proof []byte) *WitnessHandler { 28 | m.proof = proof 29 | 30 | return m 31 | } 32 | 33 | // WithError injects an error. 34 | func (m *WitnessHandler) WithError(err error) *WitnessHandler { 35 | m.err = err 36 | 37 | return m 38 | } 39 | 40 | // Witness adds the anchor credential to a list that can be inspected using the AnchorCreds function 41 | // and returns the injected proof/error. 42 | func (m *WitnessHandler) Witness(anchorCred []byte) ([]byte, error) { 43 | m.mutex.Lock() 44 | defer m.mutex.Unlock() 45 | 46 | m.anchorCreds = append(m.anchorCreds, anchorCred) 47 | 48 | return m.proof, m.err 49 | } 50 | 51 | // AnchorCreds returns all of the anchor credentials that were witnessed by this mock. 52 | func (m *WitnessHandler) AnchorCreds() [][]byte { 53 | m.mutex.Lock() 54 | defer m.mutex.Unlock() 55 | 56 | return m.anchorCreds 57 | } 58 | -------------------------------------------------------------------------------- /pkg/activitypub/service/mocks/webfingerresolver.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | // WebFingerResolver implements a mock WebFinger resolver. 10 | type WebFingerResolver struct { 11 | Err error 12 | URI string 13 | } 14 | 15 | // ResolveHostMetaLink returns either the specified error, the specified URI, otherwise, if neither were specified 16 | // then the URI in the argument is returned. 17 | func (m *WebFingerResolver) ResolveHostMetaLink(uri, _ string) (string, error) { 18 | if m.Err != nil { 19 | return "", m.Err 20 | } 21 | 22 | if m.URI != "" { 23 | return m.URI, nil 24 | } 25 | 26 | return uri, nil 27 | } 28 | -------------------------------------------------------------------------------- /pkg/activitypub/store/ariesstore/ariesstore_internal_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package ariesstore 7 | 8 | import ( 9 | "errors" 10 | "testing" 11 | 12 | "github.com/hyperledger/aries-framework-go/component/storageutil/mock" 13 | "github.com/stretchr/testify/require" 14 | ) 15 | 16 | func TestIterators_FailureCases(t *testing.T) { 17 | t.Run("Reference iterator", func(t *testing.T) { 18 | iterator := referenceIterator{ariesIterator: &mock.Iterator{ErrNext: errors.New("next error")}} 19 | 20 | activity, err := iterator.Next() 21 | require.EqualError(t, err, "failed to determine if there are more results: next error") 22 | require.Nil(t, activity) 23 | 24 | iterator = referenceIterator{ariesIterator: &mock.Iterator{ 25 | NextReturn: true, ErrValue: errors.New("value error"), 26 | }} 27 | 28 | activity, err = iterator.Next() 29 | require.EqualError(t, err, "failed to get value: value error") 30 | require.Nil(t, activity) 31 | }) 32 | } 33 | -------------------------------------------------------------------------------- /pkg/activitypub/store/spi/spi_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package spi 8 | 9 | import ( 10 | "encoding/json" 11 | "testing" 12 | 13 | "github.com/stretchr/testify/require" 14 | 15 | "github.com/trustbloc/orb/pkg/activitypub/vocab" 16 | "github.com/trustbloc/orb/pkg/internal/testutil" 17 | ) 18 | 19 | func TestCriteria(t *testing.T) { 20 | c := NewCriteria( 21 | WithType(vocab.TypeCreate, vocab.TypeAnnounce), 22 | WithReferenceType(Inbox), 23 | WithReferenceIRI(testutil.MustParseURL("https://example.com/ref")), 24 | WithObjectIRI(testutil.MustParseURL("https://example.com/obj")), 25 | WithActivityIRIs( 26 | testutil.MustParseURL("https://example.com/activity1"), 27 | testutil.MustParseURL("https://example.com/activity2"), 28 | ), 29 | ) 30 | require.NotNil(t, c) 31 | require.Len(t, c.Types, 2) 32 | require.Equal(t, vocab.TypeCreate, c.Types[0]) 33 | require.Equal(t, vocab.TypeAnnounce, c.Types[1]) 34 | 35 | b, err := json.Marshal(c) 36 | require.NoError(t, err) 37 | 38 | t.Logf("%s", b) 39 | } 40 | -------------------------------------------------------------------------------- /pkg/activitypub/vocab/linktype.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package vocab 8 | 9 | import ( 10 | "net/url" 11 | ) 12 | 13 | // LinkType defines the ActivityPub 'Link' type. 14 | type LinkType struct { 15 | link *linkType 16 | } 17 | 18 | type linkType struct { 19 | HRef *URLProperty `json:"href,omitempty"` 20 | Rel []string `json:"rel,omitempty"` 21 | } 22 | 23 | // NewLink creates a new Link type. 24 | func NewLink(hRef *url.URL, rel ...string) *LinkType { 25 | return &LinkType{ 26 | link: &linkType{ 27 | HRef: NewURLProperty(hRef), 28 | Rel: rel, 29 | }, 30 | } 31 | } 32 | 33 | // Type always returns the "Link" type. 34 | func (t *LinkType) Type() *TypeProperty { 35 | return NewTypeProperty(TypeLink) 36 | } 37 | 38 | // HRef return the reference ('href' field). 39 | func (t *LinkType) HRef() *url.URL { 40 | if t == nil || t.link == nil || t.link.HRef == nil { 41 | return nil 42 | } 43 | 44 | return t.link.HRef.URL() 45 | } 46 | 47 | // Rel returns the relationship ('rel' field). 48 | func (t *LinkType) Rel() Relationship { 49 | if t == nil || t.link == nil { 50 | return nil 51 | } 52 | 53 | return t.link.Rel 54 | } 55 | 56 | // MarshalJSON marshals the link type to JSON. 57 | func (t *LinkType) MarshalJSON() ([]byte, error) { 58 | return MarshalJSON(t.link, Document{propertyType: TypeLink}) 59 | } 60 | 61 | // UnmarshalJSON umarshals the link type from JSON. 62 | func (t *LinkType) UnmarshalJSON(bytes []byte) error { 63 | t.link = &linkType{} 64 | 65 | return UnmarshalJSON(bytes, &t.link) 66 | } 67 | 68 | // Relationship holds the relationship of the Link. 69 | type Relationship []string 70 | 71 | // Is return true if the given relationship is contained. 72 | func (r Relationship) Is(relationship string) bool { 73 | for _, rel := range r { 74 | if rel == relationship { 75 | return true 76 | } 77 | } 78 | 79 | return false 80 | } 81 | -------------------------------------------------------------------------------- /pkg/activitypub/vocab/linktype_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package vocab 8 | 9 | import ( 10 | "encoding/json" 11 | "testing" 12 | 13 | "github.com/stretchr/testify/require" 14 | "github.com/trustbloc/sidetree-go/pkg/canonicalizer" 15 | 16 | "github.com/trustbloc/orb/pkg/internal/testutil" 17 | ) 18 | 19 | var href = MustParseURL("hl:uEiDaKXK8DrWLEz-mJk9JCvhVpBg6DUiR-84p8cuG_kLKwg") 20 | 21 | func TestNewLink(t *testing.T) { 22 | t.Run("Nil type", func(t *testing.T) { 23 | var link *LinkType 24 | 25 | require.Nil(t, link.HRef()) 26 | require.True(t, link.Type().Is(TypeLink)) 27 | require.False(t, link.Rel().Is(RelationshipWitness)) 28 | }) 29 | 30 | t.Run("Success", func(t *testing.T) { 31 | link := NewLink(href, RelationshipWitness) 32 | require.NotNil(t, link) 33 | require.True(t, link.Type().Is(TypeLink)) 34 | require.NotNil(t, link.HRef()) 35 | require.Equal(t, href.String(), link.HRef().String()) 36 | require.True(t, link.Rel().Is(RelationshipWitness)) 37 | }) 38 | } 39 | 40 | func TestLinkType_MarshalJSON(t *testing.T) { 41 | link := NewLink(href, RelationshipWitness) 42 | require.NotNil(t, link) 43 | 44 | linkBytes, err := canonicalizer.MarshalCanonical(link) 45 | require.NoError(t, err) 46 | 47 | t.Logf("Link: %s", linkBytes) 48 | 49 | require.Equal(t, testutil.GetCanonical(t, jsonLink), string(linkBytes)) 50 | } 51 | 52 | func TestLinkType_UnmarshalJSON(t *testing.T) { 53 | link := &LinkType{} 54 | 55 | require.NoError(t, json.Unmarshal([]byte(jsonLink), &link)) 56 | require.True(t, link.Type().Is(TypeLink)) 57 | require.NotNil(t, link.HRef()) 58 | require.Equal(t, href.String(), link.HRef().String()) 59 | require.True(t, link.Rel().Is(RelationshipWitness)) 60 | } 61 | 62 | const ( 63 | jsonLink = `{ 64 | "href": "hl:uEiDaKXK8DrWLEz-mJk9JCvhVpBg6DUiR-84p8cuG_kLKwg", 65 | "rel": ["witness"], 66 | "type": "Link" 67 | }` 68 | ) 69 | -------------------------------------------------------------------------------- /pkg/activitypub/vocab/typeproperty_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package vocab 8 | 9 | import ( 10 | "encoding/json" 11 | "testing" 12 | 13 | "github.com/stretchr/testify/require" 14 | ) 15 | 16 | func TestTypeProperty(t *testing.T) { 17 | const ( 18 | jsonType = `"Create"` 19 | jsonMultiType = `["Create","AnchorEvent"]` 20 | ) 21 | 22 | t.Run("Nil type", func(t *testing.T) { 23 | p := NewTypeProperty() 24 | require.Nil(t, p) 25 | require.False(t, p.Is(TypeCreate)) 26 | require.False(t, p.IsAny(TypeCreate)) 27 | require.Empty(t, p.Types()) 28 | require.Equal(t, "", p.String()) 29 | }) 30 | 31 | t.Run("Single type", func(t *testing.T) { 32 | p := NewTypeProperty(TypeCreate) 33 | require.NotNil(t, p) 34 | 35 | types := p.Types() 36 | require.Len(t, types, 1) 37 | require.Equal(t, TypeCreate, types[0]) 38 | 39 | bytes, err := json.Marshal(p) 40 | require.NoError(t, err) 41 | require.Equal(t, jsonType, string(bytes)) 42 | 43 | p2 := &TypeProperty{} 44 | require.NoError(t, json.Unmarshal([]byte(jsonType), p2)) 45 | require.True(t, p2.Is(TypeCreate)) 46 | require.Equal(t, "Create", p2.String()) 47 | }) 48 | 49 | t.Run("Multiple types", func(t *testing.T) { 50 | p := NewTypeProperty(TypeCreate, TypeAnchorEvent) 51 | require.NotNil(t, p) 52 | 53 | types := p.Types() 54 | require.Len(t, types, 2) 55 | require.Equal(t, TypeCreate, types[0]) 56 | require.Equal(t, TypeAnchorEvent, types[1]) 57 | 58 | bytes, err := json.Marshal(p) 59 | require.NoError(t, err) 60 | require.Equal(t, jsonMultiType, string(bytes)) 61 | 62 | p2 := &TypeProperty{} 63 | require.NoError(t, json.Unmarshal([]byte(jsonMultiType), p2)) 64 | require.True(t, p2.Is(TypeCreate)) 65 | require.False(t, p2.Is(TypeCreate, TypeFollow)) 66 | require.Equal(t, "[Create AnchorEvent]", p2.String()) 67 | }) 68 | } 69 | -------------------------------------------------------------------------------- /pkg/activitypub/vocab/vocab_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package vocab 8 | 9 | import ( 10 | "testing" 11 | "time" 12 | 13 | "github.com/stretchr/testify/require" 14 | ) 15 | 16 | func TestDocument_MergeWith(t *testing.T) { 17 | const ( 18 | field1 = "Field1" 19 | field2 = "Field2" 20 | field3 = "Field3" 21 | field4 = "Field4" 22 | ) 23 | 24 | doc1 := Document{ 25 | field1: "Value1", 26 | field3: 3, 27 | } 28 | 29 | doc2 := Document{ 30 | field2: "Value2", 31 | field4: 4, 32 | } 33 | 34 | doc1.MergeWith(doc2) 35 | require.Equal(t, "Value1", doc1[field1]) 36 | require.Equal(t, "Value2", doc1[field2]) 37 | require.Equal(t, 3, doc1[field3]) 38 | require.Equal(t, 4, doc1[field4]) 39 | } 40 | 41 | func TestDocument_Unmarshal(t *testing.T) { 42 | const ( 43 | field1 = "Field1" 44 | field2 = "Field2" 45 | value1 = "Value1" 46 | value2 = 3 47 | ) 48 | 49 | type contentType struct { 50 | Field1 string 51 | Field2 int 52 | } 53 | 54 | doc := Document{ 55 | field1: value1, 56 | field2: value2, 57 | } 58 | 59 | contentObj := &contentType{} 60 | require.NoError(t, doc.Unmarshal(contentObj)) 61 | require.Equal(t, value1, contentObj.Field1) 62 | require.Equal(t, value2, contentObj.Field2) 63 | } 64 | 65 | func TestMustParseURL(t *testing.T) { 66 | t.Run("Success", func(t *testing.T) { 67 | const iri = "https://example.com" 68 | 69 | require.Equal(t, iri, MustParseURL(iri).String()) 70 | }) 71 | 72 | t.Run("Panic", func(t *testing.T) { 73 | require.Panics(t, func() { 74 | MustParseURL(string([]byte{0})) 75 | }) 76 | }) 77 | } 78 | 79 | func getStaticTime() time.Time { 80 | loc, err := time.LoadLocation("UTC") 81 | if err != nil { 82 | panic(err) 83 | } 84 | 85 | return time.Date(2021, time.January, 27, 9, 30, 10, 0, loc) 86 | } 87 | -------------------------------------------------------------------------------- /pkg/anchor/anchorlinkset/generator/samplegenerator/samplegenerator.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package samplegenerator 8 | 9 | import ( 10 | "github.com/trustbloc/orb/pkg/activitypub/vocab" 11 | "github.com/trustbloc/orb/pkg/anchor/anchorlinkset/generator/didorbgenerator" 12 | ) 13 | 14 | const ( 15 | // ID specifies the ID of the generator. 16 | ID = "https://w3id.org/test#v1" 17 | 18 | // Namespace specifies the namespace of the generator. 19 | Namespace = "did:test" 20 | 21 | // Version specifies the version of the generator. 22 | Version = uint64(1) 23 | ) 24 | 25 | // Generator implements a generator used by tests. It also demonstrates how to extend an existing generator 26 | // implementation in order to support future versions. 27 | type Generator struct { 28 | *didorbgenerator.Generator 29 | } 30 | 31 | // New returns a new test generator. 32 | func New() *Generator { 33 | return &Generator{ 34 | Generator: didorbgenerator.New( 35 | didorbgenerator.WithID(vocab.MustParseURL(ID)), 36 | didorbgenerator.WithNamespace(Namespace), 37 | didorbgenerator.WithVersion(Version), 38 | ), 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /pkg/anchor/anchorlinkset/vcresthandler/openapi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package vcresthandler 8 | 9 | // swagger:parameters vcGetReq 10 | type vcGetReq struct { //nolint: unused 11 | // in: path 12 | ID string `json:"id"` 13 | } 14 | 15 | // swagger:response vcGetResp 16 | type vcGetResp struct { //nolint: unused 17 | Body string 18 | } 19 | 20 | // getVC swagger:route GET /vc/{id} VC vcGetReq 21 | // 22 | // Retrieves the current witness vc. 23 | // 24 | // Responses: 25 | // 26 | // 200: vcGetResp 27 | func getVC() { //nolint: unused 28 | } 29 | -------------------------------------------------------------------------------- /pkg/anchor/info/info.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package info 8 | 9 | // AnchorInfo represents a hashlink that can be used to fetch the anchor. 10 | type AnchorInfo struct { 11 | Hashlink string `json:"hashLink"` 12 | LocalHashlink string `json:"localHashLink"` 13 | AttributedTo string `json:"attributedTo,omitempty"` 14 | AlternateSources []string `json:"alternateSources,omitempty"` 15 | } 16 | -------------------------------------------------------------------------------- /pkg/anchor/multierror/multierror.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. 3 | 4 | This file contains software code that is the intellectual property of SecureKey. 5 | SecureKey reserves all rights in the code and you may not use it without 6 | written permission from SecureKey. 7 | */ 8 | 9 | package multierror 10 | 11 | // Error contains multiple errors mapped by unique suffix. 12 | type Error struct { 13 | errors map[string]error 14 | } 15 | 16 | // New returns a new multi-error which contains a map of errors whose key is the unique DID suffix. 17 | func New() *Error { 18 | return &Error{ 19 | errors: make(map[string]error), 20 | } 21 | } 22 | 23 | // Error implements the error interface. 24 | func (e *Error) Error() string { 25 | // Return an arbitrary error. 26 | for _, err := range e.errors { 27 | return err.Error() 28 | } 29 | 30 | return "" 31 | } 32 | 33 | // Errors returns the map of suffix errors. 34 | func (e *Error) Errors() map[string]error { 35 | if e == nil { 36 | return nil 37 | } 38 | 39 | return e.errors 40 | } 41 | 42 | // Set sets the error for the given suffix. 43 | func (e *Error) Set(suffix string, err error) { 44 | e.errors[suffix] = err 45 | } 46 | -------------------------------------------------------------------------------- /pkg/anchor/multierror/multierror_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. 3 | 4 | This file contains software code that is the intellectual property of SecureKey. 5 | SecureKey reserves all rights in the code and you may not use it without 6 | written permission from SecureKey. 7 | */ 8 | 9 | package multierror 10 | 11 | import ( 12 | "errors" 13 | "fmt" 14 | "testing" 15 | 16 | "github.com/stretchr/testify/require" 17 | ) 18 | 19 | func TestError(t *testing.T) { 20 | var err0 *Error 21 | require.Empty(t, err0.Errors()) 22 | 23 | err1 := New() 24 | require.NotNil(t, err1) 25 | require.Empty(t, err1.Error()) 26 | 27 | err1.Set("1111", errors.New("injected error1")) 28 | err1.Set("2222", errors.New("injected error2")) 29 | 30 | err := fmt.Errorf("got some error with cause: %w", err1) 31 | 32 | var mErr *Error 33 | require.True(t, errors.As(err, &mErr)) 34 | require.NotNil(t, mErr) 35 | require.Len(t, mErr.Errors(), 2) 36 | } 37 | -------------------------------------------------------------------------------- /pkg/anchor/subject/model.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package subject 8 | 9 | // Payload defines orb anchor details. 10 | type Payload struct { 11 | OperationCount uint64 12 | CoreIndex string 13 | Attachments []string 14 | Namespace string 15 | Version uint64 16 | AnchorOrigin string 17 | PreviousAnchors []*SuffixAnchor 18 | } 19 | 20 | // SuffixAnchor describes an anchor for suffix. 21 | type SuffixAnchor struct { 22 | Suffix string 23 | Anchor string 24 | } 25 | -------------------------------------------------------------------------------- /pkg/anchor/util/anchordata.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package util 8 | 9 | import ( 10 | "fmt" 11 | "regexp" 12 | "strconv" 13 | "strings" 14 | ) 15 | 16 | const ( 17 | delimiter = "." 18 | allowedParts = 2 19 | base10 = 10 20 | bitSize64 = 64 21 | ) 22 | 23 | var integerRegex = regexp.MustCompile(`^[1-9]\d*$`) 24 | 25 | // AnchorData holds anchored data. 26 | type AnchorData struct { 27 | OperationCount uint64 28 | CoreIndexFileURI string 29 | } 30 | 31 | // ParseAnchorString will parse anchor string into anchor data model. 32 | func ParseAnchorString(anchor string) (*AnchorData, error) { 33 | parts := strings.Split(anchor, delimiter) 34 | 35 | if len(parts) != allowedParts { 36 | return nil, fmt.Errorf("parse anchor data[%s] failed: expecting [%d] parts, got [%d] parts", 37 | anchor, allowedParts, len(parts)) 38 | } 39 | 40 | ok := integerRegex.MatchString(parts[0]) 41 | if !ok { 42 | return nil, fmt.Errorf("parse anchor data[%s] failed: number of operations must be positive integer", anchor) 43 | } 44 | 45 | opsNum, err := strconv.ParseUint(parts[0], base10, bitSize64) 46 | if err != nil { 47 | return nil, fmt.Errorf("parse anchor data[%s] failed: %w", anchor, err) 48 | } 49 | 50 | return &AnchorData{ 51 | OperationCount: opsNum, 52 | CoreIndexFileURI: parts[1], 53 | }, nil 54 | } 55 | 56 | // GetAnchorString will create anchor string from anchor data. 57 | func (ad *AnchorData) GetAnchorString() string { 58 | return fmt.Sprintf("%d", ad.OperationCount) + delimiter + ad.CoreIndexFileURI 59 | } 60 | -------------------------------------------------------------------------------- /pkg/anchor/util/anchordata_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package util 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestParseAnchorData(t *testing.T) { 16 | t.Run("success", func(t *testing.T) { 17 | ad, err := ParseAnchorString("101.coreIndexURI") 18 | require.NoError(t, err) 19 | require.NotNil(t, ad) 20 | 21 | require.Equal(t, ad.OperationCount, uint64(101)) 22 | require.Equal(t, ad.CoreIndexFileURI, "coreIndexURI") 23 | 24 | require.Equal(t, "101.coreIndexURI", ad.GetAnchorString()) 25 | }) 26 | 27 | t.Run("error - invalid number of parts", func(t *testing.T) { 28 | ad, err := ParseAnchorString("1.coreIndexURI.other") 29 | require.Error(t, err) 30 | require.Nil(t, ad) 31 | 32 | require.Contains(t, err.Error(), "expecting [2] parts, got [3] parts") 33 | }) 34 | 35 | t.Run("error - invalid number of operations", func(t *testing.T) { 36 | ad, err := ParseAnchorString("abc.coreIndexURI") 37 | require.Error(t, err) 38 | require.Nil(t, ad) 39 | 40 | require.Contains(t, err.Error(), "number of operations must be positive integer") 41 | }) 42 | 43 | t.Run("error - invalid number of operations starts with 0", func(t *testing.T) { 44 | ad, err := ParseAnchorString("01.coreIndexURI") 45 | require.Error(t, err) 46 | require.Nil(t, ad) 47 | 48 | require.Contains(t, err.Error(), "number of operations must be positive integer") 49 | }) 50 | 51 | t.Run("error - number of operations is negative", func(t *testing.T) { 52 | ad, err := ParseAnchorString("-1.coreIndexURI") 53 | require.Error(t, err) 54 | require.Nil(t, ad) 55 | 56 | require.Contains(t, err.Error(), "number of operations must be positive integer") 57 | }) 58 | } 59 | -------------------------------------------------------------------------------- /pkg/anchor/util/util.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package util 8 | 9 | import ( 10 | "fmt" 11 | "strings" 12 | 13 | "github.com/hyperledger/aries-framework-go/pkg/doc/verifiable" 14 | 15 | "github.com/trustbloc/orb/pkg/errors" 16 | "github.com/trustbloc/orb/pkg/linkset" 17 | ) 18 | 19 | // VerifiableCredentialFromAnchorLink validates the AnchorEvent and returns the embedded verifiable credential. 20 | func VerifiableCredentialFromAnchorLink(anchorLink *linkset.Link, opts ...verifiable.CredentialOpt) (*verifiable.Credential, error) { 21 | if err := anchorLink.Validate(); err != nil { 22 | return nil, fmt.Errorf("invalid anchor link: %w", err) 23 | } 24 | 25 | if anchorLink.Replies() == nil { 26 | return nil, fmt.Errorf("no replies in anchor link") 27 | } 28 | 29 | vcBytes, err := anchorLink.Replies().Content() 30 | if err != nil { 31 | return nil, fmt.Errorf("unmarshal reply: %w", err) 32 | } 33 | 34 | vc, err := verifiable.ParseCredential(vcBytes, append(opts, verifiable.WithStrictValidation())...) 35 | if err != nil { 36 | if strings.Contains(err.Error(), "http request unsuccessful") || 37 | strings.Contains(err.Error(), "http server returned status code") || 38 | strings.Contains(err.Error(), "database error getting public key for issuer") { 39 | // The server is probably down. Return a transient error so that it may be retried. 40 | return nil, errors.NewTransientf("parse credential: %w", err) 41 | } 42 | 43 | return nil, fmt.Errorf("parse credential: %w", err) 44 | } 45 | 46 | return vc, nil 47 | } 48 | -------------------------------------------------------------------------------- /pkg/anchor/vcpubsub/publisher.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package vcpubsub 8 | 9 | import ( 10 | "context" 11 | "encoding/json" 12 | "fmt" 13 | 14 | "github.com/ThreeDotsLabs/watermill/message" 15 | "github.com/trustbloc/logutil-go/pkg/log" 16 | 17 | logfields "github.com/trustbloc/orb/internal/pkg/log" 18 | "github.com/trustbloc/orb/pkg/errors" 19 | "github.com/trustbloc/orb/pkg/linkset" 20 | "github.com/trustbloc/orb/pkg/pubsub" 21 | "github.com/trustbloc/orb/pkg/pubsub/spi" 22 | ) 23 | 24 | var logger = log.New("anchor") 25 | 26 | const anchorTopic = "orb.anchor_linkset" 27 | 28 | type pubSub interface { 29 | Publish(topic string, messages ...*message.Message) error 30 | SubscribeWithOpts(ctx context.Context, topic string, opts ...spi.Option) (<-chan *message.Message, error) 31 | } 32 | 33 | // Publisher implements a publisher that publishes witnessed verifiable credentials to a message queue. 34 | type Publisher struct { 35 | pubSub pubSub 36 | jsonMarshal func(v interface{}) ([]byte, error) 37 | } 38 | 39 | // NewPublisher returns a new verifiable credential publisher. 40 | func NewPublisher(pubSub pubSub) *Publisher { 41 | return &Publisher{ 42 | pubSub: pubSub, 43 | jsonMarshal: json.Marshal, 44 | } 45 | } 46 | 47 | // Publish publishes a verifiable credential to a message queue for processing. 48 | func (h *Publisher) Publish(ctx context.Context, anchorLinkset *linkset.Linkset) error { 49 | payload, err := h.jsonMarshal(anchorLinkset) 50 | if err != nil { 51 | return fmt.Errorf("marshal anchor link: %w", err) 52 | } 53 | 54 | logger.Debugc(ctx, "Publishing anchor linkset", log.WithTopic(anchorTopic), logfields.WithData(payload)) 55 | 56 | err = h.pubSub.Publish(anchorTopic, pubsub.NewMessage(ctx, payload)) 57 | if err != nil { 58 | return errors.NewTransient(err) 59 | } 60 | 61 | return nil 62 | } 63 | -------------------------------------------------------------------------------- /pkg/anchor/witness/policy/config/policystore.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package config 8 | 9 | import ( 10 | "encoding/json" 11 | "fmt" 12 | 13 | "github.com/hyperledger/aries-framework-go/spi/storage" 14 | 15 | orberrors "github.com/trustbloc/orb/pkg/errors" 16 | ) 17 | 18 | const policyKey = "witness-policy" 19 | 20 | // Store implements the witness policy config store. 21 | type Store struct { 22 | store storage.Store 23 | marshal func(v interface{}) ([]byte, error) 24 | unmarshal func(data []byte, v interface{}) error 25 | } 26 | 27 | // NewPolicyStore returns a new witness policy config store. 28 | func NewPolicyStore(store storage.Store) *Store { 29 | return &Store{ 30 | store: store, 31 | marshal: json.Marshal, 32 | unmarshal: json.Unmarshal, 33 | } 34 | } 35 | 36 | // PutPolicy stores the witness policy. 37 | func (s *Store) PutPolicy(policyStr string) error { 38 | policyCfg := &policyCfg{ 39 | Policy: policyStr, 40 | } 41 | 42 | valueBytes, err := s.marshal(policyCfg) 43 | if err != nil { 44 | return fmt.Errorf("marshal witness policy: %w", err) 45 | } 46 | 47 | err = s.store.Put(policyKey, valueBytes) 48 | if err != nil { 49 | return orberrors.NewTransientf("store witness policy: %w", err) 50 | } 51 | 52 | return nil 53 | } 54 | 55 | // GetPolicy returns the witness policy. 56 | func (s *Store) GetPolicy() (string, error) { 57 | policyBytes, err := s.store.Get(policyKey) 58 | if err != nil { 59 | return "", err 60 | } 61 | 62 | policyCfg := &policyCfg{} 63 | 64 | err = s.unmarshal(policyBytes, &policyCfg) 65 | if err != nil { 66 | return "", fmt.Errorf("unmarshal witness policy: %w", err) 67 | } 68 | 69 | return policyCfg.Policy, nil 70 | } 71 | 72 | //nolint:tagliatelle 73 | type policyCfg struct { 74 | Policy string `json:"Policy"` 75 | } 76 | -------------------------------------------------------------------------------- /pkg/anchor/witness/policy/resthandler/openapi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package resthandler 8 | 9 | // swagger:parameters policyGetReq 10 | type policyGetReq struct { //nolint: unused 11 | } 12 | 13 | // swagger:response policyGetResp 14 | type policyGetResp struct { //nolint: unused 15 | Body string 16 | } 17 | 18 | // getPolicy swagger:route GET /policy policy policyGetReq 19 | // 20 | // Retrieves the current witness policy. 21 | // 22 | // Responses: 23 | // 24 | // 200: policyGetResp 25 | func getPolicy() { //nolint: unused 26 | } 27 | 28 | // swagger:parameters policyPostReq 29 | type policyPostReq struct { //nolint: unused 30 | // in: body 31 | Body string 32 | } 33 | 34 | // swagger:response policyPostResp 35 | type policyPostResp struct { //nolint: unused 36 | Body string 37 | } 38 | 39 | // postPolicy swagger:route POST /policy policy policyPostReq 40 | // 41 | // Retrieves the current witness policy. 42 | // 43 | // Responses: 44 | // 45 | // 200: policyPostResp 46 | func postPolicy() { //nolint: unused 47 | } 48 | -------------------------------------------------------------------------------- /pkg/anchor/witness/policy/resthandler/retriever.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package resthandler 8 | 9 | import ( 10 | "encoding/json" 11 | "errors" 12 | "net/http" 13 | 14 | "github.com/hyperledger/aries-framework-go/spi/storage" 15 | "github.com/trustbloc/logutil-go/pkg/log" 16 | "github.com/trustbloc/sidetree-svc-go/pkg/restapi/common" 17 | 18 | logfields "github.com/trustbloc/orb/internal/pkg/log" 19 | ) 20 | 21 | // PolicyRetriever retrieves the current witness policy. 22 | type PolicyRetriever struct { 23 | store policyStore 24 | unmarshal func([]byte, interface{}) error 25 | } 26 | 27 | // Path returns the HTTP REST endpoint for the policy retriever. 28 | func (pc *PolicyRetriever) Path() string { 29 | return endpoint 30 | } 31 | 32 | // Method returns the HTTP REST method for the policy retriever. 33 | func (pc *PolicyRetriever) Method() string { 34 | return http.MethodGet 35 | } 36 | 37 | // Handler returns the HTTP REST handle for the PolicyRetriever service. 38 | func (pc *PolicyRetriever) Handler() common.HTTPRequestHandler { 39 | return pc.handle 40 | } 41 | 42 | // NewRetriever returns a new PolicyRetriever. 43 | func NewRetriever(store policyStore) *PolicyRetriever { 44 | return &PolicyRetriever{ 45 | store: store, 46 | unmarshal: json.Unmarshal, 47 | } 48 | } 49 | 50 | func (pc *PolicyRetriever) handle(w http.ResponseWriter, req *http.Request) { 51 | policyStr, err := pc.store.GetPolicy() 52 | if err != nil { 53 | if errors.Is(err, storage.ErrDataNotFound) { 54 | logger.Debug("Witness policy not found") 55 | 56 | writeResponse(w, http.StatusNotFound, nil) 57 | 58 | return 59 | } 60 | 61 | logger.Error("Error retrieving witness policy", log.WithError(err)) 62 | 63 | writeResponse(w, http.StatusInternalServerError, []byte(internalServerErrorResponse)) 64 | 65 | return 66 | } 67 | 68 | logger.Debug("Retrieved witness policy", logfields.WithWitnessPolicy(policyStr)) 69 | 70 | writeResponse(w, http.StatusOK, []byte(policyStr)) 71 | } 72 | -------------------------------------------------------------------------------- /pkg/anchor/witness/policy/selector/random/selector.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package random 8 | 9 | import ( 10 | "fmt" 11 | "math/rand" 12 | "time" 13 | 14 | "github.com/trustbloc/orb/pkg/anchor/witness/proof" 15 | orberrors "github.com/trustbloc/orb/pkg/errors" 16 | ) 17 | 18 | // New returns new random selector. 19 | func New() *Selector { 20 | rand.Seed(time.Now().UnixNano()) //nolint:staticcheck 21 | 22 | return &Selector{} 23 | } 24 | 25 | // Selector implements random selection of n out of m witnesses. 26 | type Selector struct{} 27 | 28 | // Select selects n witnesses out of provided list of witnesses. 29 | func (s *Selector) Select(witnesses []*proof.Witness, n int) ([]*proof.Witness, error) { 30 | l := len(witnesses) 31 | 32 | if n > l { 33 | return nil, fmt.Errorf("unable to select %d witnesses from witness array of length %d: %w", 34 | n, len(witnesses), orberrors.ErrWitnessesNotFound) 35 | } 36 | 37 | if n == l { 38 | return witnesses, nil 39 | } 40 | 41 | max := len(witnesses) 42 | 43 | var selected []*proof.Witness 44 | 45 | uniqueIndexes := make(map[int]bool) 46 | 47 | for i := 0; i < n; i++ { 48 | for { 49 | i := rand.Intn(max) //nolint:gosec 50 | 51 | if _, ok := uniqueIndexes[i]; !ok { 52 | uniqueIndexes[i] = true 53 | 54 | selected = append(selected, witnesses[i]) 55 | 56 | break 57 | } 58 | } 59 | } 60 | 61 | return selected, nil 62 | } 63 | -------------------------------------------------------------------------------- /pkg/anchor/witness/policy/selector/random/selector_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package random 8 | 9 | import ( 10 | "errors" 11 | "testing" 12 | 13 | "github.com/stretchr/testify/require" 14 | 15 | "github.com/trustbloc/orb/pkg/anchor/witness/proof" 16 | orberrors "github.com/trustbloc/orb/pkg/errors" 17 | ) 18 | 19 | func TestNew(t *testing.T) { 20 | t.Run("success", func(t *testing.T) { 21 | s := New() 22 | require.NotNil(t, s) 23 | }) 24 | } 25 | 26 | func TestSelect(t *testing.T) { 27 | t.Run("success", func(t *testing.T) { 28 | s := New() 29 | require.NotNil(t, s) 30 | 31 | witnesses := []*proof.Witness{{}, {}, {}, {}} 32 | 33 | selected, err := s.Select(witnesses, 3) 34 | require.NoError(t, err) 35 | require.Equal(t, 3, len(selected)) 36 | }) 37 | 38 | t.Run("success", func(t *testing.T) { 39 | s := New() 40 | require.NotNil(t, s) 41 | 42 | witnesses := []*proof.Witness{{}, {}} 43 | 44 | selected, err := s.Select(witnesses, 2) 45 | require.NoError(t, err) 46 | require.Equal(t, 2, len(selected)) 47 | }) 48 | 49 | t.Run("error", func(t *testing.T) { 50 | s := New() 51 | require.NotNil(t, s) 52 | 53 | selected, err := s.Select(nil, 2) 54 | require.Error(t, err) 55 | require.Empty(t, selected) 56 | require.True(t, errors.Is(err, orberrors.ErrWitnessesNotFound)) 57 | require.Contains(t, err.Error(), "unable to select 2 witnesses from witness array of length 0") 58 | }) 59 | } 60 | -------------------------------------------------------------------------------- /pkg/anchor/witness/proof/proof.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package proof 8 | 9 | import ( 10 | "fmt" 11 | 12 | "github.com/trustbloc/orb/pkg/activitypub/vocab" 13 | ) 14 | 15 | // Witness contains info about witness. 16 | type Witness struct { 17 | Type WitnessType `json:"type"` 18 | URI *vocab.URLProperty `json:"uri"` 19 | HasLog bool `json:"hasLog"` 20 | Selected bool `json:"selected"` 21 | } 22 | 23 | func (wf *Witness) String() string { 24 | return fmt.Sprintf("{type:%s, witness:%s, log:%t}", wf.Type, wf.URI, wf.HasLog) 25 | } 26 | 27 | // WitnessProof contains anchor index witness proof. 28 | type WitnessProof struct { 29 | *Witness 30 | Proof []byte 31 | } 32 | 33 | func (wf *WitnessProof) String() string { 34 | return fmt.Sprintf("{type:%s, witness:%s, log:%t, proof:%s}", wf.Type, wf.URI, wf.HasLog, string(wf.Proof)) 35 | } 36 | 37 | // WitnessType defines valid values for witness type. 38 | type WitnessType string 39 | 40 | const ( 41 | 42 | // WitnessTypeBatch captures "batch" witness type. 43 | WitnessTypeBatch WitnessType = "batch" 44 | 45 | // WitnessTypeSystem captures "system" witness type. 46 | WitnessTypeSystem WitnessType = "system" 47 | ) 48 | 49 | // AnchorIndexStatus defines valid values for verifiable credential proof collection status. 50 | type AnchorIndexStatus string 51 | 52 | const ( 53 | 54 | // AnchorIndexStatusInProcess defines "in-process" status. 55 | AnchorIndexStatusInProcess AnchorIndexStatus = "in-process" 56 | 57 | // AnchorIndexStatusCompleted defines "completed" status. 58 | AnchorIndexStatusCompleted AnchorIndexStatus = "completed" 59 | ) 60 | -------------------------------------------------------------------------------- /pkg/anchor/witness/proof/proof_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package proof 8 | 9 | import ( 10 | "net/url" 11 | "testing" 12 | 13 | "github.com/stretchr/testify/require" 14 | 15 | "github.com/trustbloc/orb/pkg/activitypub/vocab" 16 | ) 17 | 18 | func Test(t *testing.T) { 19 | t.Run("success", func(t *testing.T) { 20 | testURI, err := url.Parse("http://domain.com/service") 21 | require.NoError(t, err) 22 | 23 | w := &Witness{Type: WitnessTypeBatch, URI: vocab.NewURLProperty(testURI), HasLog: true} 24 | require.Equal(t, w.String(), "{type:batch, witness:http://domain.com/service, log:true}") 25 | }) 26 | 27 | t.Run("success", func(t *testing.T) { 28 | testURI, err := url.Parse("http://domain.com/service") 29 | require.NoError(t, err) 30 | 31 | wp := &WitnessProof{ 32 | Witness: &Witness{ 33 | Type: WitnessTypeBatch, 34 | URI: vocab.NewURLProperty(testURI), 35 | HasLog: true, 36 | }, 37 | Proof: []byte("proof"), 38 | } 39 | require.Equal(t, wp.String(), "{type:batch, witness:http://domain.com/service, log:true, proof:proof}") 40 | }) 41 | } 42 | -------------------------------------------------------------------------------- /pkg/cas/extendedcasclient/extendedcasclient.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package extendedcasclient 8 | 9 | import casapi "github.com/trustbloc/sidetree-svc-go/pkg/api/cas" 10 | 11 | // CIDFormatOption is an option for specifying the CID format used in a WriteWithCIDFormat call. 12 | type CIDFormatOption func(opts *CIDFormatOptions) 13 | 14 | // CIDFormatOptions represent CID format options for use in a Client.WriteWithCIDFormat call. 15 | type CIDFormatOptions struct { 16 | CIDVersion int 17 | } 18 | 19 | // WithCIDVersion sets the CID version to be used in a WriteWithCIDFormat call. 20 | // Currently, 0 and 1 are the only valid options. 21 | func WithCIDVersion(cidVersion int) CIDFormatOption { 22 | return func(opts *CIDFormatOptions) { 23 | opts.CIDVersion = cidVersion 24 | } 25 | } 26 | 27 | // Client represents a CAS client with an additional method that allows the CID format 28 | // to be specified for a specific write. 29 | type Client interface { 30 | casapi.Client 31 | WriteWithCIDFormat(content []byte, opts ...CIDFormatOption) (string, error) 32 | GetPrimaryWriterType() string 33 | } 34 | -------------------------------------------------------------------------------- /pkg/config/config.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package config 8 | 9 | import ( 10 | "github.com/trustbloc/sidetree-go/pkg/api/operation" 11 | "github.com/trustbloc/sidetree-go/pkg/versions/1_0/operationparser" 12 | 13 | "github.com/trustbloc/orb/pkg/store/operation/unpublished" 14 | ) 15 | 16 | // Sidetree holds global Sidetree configuration. 17 | type Sidetree struct { 18 | MethodContext []string 19 | EnableBase bool 20 | 21 | UnpublishedOpStore *unpublished.Store 22 | UnpublishedOperationStoreOperationTypes []operation.Type 23 | 24 | IncludeUnpublishedOperations bool 25 | IncludePublishedOperations bool 26 | 27 | AllowedOriginsValidator operationparser.ObjectValidator 28 | } 29 | -------------------------------------------------------------------------------- /pkg/context/common/provider.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package common 8 | 9 | import ( 10 | "net/url" 11 | 12 | "github.com/trustbloc/sidetree-go/pkg/api/operation" 13 | 14 | "github.com/trustbloc/orb/pkg/anchor/graph" 15 | ) 16 | 17 | // OperationStore interface to access operation store. 18 | type OperationStore interface { 19 | Get(suffix string) ([]*operation.AnchoredOperation, error) 20 | Put(ops []*operation.AnchoredOperation) error 21 | } 22 | 23 | // AnchorGraph interface to access did anchors. 24 | type AnchorGraph interface { 25 | GetDidAnchors(cid, suffix string) ([]graph.Anchor, error) 26 | } 27 | 28 | // CASResolver interface to resolve cid. Returns the content and a hashlink to the local CAS store. 29 | type CASResolver interface { 30 | Resolve(webCASURL *url.URL, cid string, data []byte) ([]byte, string, error) 31 | } 32 | 33 | // CASReader interface to read from content addressable storage. 34 | type CASReader interface { 35 | Read(key string) ([]byte, error) 36 | } 37 | -------------------------------------------------------------------------------- /pkg/context/context.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package context 8 | 9 | import ( 10 | "github.com/trustbloc/sidetree-svc-go/pkg/api/protocol" 11 | "github.com/trustbloc/sidetree-svc-go/pkg/batch" 12 | "github.com/trustbloc/sidetree-svc-go/pkg/batch/cutter" 13 | ) 14 | 15 | // New returns a new server context. 16 | func New(pc protocol.Client, aw batch.AnchorWriter, opQueue cutter.OperationQueue) *ServerContext { 17 | return &ServerContext{ 18 | ProtocolClient: pc, 19 | AnchorWriter: aw, 20 | OpQueue: opQueue, 21 | } 22 | } 23 | 24 | // ServerContext implements batch context. 25 | type ServerContext struct { 26 | ProtocolClient protocol.Client 27 | AnchorWriter batch.AnchorWriter 28 | OpQueue cutter.OperationQueue 29 | } 30 | 31 | // Protocol returns the ProtocolClient. 32 | func (m *ServerContext) Protocol() protocol.Client { 33 | return m.ProtocolClient 34 | } 35 | 36 | // Anchor returns the anchor writer. 37 | func (m *ServerContext) Anchor() batch.AnchorWriter { 38 | return m.AnchorWriter 39 | } 40 | 41 | // OperationQueue returns the queue containing the pending operations. 42 | func (m *ServerContext) OperationQueue() cutter.OperationQueue { 43 | return m.OpQueue 44 | } 45 | -------------------------------------------------------------------------------- /pkg/context/context_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package context 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | "github.com/trustbloc/sidetree-svc-go/pkg/batch/opqueue" 14 | ) 15 | 16 | func TestNew(t *testing.T) { 17 | c := New(nil, nil, &opqueue.MemQueue{}) 18 | require.NotNil(t, c) 19 | 20 | require.Equal(t, nil, c.Anchor()) 21 | require.Equal(t, nil, c.Protocol()) 22 | require.NotNil(t, c.OperationQueue()) 23 | } 24 | -------------------------------------------------------------------------------- /pkg/context/protocol/provider/provider.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package provider 8 | 9 | import ( 10 | "fmt" 11 | "sync" 12 | 13 | "github.com/trustbloc/sidetree-svc-go/pkg/api/protocol" 14 | ) 15 | 16 | // New creates new protocol client provider. 17 | func New() *ClientProvider { 18 | return &ClientProvider{clients: make(map[string]protocol.Client)} 19 | } 20 | 21 | // ClientProvider implements mock protocol client provider. 22 | type ClientProvider struct { 23 | mutex sync.RWMutex 24 | clients map[string]protocol.Client 25 | } 26 | 27 | // Add adds protocol client for namespace. 28 | func (m *ClientProvider) Add(namespace string, pc protocol.Client) { 29 | m.mutex.Lock() 30 | defer m.mutex.Unlock() 31 | 32 | m.clients[namespace] = pc 33 | } 34 | 35 | // ForNamespace will return protocol client for that namespace. 36 | func (m *ClientProvider) ForNamespace(namespace string) (protocol.Client, error) { 37 | m.mutex.RLock() 38 | defer m.mutex.RUnlock() 39 | 40 | pc, ok := m.clients[namespace] 41 | if !ok { 42 | return nil, fmt.Errorf("protocol client not defined for namespace: %s", namespace) 43 | } 44 | 45 | return pc, nil 46 | } 47 | -------------------------------------------------------------------------------- /pkg/context/protocol/provider/provider_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package provider 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | "github.com/trustbloc/sidetree-go/pkg/api/protocol" 14 | svcprotocol "github.com/trustbloc/sidetree-svc-go/pkg/api/protocol" 15 | svcmocks "github.com/trustbloc/sidetree-svc-go/pkg/mocks" 16 | 17 | "github.com/trustbloc/orb/pkg/context/protocol/client" 18 | ) 19 | 20 | const ns = "did:orb" 21 | 22 | func TestNew(t *testing.T) { 23 | p := New() 24 | require.NotNil(t, p) 25 | } 26 | 27 | func TestClientProvider_ForNamespace(t *testing.T) { 28 | v1_0 := &svcmocks.ProtocolVersion{} 29 | v1_0.ProtocolReturns(protocol.Protocol{ 30 | GenesisTime: 0, 31 | MaxOperationCount: 10, 32 | }) 33 | 34 | versions := []svcprotocol.Version{v1_0} 35 | 36 | pc, err := client.New(versions) 37 | require.NotNil(t, pc) 38 | require.NoError(t, err) 39 | 40 | p := New() 41 | require.NotNil(t, p) 42 | 43 | p.Add(ns, pc) 44 | 45 | t.Run("success", func(t *testing.T) { 46 | retClient, err := p.ForNamespace(ns) 47 | require.NoError(t, err) 48 | require.NotNil(t, retClient) 49 | 50 | cur, err := retClient.Current() 51 | require.NoError(t, err) 52 | require.Equal(t, uint(10), cur.Protocol().MaxOperationCount) 53 | }) 54 | 55 | t.Run("error - client not found for namespace", func(t *testing.T) { 56 | retClient, err := p.ForNamespace("invalid") 57 | require.Error(t, err) 58 | require.Nil(t, retClient) 59 | require.Contains(t, err.Error(), "protocol client not defined for namespace: invalid") 60 | }) 61 | } 62 | -------------------------------------------------------------------------------- /pkg/didanchor/memdidanchor/store.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package memdidanchor 8 | 9 | import ( 10 | "sync" 11 | 12 | "github.com/trustbloc/orb/pkg/didanchor" 13 | ) 14 | 15 | // DidAnchor is in-memory implementation of did/anchor references. 16 | type DidAnchor struct { 17 | mutex sync.RWMutex 18 | m map[string]string 19 | } 20 | 21 | // New creates in-memory implementation for latest did anchor. 22 | func New() *DidAnchor { 23 | return &DidAnchor{m: make(map[string]string)} 24 | } 25 | 26 | // PutBulk saves anchor cid for specified suffixes. If suffix already exists, anchor value will be overwritten. 27 | func (ref *DidAnchor) PutBulk(suffixes []string, _ []bool, cid string) error { 28 | ref.mutex.Lock() 29 | defer ref.mutex.Unlock() 30 | 31 | for _, suffix := range suffixes { 32 | ref.m[suffix] = cid 33 | } 34 | 35 | return nil 36 | } 37 | 38 | // GetBulk retrieves anchors for specified suffixes. 39 | func (ref *DidAnchor) GetBulk(suffixes []string) ([]string, error) { 40 | ref.mutex.RLock() 41 | defer ref.mutex.RUnlock() 42 | 43 | anchors := make([]string, len(suffixes)) 44 | 45 | for i, suffix := range suffixes { 46 | anchor, ok := ref.m[suffix] 47 | if !ok { 48 | anchors[i] = "" 49 | } else { 50 | anchors[i] = anchor 51 | } 52 | } 53 | 54 | return anchors, nil 55 | } 56 | 57 | // Get retrieves anchor for specified suffix. 58 | func (ref *DidAnchor) Get(suffix string) (string, error) { 59 | ref.mutex.RLock() 60 | defer ref.mutex.RUnlock() 61 | 62 | anchor, ok := ref.m[suffix] 63 | if !ok { 64 | return "", didanchor.ErrDataNotFound 65 | } 66 | 67 | return anchor, nil 68 | } 69 | -------------------------------------------------------------------------------- /pkg/didanchor/memdidanchor/store_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package memdidanchor 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | 14 | "github.com/trustbloc/orb/pkg/didanchor" 15 | ) 16 | 17 | const ( 18 | testSuffix = "suffix" 19 | testCID = "cid" 20 | ) 21 | 22 | func TestDidAnchor_PutBulk(t *testing.T) { 23 | t.Run("success", func(t *testing.T) { 24 | refs := New() 25 | 26 | err := refs.PutBulk([]string{testSuffix}, nil, testCID) 27 | require.NoError(t, err) 28 | }) 29 | } 30 | 31 | func TestDidAnchor_GetBulk(t *testing.T) { 32 | t.Run("success", func(t *testing.T) { 33 | refs := New() 34 | 35 | err := refs.PutBulk([]string{testSuffix}, nil, testCID) 36 | require.NoError(t, err) 37 | 38 | anchors, err := refs.GetBulk([]string{testSuffix}) 39 | require.NoError(t, err) 40 | require.Equal(t, anchors, []string{testCID}) 41 | }) 42 | 43 | t.Run("success - did anchor not found", func(t *testing.T) { 44 | refs := New() 45 | 46 | anchors, err := refs.GetBulk([]string{"non-existent"}) 47 | require.NoError(t, err) 48 | require.Equal(t, "", anchors[0]) 49 | }) 50 | } 51 | 52 | func TestDidAnchor_Get(t *testing.T) { 53 | t.Run("success", func(t *testing.T) { 54 | refs := New() 55 | 56 | err := refs.PutBulk([]string{testSuffix}, nil, testCID) 57 | require.NoError(t, err) 58 | 59 | anchor, err := refs.Get(testSuffix) 60 | require.NoError(t, err) 61 | require.Equal(t, anchor, testCID) 62 | }) 63 | 64 | t.Run("error - did anchor not found", func(t *testing.T) { 65 | refs := New() 66 | 67 | anchor, err := refs.Get("non-existent") 68 | require.Error(t, err) 69 | require.Empty(t, anchor) 70 | require.Equal(t, err, didanchor.ErrDataNotFound) 71 | }) 72 | } 73 | -------------------------------------------------------------------------------- /pkg/didanchor/refs.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package didanchor 8 | 9 | import "errors" 10 | 11 | // DidAnchor manages latest anchor for suffix. 12 | type DidAnchor interface { 13 | PutBulk(suffixes []string, cid string) error 14 | GetBulk(suffixes []string) ([]string, error) 15 | Get(suffix string) (string, error) 16 | } 17 | 18 | // ErrDataNotFound is used to indicate data not found error. 19 | var ErrDataNotFound = errors.New("data not found") 20 | -------------------------------------------------------------------------------- /pkg/discovery/did/noop/noop.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package noop 8 | 9 | import "context" 10 | 11 | // New creates new noop discovery. 12 | func New() *Discovery { 13 | return &Discovery{} 14 | } 15 | 16 | // Discovery implements noop did discovery. 17 | type Discovery struct{} 18 | 19 | // RequestDiscovery requests did discovery. 20 | func (*Discovery) RequestDiscovery(ctx context.Context, id string) error { 21 | return nil 22 | } 23 | -------------------------------------------------------------------------------- /pkg/discovery/did/noop/noop_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package noop 8 | 9 | import ( 10 | "context" 11 | "testing" 12 | 13 | "github.com/stretchr/testify/require" 14 | ) 15 | 16 | func TestDiscovery_RequestDiscovery(t *testing.T) { 17 | t.Run("success", func(t *testing.T) { 18 | d := New() 19 | 20 | err := d.RequestDiscovery(context.Background(), "did") 21 | require.NoError(t, err) 22 | }) 23 | } 24 | -------------------------------------------------------------------------------- /pkg/discovery/endpoint/client/models/endpoint.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package models 7 | 8 | import "time" 9 | 10 | // Endpoint include info about anchor endpoint. 11 | type Endpoint struct { 12 | ResolutionEndpoints []string 13 | OperationEndpoints []string 14 | MinResolvers int 15 | MaxAge uint `json:"-"` 16 | AnchorOrigin string 17 | AnchorURI string 18 | } 19 | 20 | // CacheLifetime returns the cache lifetime of the endpoint config file before it needs to be checked for an update. 21 | func (c *Endpoint) CacheLifetime() (time.Duration, error) { 22 | return time.Duration(c.MaxAge) * time.Second, nil 23 | } 24 | -------------------------------------------------------------------------------- /pkg/discovery/endpoint/restapi/model.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package restapi 8 | 9 | // ErrorResponse to send error message in the response. 10 | type ErrorResponse struct { 11 | Message string `json:"errMessage,omitempty"` 12 | } 13 | 14 | // WellKnownResponse well known response. 15 | type WellKnownResponse struct { 16 | ResolutionEndpoint string `json:"resolutionEndpoint,omitempty"` 17 | OperationEndpoint string `json:"operationEndpoint,omitempty"` 18 | } 19 | 20 | // JRD is a JSON Resource Descriptor as defined in https://datatracker.ietf.org/doc/html/rfc6415#appendix-A 21 | // and https://datatracker.ietf.org/doc/html/rfc7033#section-4.4. 22 | type JRD struct { 23 | Subject string `json:"subject,omitempty"` 24 | Properties map[string]interface{} `json:"properties,omitempty"` 25 | Links []Link `json:"links,omitempty"` 26 | } 27 | 28 | // Link is a link in a JRD. 29 | // Note that while the host-meta and WebFinger endpoints both use this, only host-meta supports the Template field. 30 | type Link struct { 31 | Rel string `json:"rel,omitempty"` 32 | Type string `json:"type,omitempty"` 33 | Href string `json:"href,omitempty"` 34 | Template string `json:"template,omitempty"` 35 | } 36 | -------------------------------------------------------------------------------- /pkg/discovery/endpoint/restapi/openapi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package restapi 7 | 8 | // genericError model 9 | // 10 | // swagger:response genericError 11 | type genericError struct { //nolint: unused 12 | // in: body 13 | Body ErrorResponse 14 | } 15 | 16 | // wellKnownReq model 17 | // 18 | // swagger:parameters wellKnownReq 19 | type wellKnownReq struct{} //nolint: unused 20 | 21 | // wellKnownResp model 22 | // 23 | // swagger:response wellKnownResp 24 | type wellKnownResp struct { //nolint: unused 25 | // in: body 26 | Body *WellKnownResponse 27 | } 28 | 29 | // webFingerReq model 30 | // 31 | // swagger:parameters webFingerReq 32 | type webFingerReq struct { //nolint: unused 33 | // in: query 34 | Resource string `json:"resource"` 35 | } 36 | 37 | // webFingerResp model 38 | // 39 | // swagger:response webFingerResp 40 | type webFingerResp struct { //nolint: unused 41 | // in: body 42 | Body *JRD 43 | } 44 | 45 | // wellKnownDIDReq model 46 | // 47 | // swagger:parameters wellKnownDIDReq 48 | type wellKnownDIDReq struct{} //nolint: unused 49 | 50 | // wellKnownDIDResp model 51 | // 52 | // swagger:response wellKnownDIDResp 53 | type wellKnownDIDResp struct { //nolint: unused 54 | } 55 | 56 | // wellKnownNodeInfoReq model 57 | // 58 | // swagger:parameters wellKnownNodeInfoReq 59 | type wellKnownNodeInfoReq struct{} //nolint: unused 60 | 61 | // wellKnownNodeInfoResp model 62 | // 63 | // swagger:response wellKnownNodeInfoResp 64 | type wellKnownNodeInfoResp struct { //nolint: unused 65 | // in: body 66 | Body *JRD 67 | } 68 | -------------------------------------------------------------------------------- /pkg/document/didresolver/resolvehandler.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package didresolver 8 | 9 | import ( 10 | "fmt" 11 | "strings" 12 | 13 | "github.com/trustbloc/sidetree-go/pkg/document" 14 | ) 15 | 16 | type webResolver interface { 17 | ResolveDocument(id string) (*document.ResolutionResult, error) 18 | } 19 | 20 | type orbResolver interface { 21 | ResolveDocument(id string, opts ...document.ResolutionOption) (*document.ResolutionResult, error) 22 | } 23 | 24 | // ResolveHandler resolves did:orb and did:web (produced from did:orb) documents. 25 | type ResolveHandler struct { 26 | webResolver 27 | orbResolver 28 | } 29 | 30 | // NewResolveHandler returns a new did document resolve handler. Supported methods are did:orb and did:web. 31 | func NewResolveHandler(orbResolver orbResolver, webResolver webResolver) *ResolveHandler { 32 | rh := &ResolveHandler{ 33 | orbResolver: orbResolver, 34 | webResolver: webResolver, 35 | } 36 | 37 | return rh 38 | } 39 | 40 | // ResolveDocument resolves a did document. 41 | func (r *ResolveHandler) ResolveDocument(id string, opts ...document.ResolutionOption) (*document.ResolutionResult, error) { 42 | switch { 43 | case strings.HasPrefix(id, "did:orb"): 44 | return r.orbResolver.ResolveDocument(id, opts...) 45 | case strings.HasPrefix(id, "did:web"): 46 | return r.webResolver.ResolveDocument(id) 47 | default: 48 | return nil, fmt.Errorf("did method not supported for id[%s]", id) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /pkg/document/resolvehandler/openapi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package resolvehandler 8 | 9 | import ( 10 | "github.com/trustbloc/sidetree-go/pkg/document" 11 | ) 12 | 13 | // swagger:parameters identifiersReq 14 | type identifiersReq struct { //nolint: unused 15 | // In: path 16 | ID string `json:"id"` 17 | } 18 | 19 | // swagger:response identifiersResp 20 | type identifiersResp struct { //nolint: unused 21 | // in: body 22 | Body document.ResolutionResult 23 | } 24 | 25 | // identifiersRequest swagger:route GET /sidetree/v1/identifiers/{id} Sidetree identifiersReq 26 | // 27 | // A DID document is retrieved using the /sidetree/v1/identifiers endpoint. 28 | // 29 | // Produces: 30 | // - application/json 31 | // 32 | // Responses: 33 | // 34 | // 200: identifiersResp 35 | func identifiersRequest() { //nolint: unused 36 | } 37 | -------------------------------------------------------------------------------- /pkg/document/updatehandler/openapi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package updatehandler 8 | 9 | // Request message 10 | // 11 | // swagger:parameters operationsReq 12 | type operationsReq struct { //nolint: unused 13 | // in: body 14 | Body string 15 | } 16 | 17 | // Response message 18 | // 19 | // swagger:response operationsResp 20 | type operationsResp struct { //nolint: unused 21 | Body string 22 | } 23 | 24 | // handlePost swagger:route POST /sidetree/v1/operations Sidetree operationsReq 25 | // 26 | // Posts a Sidetree operation. 27 | // 28 | // Consumes: 29 | // - application/json 30 | // 31 | // Responses: 32 | // 33 | // 200: operationsResp 34 | func operationsResponse() { //nolint: unused 35 | } 36 | -------------------------------------------------------------------------------- /pkg/document/updatehandler/updatehandler.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package updatehandler 8 | 9 | import ( 10 | "time" 11 | 12 | "github.com/trustbloc/sidetree-go/pkg/document" 13 | "github.com/trustbloc/sidetree-svc-go/pkg/restapi/dochandler" 14 | ) 15 | 16 | type metricsProvider interface { 17 | DocumentCreateUpdateTime(duration time.Duration) 18 | } 19 | 20 | // Option is an option for update handler. 21 | type Option func(opts *UpdateHandler) 22 | 23 | // UpdateHandler handles the creation and update of documents. 24 | type UpdateHandler struct { 25 | coreProcessor dochandler.Processor 26 | metrics metricsProvider 27 | } 28 | 29 | // New creates a new document update handler. 30 | func New(processor dochandler.Processor, metrics metricsProvider, opts ...Option) *UpdateHandler { 31 | dh := &UpdateHandler{ 32 | coreProcessor: processor, 33 | metrics: metrics, 34 | } 35 | 36 | // apply options 37 | for _, opt := range opts { 38 | opt(dh) 39 | } 40 | 41 | return dh 42 | } 43 | 44 | // Namespace returns the namespace of the document handler. 45 | func (r *UpdateHandler) Namespace() string { 46 | return r.coreProcessor.Namespace() 47 | } 48 | 49 | // ProcessOperation validates operation and adds it to the batch. 50 | func (r *UpdateHandler) ProcessOperation(operationBuffer []byte, protocolVersion uint64) (*document.ResolutionResult, error) { 51 | startTime := time.Now() 52 | 53 | defer func() { 54 | r.metrics.DocumentCreateUpdateTime(time.Since(startTime)) 55 | }() 56 | 57 | doc, err := r.coreProcessor.ProcessOperation(operationBuffer, protocolVersion) 58 | if err != nil { 59 | return nil, err 60 | } 61 | 62 | return doc, nil 63 | } 64 | -------------------------------------------------------------------------------- /pkg/errors/errors_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package errors 8 | 9 | import ( 10 | "errors" 11 | "fmt" 12 | "testing" 13 | 14 | "github.com/stretchr/testify/require" 15 | ) 16 | 17 | func TestTransientError(t *testing.T) { 18 | et := errors.New("some transient error") 19 | ep := errors.New("some persistent error") 20 | 21 | err := fmt.Errorf("got error: %w", NewTransient(et)) 22 | 23 | require.True(t, IsTransient(err)) 24 | require.True(t, errors.Is(err, et)) 25 | require.False(t, IsTransient(ep)) 26 | require.EqualError(t, err, "got error: some transient error") 27 | 28 | err = NewTransientf("some transient error") 29 | require.True(t, IsTransient(err)) 30 | } 31 | 32 | func TestBadRequestError(t *testing.T) { 33 | eir := errors.New("some bad request error") 34 | e := errors.New("some other error") 35 | 36 | err := fmt.Errorf("got error: %w", NewBadRequest(eir)) 37 | 38 | require.True(t, IsBadRequest(err)) 39 | require.True(t, errors.Is(err, eir)) 40 | require.False(t, IsBadRequest(e)) 41 | require.EqualError(t, err, "got error: some bad request error") 42 | 43 | err = NewBadRequestf("some bad request") 44 | require.True(t, IsBadRequest(err)) 45 | } 46 | -------------------------------------------------------------------------------- /pkg/httpserver/auth/authwrapper_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package auth 8 | 9 | import ( 10 | "net/http" 11 | "net/http/httptest" 12 | "testing" 13 | 14 | "github.com/stretchr/testify/require" 15 | "github.com/trustbloc/sidetree-svc-go/pkg/restapi/common" 16 | 17 | apmocks "github.com/trustbloc/orb/pkg/activitypub/mocks" 18 | ) 19 | 20 | func TestHandlerWrapper(t *testing.T) { 21 | t.Run("Success", func(t *testing.T) { 22 | w := NewHandlerWrapper(&mockHTTPHandler{ 23 | path: "/services/orb/outbox", 24 | method: http.MethodPost, 25 | }, &apmocks.AuthTokenMgr{}) 26 | require.NotNil(t, w) 27 | 28 | rw := httptest.NewRecorder() 29 | req := httptest.NewRequest(http.MethodPost, "/services/orb/outbox", http.NoBody) 30 | req.Header[authHeader] = []string{tokenPrefix + "ADMIN_TOKEN"} 31 | 32 | w.Handler()(rw, req) 33 | 34 | result := rw.Result() 35 | require.Equal(t, http.StatusOK, result.StatusCode) 36 | require.NoError(t, result.Body.Close()) 37 | }) 38 | 39 | t.Run("Unauthorized", func(t *testing.T) { 40 | tm := &apmocks.AuthTokenMgr{} 41 | tm.RequiredAuthTokensReturns([]string{"admin"}, nil) 42 | 43 | w := NewHandlerWrapper(&mockHTTPHandler{ 44 | path: "/services/orb/outbox", 45 | method: http.MethodPost, 46 | }, tm) 47 | require.NotNil(t, w) 48 | 49 | rw := httptest.NewRecorder() 50 | req := httptest.NewRequest(http.MethodPost, "/services/orb/outbox", http.NoBody) 51 | 52 | w.Handler()(rw, req) 53 | 54 | result := rw.Result() 55 | require.Equal(t, http.StatusUnauthorized, result.StatusCode) 56 | require.NoError(t, result.Body.Close()) 57 | }) 58 | } 59 | 60 | type mockHTTPHandler struct { 61 | path string 62 | method string 63 | } 64 | 65 | func (m *mockHTTPHandler) Path() string { 66 | return m.path 67 | } 68 | 69 | func (m *mockHTTPHandler) Method() string { 70 | return m.method 71 | } 72 | 73 | func (m *mockHTTPHandler) Handler() common.HTTPRequestHandler { 74 | return func(writer http.ResponseWriter, request *http.Request) {} 75 | } 76 | -------------------------------------------------------------------------------- /pkg/httpserver/maintenance/mode.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package maintenance 8 | 9 | import ( 10 | "net/http" 11 | 12 | "github.com/trustbloc/logutil-go/pkg/log" 13 | "github.com/trustbloc/sidetree-svc-go/pkg/restapi/common" 14 | 15 | logfields "github.com/trustbloc/orb/internal/pkg/log" 16 | ) 17 | 18 | const loggerModule = "maintenance" 19 | 20 | const serviceUnavailableResponse = "Service Unavailable.\n" 21 | 22 | // HandlerWrapper wraps an existing HTTP handler and call to handler endpoint returns 503 (Service Unavailable). 23 | // If authorized then the wrapped handler is invoked. 24 | type HandlerWrapper struct { 25 | common.HTTPHandler 26 | 27 | writeResponse func(w http.ResponseWriter, status int, body []byte) 28 | logger *log.Log 29 | } 30 | 31 | // NewMaintenanceWrapper will return service unavailable for handler that was passed in. 32 | func NewMaintenanceWrapper(handler common.HTTPHandler) *HandlerWrapper { 33 | logger := log.New(loggerModule, log.WithFields(logfields.WithServiceEndpoint(handler.Path()))) 34 | 35 | return &HandlerWrapper{ 36 | HTTPHandler: handler, 37 | logger: logger, 38 | writeResponse: func(w http.ResponseWriter, status int, body []byte) { 39 | w.WriteHeader(status) 40 | 41 | if len(body) > 0 { 42 | if _, err := w.Write(body); err != nil { 43 | log.WriteResponseBodyError(logger, err) 44 | 45 | return 46 | } 47 | 48 | log.WroteResponse(logger, body) 49 | } 50 | }, 51 | } 52 | } 53 | 54 | // Handler returns the 'wrapper' handler. 55 | func (h *HandlerWrapper) Handler() common.HTTPRequestHandler { 56 | return func(w http.ResponseWriter, req *http.Request) { 57 | h.writeResponse(w, http.StatusServiceUnavailable, []byte(serviceUnavailableResponse)) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /pkg/httpserver/maintenance/mode_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package maintenance 8 | 9 | import ( 10 | "net/http" 11 | "net/http/httptest" 12 | "testing" 13 | 14 | "github.com/stretchr/testify/require" 15 | "github.com/trustbloc/sidetree-svc-go/pkg/restapi/common" 16 | ) 17 | 18 | func TestHandlerWrapper(t *testing.T) { 19 | t.Run("Success", func(t *testing.T) { 20 | const path = "/services/orb/inbox" 21 | 22 | w := NewMaintenanceWrapper(&mockHTTPHandler{ 23 | path: path, 24 | method: http.MethodPost, 25 | }) 26 | require.NotNil(t, w) 27 | 28 | require.Equal(t, path, w.Path()) 29 | require.Equal(t, http.MethodPost, w.Method()) 30 | 31 | rw := httptest.NewRecorder() 32 | req := httptest.NewRequest(http.MethodPost, "/services/orb/inbox", http.NoBody) 33 | 34 | w.Handler()(rw, req) 35 | 36 | result := rw.Result() 37 | require.Equal(t, http.StatusServiceUnavailable, result.StatusCode) 38 | require.NoError(t, result.Body.Close()) 39 | }) 40 | } 41 | 42 | type mockHTTPHandler struct { 43 | path string 44 | method string 45 | } 46 | 47 | func (m *mockHTTPHandler) Path() string { 48 | return m.path 49 | } 50 | 51 | func (m *mockHTTPHandler) Method() string { 52 | return m.method 53 | } 54 | 55 | func (m *mockHTTPHandler) Handler() common.HTTPRequestHandler { 56 | return func(writer http.ResponseWriter, request *http.Request) {} 57 | } 58 | -------------------------------------------------------------------------------- /pkg/internal/cacheutil/cacheutil.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package cacheutil 8 | 9 | import ( 10 | "fmt" 11 | "time" 12 | 13 | "github.com/bluele/gcache" 14 | ) 15 | 16 | // Cacheable interface has to implemented by objects in the cache. 17 | type Cacheable interface { 18 | CacheLifetime() (time.Duration, error) 19 | } 20 | 21 | // GetNewCacheable uses fetcher function to retrieve object. 22 | func GetNewCacheable( 23 | fetcher func(key string) (Cacheable, error), 24 | ) func(key string) (interface{}, *time.Duration, error) { 25 | return func(key string) (interface{}, *time.Duration, error) { 26 | data, err := fetcher(key) 27 | if err != nil { 28 | return nil, nil, fmt.Errorf("fetching cacheable object: %w", err) 29 | } 30 | 31 | expiryTime, err := data.CacheLifetime() 32 | if err != nil { 33 | return nil, nil, fmt.Errorf("failed to get object expiry time: %w", err) 34 | } 35 | 36 | return data, &expiryTime, nil 37 | } 38 | } 39 | 40 | // MakeCache is helper function to create cache with string keys. 41 | func MakeCache(fetcher func(key string) (interface{}, *time.Duration, error)) gcache.Cache { 42 | return gcache.New(0).LoaderExpireFunc(func(key interface{}) (interface{}, *time.Duration, error) { 43 | r, ok := key.(string) 44 | if !ok { 45 | return nil, nil, fmt.Errorf("key must be string") 46 | } 47 | 48 | return fetcher(r) 49 | }).Build() 50 | } 51 | -------------------------------------------------------------------------------- /pkg/lifecycle/lifecycle_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package lifecycle 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestLifecycle(t *testing.T) { 16 | started := false 17 | stopped := false 18 | 19 | lc := New( 20 | "service1", 21 | WithStart(func() { 22 | started = true 23 | }), 24 | WithStop(func() { 25 | stopped = true 26 | }), 27 | ) 28 | require.NotNil(t, lc) 29 | 30 | require.Equal(t, StateNotStarted, lc.State()) 31 | 32 | lc.Start() 33 | require.True(t, started) 34 | require.Equal(t, StateStarted, lc.State()) 35 | 36 | require.NotPanics(t, lc.Start) 37 | 38 | lc.Stop() 39 | require.True(t, stopped) 40 | require.Equal(t, StateStopped, lc.State()) 41 | 42 | require.NotPanics(t, lc.Stop) 43 | } 44 | -------------------------------------------------------------------------------- /pkg/nodeinfo/metadata.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package nodeinfo 8 | 9 | // Following are variables set during the build with ldflags: 10 | 11 | // OrbVersion contains the version of the Orb build. 12 | var OrbVersion = "latest" 13 | -------------------------------------------------------------------------------- /pkg/nodeinfo/model.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package nodeinfo 8 | 9 | const ( 10 | activityPubProtocol = "activitypub" 11 | orbRepository = "https://github.com/trustbloc/orb" 12 | ) 13 | 14 | // Version specified the version of the NodeInfo data. 15 | type Version = string 16 | 17 | const ( 18 | // V2_0 is NodeInfo version 2.0 (http://nodeinfo.diaspora.software/ns/schema/2.0#). 19 | V2_0 Version = "2.0" 20 | 21 | // V2_1 is NodeInfo version 2.1 (http://nodeinfo.diaspora.software/ns/schema/2.1#). 22 | V2_1 Version = "2.1" 23 | ) 24 | 25 | // NodeInfo contains NodeInfo data. 26 | type NodeInfo struct { 27 | Version string `json:"version"` 28 | Software Software `json:"software"` 29 | Protocols []string `json:"protocols"` 30 | Services Services `json:"services"` 31 | OpenRegistrations bool `json:"openRegistrations"` 32 | Usage Usage `json:"usage"` 33 | Metadata map[string]interface{} `json:"metadata,omitempty"` 34 | } 35 | 36 | // Software contains information about the Orb application, including version. 37 | type Software struct { 38 | Name string `json:"name"` 39 | Version string `json:"version"` 40 | Repository string `json:"repository,omitempty"` 41 | } 42 | 43 | // Services contains services. (Currently Orb does not use this object.) 44 | type Services struct { 45 | Inbound []string `json:"inbound"` 46 | Outbound []string `json:"outbound"` 47 | } 48 | 49 | // Usage contains usage statistics, including the number of 'Create' and 'Like' activities were issued by this node. 50 | type Usage struct { 51 | Users Users `json:"users"` 52 | LocalPosts int `json:"localPosts"` 53 | LocalComments int `json:"localComments"` 54 | } 55 | 56 | // Users contains the number of users. (Currently always 1.) 57 | type Users struct { 58 | Total int `json:"total"` 59 | } 60 | -------------------------------------------------------------------------------- /pkg/nodeinfo/openapi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package nodeinfo 7 | 8 | // nodeInfo20Req model 9 | // 10 | // swagger:parameters nodeInfo20Req 11 | type nodeInfo20Req struct{} //nolint: unused 12 | 13 | // nodeInfo20Resp model 14 | // 15 | // swagger:response nodeInfo20Resp 16 | type nodeInfo20Resp struct { //nolint: unused 17 | // in: body 18 | Body *NodeInfo 19 | } 20 | 21 | // handle swagger:route Get /nodeinfo/2.0 System nodeInfo20Req 22 | // 23 | // The NodeInfo endpoints provide general information about an Orb server, including the version, the number of posts (Create activities) and the number of comments (Like activities). This endpoint returns a version 2.0 response. 24 | // 25 | // Responses: 26 | // 27 | // 200: nodeInfo20Resp 28 | // 29 | //nolint:lll 30 | func (h *Handler) nodeInfo20GetReq() { //nolint: unused 31 | } 32 | 33 | // nodeInfo21Req model 34 | // 35 | // swagger:parameters nodeInfo21Req 36 | type nodeInfo21Req struct{} //nolint: unused 37 | 38 | // nodeInfo21Resp model 39 | // 40 | // swagger:response nodeInfo21Resp 41 | type nodeInfo21Resp struct { //nolint: unused 42 | // in: body 43 | Body *NodeInfo 44 | } 45 | 46 | // handle swagger:route Get /nodeinfo/2.1 System nodeInfo21Req 47 | // 48 | // The NodeInfo endpoints provide general information about an Orb server, including the version, the number of posts (Create activities) and the number of comments (Like activities). This endpoint returns a version 2.1 response. 49 | // 50 | // Responses: 51 | // 52 | // 200: nodeInfo21Resp 53 | // 54 | //nolint:lll 55 | func (h *Handler) nodeInfo21GetReq() { //nolint: unused 56 | } 57 | -------------------------------------------------------------------------------- /pkg/observability/loglevels/openapi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package loglevels 8 | 9 | // Request message 10 | // 11 | // swagger:parameters loglevelsPostReq 12 | type loglevelsPostReq struct { //nolint: unused 13 | // in: body 14 | Body string 15 | } 16 | 17 | // Response message 18 | // 19 | // swagger:response loglevelsPostResp 20 | type loglevelsPostResp struct { //nolint: unused 21 | Body string 22 | } 23 | 24 | // handlePost swagger:route POST /loglevels System loglevelsPostReq 25 | // 26 | // Updates the logging levels. 27 | // 28 | // Consumes: 29 | // - text/plain 30 | // 31 | // Produces: 32 | // - text/plain 33 | // 34 | // Responses: 35 | // 36 | // 200: loglevelsPostResp 37 | func loglevelsPostRequest() { //nolint: unused 38 | } 39 | 40 | // swagger:parameters loglevelsGetReq 41 | type loglevelsGetReq struct { //nolint: unused 42 | } 43 | 44 | // swagger:response loglevelsGetResp 45 | type loglevelsGetResp struct { //nolint: unused 46 | // in: body 47 | Body string 48 | } 49 | 50 | // loglevelsGetRequest swagger:route GET /loglevels System loglevelsGetReq 51 | // 52 | // Retrieves the logging levels. 53 | // 54 | // Produces: 55 | // - text/plain 56 | // 57 | // Responses: 58 | // 59 | // 200: loglevelsGetResp 60 | func loglevelsGetRequest() { //nolint: unused 61 | } 62 | -------------------------------------------------------------------------------- /pkg/observability/metrics/prometheus/handler.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package prometheus 8 | 9 | import ( 10 | "net/http" 11 | 12 | "github.com/prometheus/client_golang/prometheus" 13 | "github.com/prometheus/client_golang/prometheus/promhttp" 14 | "github.com/trustbloc/sidetree-svc-go/pkg/restapi/common" 15 | ) 16 | 17 | // Handler implements a Prometheus /metrics endpoint. 18 | type Handler struct{} 19 | 20 | // NewHandler returns a new /metrics endpoint which returns Prometheus formatted statistics. 21 | func NewHandler() *Handler { 22 | return &Handler{} 23 | } 24 | 25 | // Path returns the base path of the target URL for this Handler. 26 | func (h *Handler) Path() string { 27 | return "/metrics" 28 | } 29 | 30 | // Method returns the HTTP method, which is always GET. 31 | func (h *Handler) Method() string { 32 | return http.MethodGet 33 | } 34 | 35 | // Handler returns the Handler that should be invoked when an HTTP GET is requested to the target endpoint. 36 | // This Handler must be registered with an HTTP server. 37 | func (h *Handler) Handler() common.HTTPRequestHandler { 38 | ph := promhttp.HandlerFor(prometheus.DefaultGatherer, 39 | promhttp.HandlerOpts{ 40 | // Opt into OpenMetrics to support exemplars. 41 | EnableOpenMetrics: true, 42 | }, 43 | ) 44 | 45 | return func(writer http.ResponseWriter, request *http.Request) { 46 | ph.ServeHTTP(writer, request) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /pkg/observability/metrics/prometheus/handler_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package prometheus 8 | 9 | import ( 10 | "net/http" 11 | "testing" 12 | 13 | "github.com/stretchr/testify/require" 14 | ) 15 | 16 | func TestNewHandler(t *testing.T) { 17 | h := NewHandler() 18 | require.NotNil(t, h) 19 | require.Equal(t, "/metrics", h.Path()) 20 | require.Equal(t, http.MethodGet, h.Method()) 21 | require.NotNil(t, h.Handler()) 22 | } 23 | -------------------------------------------------------------------------------- /pkg/observability/metrics/prometheus/openapi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package prometheus 8 | 9 | // swagger:parameters metricsGetReq 10 | type metricsGetReq struct { //nolint: unused 11 | } 12 | 13 | // swagger:response metricsGetResp 14 | type metricsGetResp struct { //nolint: unused 15 | Body string 16 | } 17 | 18 | // getMetrics swagger:route GET /metrics System metricsGetReq 19 | // 20 | // Retrieves the current witness metrics. 21 | // 22 | // Responses: 23 | // 24 | // 200: metricsGetResp 25 | func getMetrics() { //nolint: unused 26 | } 27 | -------------------------------------------------------------------------------- /pkg/orbclient/protocol/nsprovider/namespaceprovider.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package nsprovider 8 | 9 | import ( 10 | "fmt" 11 | "sync" 12 | 13 | "github.com/trustbloc/sidetree-svc-go/pkg/api/protocol" 14 | ) 15 | 16 | // New creates new client version provider per namespace. 17 | func New() *Provider { 18 | return &Provider{clients: make(map[string]ClientVersionProvider)} 19 | } 20 | 21 | // ClientVersionProvider defines interface for accessing protocol version information. 22 | type ClientVersionProvider interface { 23 | // Current returns latest client version. 24 | Current() (protocol.Version, error) 25 | 26 | // Get returns the client version at the given transaction time. 27 | Get(transactionTime uint64) (protocol.Version, error) 28 | } 29 | 30 | // Provider implements client version provider per namespace. 31 | type Provider struct { 32 | mutex sync.RWMutex 33 | clients map[string]ClientVersionProvider 34 | } 35 | 36 | // Add adds client version provider for namespace. 37 | func (m *Provider) Add(namespace string, cvp ClientVersionProvider) { 38 | m.mutex.Lock() 39 | defer m.mutex.Unlock() 40 | 41 | m.clients[namespace] = cvp 42 | } 43 | 44 | // ForNamespace will return client version provider for that namespace. 45 | func (m *Provider) ForNamespace(namespace string) (ClientVersionProvider, error) { 46 | m.mutex.RLock() 47 | defer m.mutex.RUnlock() 48 | 49 | cvp, ok := m.clients[namespace] 50 | if !ok { 51 | return nil, fmt.Errorf("client version(s) not defined for namespace: %s", namespace) 52 | } 53 | 54 | return cvp, nil 55 | } 56 | -------------------------------------------------------------------------------- /pkg/orbclient/protocol/nsprovider/namespaceprovider_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package nsprovider 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | "github.com/trustbloc/sidetree-go/pkg/api/protocol" 14 | svcprotocol "github.com/trustbloc/sidetree-svc-go/pkg/api/protocol" 15 | "github.com/trustbloc/sidetree-svc-go/pkg/mocks" 16 | 17 | "github.com/trustbloc/orb/pkg/orbclient/protocol/verprovider" 18 | ) 19 | 20 | const ns = "did:orb" 21 | 22 | //go:generate counterfeiter -o ./../../mocks/clientversionprovider.gen.go --fake-name ClientVersionProvider . ClientVersionProvider 23 | 24 | func TestNew(t *testing.T) { 25 | p := New() 26 | require.NotNil(t, p) 27 | } 28 | 29 | func TestClientProvider_ForNamespace(t *testing.T) { 30 | v1_0 := &mocks.ProtocolVersion{} 31 | v1_0.ProtocolReturns(protocol.Protocol{ 32 | GenesisTime: 0, 33 | MaxOperationCount: 10, 34 | }) 35 | 36 | versions := []svcprotocol.Version{v1_0} 37 | 38 | p := New() 39 | require.NotNil(t, p) 40 | 41 | verProvider, err := verprovider.New(versions) 42 | require.NoError(t, err) 43 | 44 | p.Add(ns, verProvider) 45 | 46 | t.Run("success", func(t *testing.T) { 47 | vp, err := p.ForNamespace(ns) 48 | require.NoError(t, err) 49 | require.NotNil(t, vp) 50 | 51 | cur, err := vp.Current() 52 | require.NoError(t, err) 53 | require.Equal(t, uint(10), cur.Protocol().MaxOperationCount) 54 | }) 55 | 56 | t.Run("error - client versions not found for namespace", func(t *testing.T) { 57 | vp, err := p.ForNamespace("invalid") 58 | require.Error(t, err) 59 | require.Nil(t, vp) 60 | require.Contains(t, err.Error(), "client version(s) not defined for namespace: invalid") 61 | }) 62 | } 63 | -------------------------------------------------------------------------------- /pkg/protocolversion/clientregistry/clientregistry_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package clientregistry 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | mocks2 "github.com/trustbloc/sidetree-svc-go/pkg/mocks" 14 | 15 | "github.com/trustbloc/orb/pkg/config" 16 | crmocks "github.com/trustbloc/orb/pkg/protocolversion/clientregistry/mocks" 17 | "github.com/trustbloc/orb/pkg/protocolversion/mocks" 18 | ) 19 | 20 | //go:generate counterfeiter -o ./mocks/clientfactory.gen.go --fake-name ClientFactory . factory 21 | 22 | func TestRegistry(t *testing.T) { 23 | const version = "0.1" 24 | 25 | f := &crmocks.ClientFactory{} 26 | f.CreateReturns(&mocks2.ProtocolVersion{}, nil) 27 | 28 | r := New() 29 | 30 | require.NotPanics(t, func() { r.Register(version, f) }) 31 | require.PanicsWithError(t, "client version factory [0.1] already registered", func() { r.Register(version, f) }) 32 | 33 | casClient := &mocks.CasClient{} 34 | 35 | pv, err := r.CreateClientVersion(version, casClient, &config.Sidetree{}) 36 | require.NoError(t, err) 37 | require.NotNil(t, pv) 38 | 39 | pv, err = r.CreateClientVersion("99", casClient, &config.Sidetree{}) 40 | require.EqualError(t, err, "client version factory for version [99] not found") 41 | require.Nil(t, pv) 42 | } 43 | -------------------------------------------------------------------------------- /pkg/protocolversion/clientregistry/testversions.go: -------------------------------------------------------------------------------- 1 | //go:build testver 2 | // +build testver 3 | 4 | /* 5 | Copyright SecureKey Technologies Inc. All Rights Reserved. 6 | 7 | SPDX-License-Identifier: Apache-2.0 8 | */ 9 | 10 | package clientregistry 11 | 12 | import ( 13 | v_test "github.com/trustbloc/orb/pkg/protocolversion/versions/test/v_test/client" 14 | v1_0 "github.com/trustbloc/orb/pkg/protocolversion/versions/v1_0/client" 15 | ) 16 | 17 | const ( 18 | // V1_0 ... 19 | V1_0 = "1.0" 20 | 21 | test = "test" 22 | ) 23 | 24 | func addVersions(registry *Registry) { 25 | // register supported versions 26 | registry.Register(V1_0, v1_0.New()) 27 | 28 | // used for test only 29 | registry.Register(test, v_test.New()) 30 | } 31 | -------------------------------------------------------------------------------- /pkg/protocolversion/clientregistry/versions.go: -------------------------------------------------------------------------------- 1 | //go:build !testver 2 | // +build !testver 3 | 4 | /* 5 | Copyright SecureKey Technologies Inc. All Rights Reserved. 6 | 7 | SPDX-License-Identifier: Apache-2.0 8 | */ 9 | 10 | package clientregistry 11 | 12 | import v1_0 "github.com/trustbloc/orb/pkg/protocolversion/versions/v1_0/client" 13 | 14 | const ( 15 | // V1_0 ... 16 | V1_0 = "1.0" 17 | ) 18 | 19 | func addVersions(registry *Registry) { 20 | // register supported versions 21 | registry.Register(V1_0, v1_0.New()) 22 | } 23 | -------------------------------------------------------------------------------- /pkg/protocolversion/common/version.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package common 8 | 9 | import ( 10 | "errors" 11 | "strings" 12 | ) 13 | 14 | // Version represents the protocol version string. 15 | type Version string 16 | 17 | // Matches returns true if the major and minor versions match. For example: 18 | // 19 | // 'v1' and 'v1.2.0' => false 20 | // 'v1' and 'v1.0.0' => true 21 | // 'v1' and 'v1.0.1' => true 22 | // 'v1.0' and 'v1.0.1' => true 23 | // 'v1.1' and 'v1.1.4' => true 24 | // 'v1.1' and 'v1.2.0' => false. 25 | func (v Version) Matches(other string) bool { 26 | p1 := strings.Split(string(v), ".") 27 | p2 := strings.Split(other, ".") 28 | 29 | var majorVersion1 string 30 | 31 | minorVersion1 := "0" 32 | 33 | var majorVersion2 string 34 | 35 | minorVersion2 := "0" 36 | 37 | if len(p1) > 0 { 38 | majorVersion1 = p1[0] 39 | } 40 | 41 | if len(p1) > 1 { 42 | minorVersion1 = p1[1] 43 | } 44 | 45 | if len(p2) > 0 { 46 | majorVersion2 = p2[0] 47 | } 48 | 49 | if len(p2) > 1 { 50 | minorVersion2 = p2[1] 51 | } 52 | 53 | return majorVersion1 == majorVersion2 && minorVersion1 == minorVersion2 54 | } 55 | 56 | // Validate validates the format of the version string. 57 | func (v Version) Validate() error { 58 | p := strings.Split(string(v), ".") 59 | 60 | if len(p) == 0 || p[0] == "" { 61 | return errors.New("no version specified") 62 | } 63 | 64 | const v2 = 2 65 | 66 | if len(p) > v2 { 67 | return errors.New("version must only have a major and optional minor part (e.g. v1 or v1.1)") 68 | } 69 | 70 | return nil 71 | } 72 | -------------------------------------------------------------------------------- /pkg/protocolversion/common/version_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package common 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestCcVersion_Matches(t *testing.T) { 16 | v1 := Version("v1") 17 | v1_0 := Version("v1.0") 18 | v1_1 := Version("v1.1") 19 | v1_2 := Version("v1.2") 20 | 21 | require.True(t, v1.Matches("v1.0.0")) 22 | require.True(t, v1.Matches("v1.0.1")) 23 | require.True(t, v1_0.Matches("v1.0.1")) 24 | require.False(t, v1.Matches("v1.2.1")) 25 | require.True(t, v1_2.Matches("v1.2.1")) 26 | require.False(t, v1_1.Matches("v1.2.0")) 27 | } 28 | 29 | func TestCcVersion_Validate(t *testing.T) { 30 | v := Version("") 31 | v1 := Version("v1") 32 | v1_0 := Version("v1.0") 33 | v1_0_0 := Version("v1.0.0") 34 | 35 | require.EqualError(t, v.Validate(), "no version specified") 36 | require.NoError(t, v1.Validate()) 37 | require.NoError(t, v1_0.Validate()) 38 | require.EqualError(t, v1_0_0.Validate(), "version must only have a major and optional minor part (e.g. v1 or v1.1)") 39 | } 40 | -------------------------------------------------------------------------------- /pkg/protocolversion/factoryregistry/testversions.go: -------------------------------------------------------------------------------- 1 | //go:build testver 2 | // +build testver 3 | 4 | /* 5 | Copyright SecureKey Technologies Inc. All Rights Reserved. 6 | 7 | SPDX-License-Identifier: Apache-2.0 8 | */ 9 | 10 | package factoryregistry 11 | 12 | import ( 13 | v_test "github.com/trustbloc/orb/pkg/protocolversion/versions/test/v_test/factory" 14 | v1_0 "github.com/trustbloc/orb/pkg/protocolversion/versions/v1_0/factory" 15 | ) 16 | 17 | const ( 18 | // V1_0 ... 19 | V1_0 = "1.0" 20 | 21 | test = "test" 22 | ) 23 | 24 | func addVersions(registry *Registry) { 25 | // register supported versions 26 | registry.Register(V1_0, v1_0.New(false)) 27 | 28 | // used for test only 29 | registry.Register(test, v_test.New()) 30 | } 31 | -------------------------------------------------------------------------------- /pkg/protocolversion/factoryregistry/versions.go: -------------------------------------------------------------------------------- 1 | //go:build !testver 2 | // +build !testver 3 | 4 | /* 5 | Copyright SecureKey Technologies Inc. All Rights Reserved. 6 | 7 | SPDX-License-Identifier: Apache-2.0 8 | */ 9 | 10 | package factoryregistry 11 | 12 | import v1_0 "github.com/trustbloc/orb/pkg/protocolversion/versions/v1_0/factory" 13 | 14 | const ( 15 | // V1_0 ... 16 | V1_0 = "1.0" 17 | ) 18 | 19 | func addVersions(registry *Registry) { 20 | // register supported versions 21 | registry.Register(V1_0, v1_0.New(registry.noTLS)) 22 | } 23 | -------------------------------------------------------------------------------- /pkg/protocolversion/mocks/allowedoriginstore.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package mocks 8 | 9 | import ( 10 | "net/url" 11 | 12 | "github.com/trustbloc/orb/pkg/internal/testutil" 13 | ) 14 | 15 | // AllowedOriginsStore is a mock, allowed origins store. 16 | type AllowedOriginsStore struct { 17 | allowedOrigins []*url.URL 18 | err error 19 | } 20 | 21 | // NewAllowedOriginsStore returns a mock, allowed origins store. 22 | func NewAllowedOriginsStore() *AllowedOriginsStore { 23 | return &AllowedOriginsStore{} 24 | } 25 | 26 | // FromString initializes the origin URIs from the given strings. 27 | func (m *AllowedOriginsStore) FromString(values ...string) *AllowedOriginsStore { 28 | m.allowedOrigins = make([]*url.URL, len(values)) 29 | 30 | for i, origin := range values { 31 | m.allowedOrigins[i] = testutil.MustParseURL(origin) 32 | } 33 | 34 | return m 35 | } 36 | 37 | // WithError sets an error for testing. 38 | func (m *AllowedOriginsStore) WithError(err error) *AllowedOriginsStore { 39 | m.err = err 40 | 41 | return m 42 | } 43 | 44 | // Get returns the anchor origins or an error. 45 | func (m *AllowedOriginsStore) Get() ([]*url.URL, error) { 46 | if m.err != nil { 47 | return nil, m.err 48 | } 49 | 50 | return m.allowedOrigins, nil 51 | } 52 | -------------------------------------------------------------------------------- /pkg/protocolversion/versions/common/protocol_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package common 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | "github.com/trustbloc/sidetree-go/pkg/api/protocol" 14 | coremocks "github.com/trustbloc/sidetree-go/pkg/mocks" 15 | "github.com/trustbloc/sidetree-svc-go/pkg/mocks" 16 | ) 17 | 18 | func TestProtocolVersion(t *testing.T) { 19 | p := &ProtocolVersion{ 20 | VersionStr: "1.1", 21 | P: protocol.Protocol{ 22 | GenesisTime: 1000, 23 | }, 24 | TxnProcessor: &mocks.TxnProcessor{}, 25 | OpParser: &coremocks.OperationParser{}, 26 | OpApplier: &coremocks.OperationApplier{}, 27 | DocComposer: &coremocks.DocumentComposer{}, 28 | OpHandler: &mocks.OperationHandler{}, 29 | OpProvider: &mocks.OperationProvider{}, 30 | DocValidator: &mocks.MockDocumentValidator{}, 31 | } 32 | 33 | require.Equal(t, p.VersionStr, p.Version()) 34 | require.Equal(t, p.P, p.Protocol()) 35 | require.Equal(t, p.TxnProcessor, p.TransactionProcessor()) 36 | require.Equal(t, p.OpParser, p.OperationParser()) 37 | require.Equal(t, p.OpApplier, p.OperationApplier()) 38 | require.Equal(t, p.DocComposer, p.DocumentComposer()) 39 | require.Equal(t, p.OpHandler, p.OperationHandler()) 40 | require.Equal(t, p.OpProvider, p.OperationProvider()) 41 | require.Equal(t, p.DocValidator, p.DocumentValidator()) 42 | } 43 | -------------------------------------------------------------------------------- /pkg/protocolversion/versions/test/v_test/client/client_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package client 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | 14 | "github.com/trustbloc/orb/pkg/config" 15 | "github.com/trustbloc/orb/pkg/protocolversion/mocks" 16 | ) 17 | 18 | func TestFactory_Create(t *testing.T) { 19 | f := New() 20 | require.NotNil(t, f) 21 | 22 | casClient := &mocks.CasClient{} 23 | 24 | t.Run("success", func(t *testing.T) { 25 | pv, err := f.Create("test", casClient, &config.Sidetree{}) 26 | require.NoError(t, err) 27 | require.NotNil(t, pv) 28 | }) 29 | } 30 | -------------------------------------------------------------------------------- /pkg/protocolversion/versions/test/v_test/config/protocol.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package config 8 | 9 | import ( 10 | "github.com/trustbloc/sidetree-go/pkg/api/protocol" 11 | ) 12 | 13 | // GetProtocolConfig returns protocol config for test version. 14 | func GetProtocolConfig() protocol.Protocol { 15 | p := protocol.Protocol{ 16 | GenesisTime: 777, 17 | MultihashAlgorithms: []uint{18}, 18 | MaxOperationCount: 10000, 19 | MaxOperationSize: 1700, 20 | MaxOperationHashLength: 100, 21 | MaxDeltaSize: 1500, 22 | MaxCasURILength: 500, 23 | CompressionAlgorithm: "GZIP", 24 | MaxChunkFileSize: 10000000, 25 | MaxProvisionalIndexFileSize: 1000000, 26 | MaxCoreIndexFileSize: 1000000, 27 | MaxProofFileSize: 2500000, 28 | Patches: []string{"add-public-keys", "remove-public-keys", "add-services", "remove-services", "add-also-known-as", "remove-also-known-as"}, //nolint:lll 29 | SignatureAlgorithms: []string{"EdDSA", "ES256", "ES256K"}, 30 | KeyAlgorithms: []string{"Ed25519", "P-256", "secp256k1"}, 31 | MaxMemoryDecompressionFactor: 3, 32 | NonceSize: 16, 33 | } 34 | 35 | return p 36 | } 37 | -------------------------------------------------------------------------------- /pkg/protocolversion/versions/test/v_test/config/protocol_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package config 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestGetProtocolConfig(t *testing.T) { 16 | t.Run("success", func(t *testing.T) { 17 | cfg := GetProtocolConfig() 18 | require.Equal(t, uint(10000), cfg.MaxOperationCount) 19 | }) 20 | } 21 | -------------------------------------------------------------------------------- /pkg/protocolversion/versions/v1_0/client/client_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package client 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | 14 | "github.com/trustbloc/orb/pkg/config" 15 | "github.com/trustbloc/orb/pkg/protocolversion/mocks" 16 | ) 17 | 18 | func TestFactory_Create(t *testing.T) { 19 | f := New() 20 | require.NotNil(t, f) 21 | 22 | casClient := &mocks.CasClient{} 23 | 24 | t.Run("success", func(t *testing.T) { 25 | pv, err := f.Create("1.0", casClient, &config.Sidetree{}) 26 | require.NoError(t, err) 27 | require.NotNil(t, pv) 28 | }) 29 | } 30 | -------------------------------------------------------------------------------- /pkg/protocolversion/versions/v1_0/config/protocol.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package config 8 | 9 | import ( 10 | "github.com/trustbloc/sidetree-go/pkg/api/protocol" 11 | ) 12 | 13 | // GetProtocolConfig returns protocol config for this version. 14 | func GetProtocolConfig() protocol.Protocol { 15 | p := protocol.Protocol{ 16 | GenesisTime: 0, 17 | MultihashAlgorithms: []uint{18}, 18 | MaxOperationCount: 10000, 19 | MaxOperationSize: 2500, 20 | MaxOperationHashLength: 100, 21 | MaxDeltaSize: 1700, 22 | MaxCasURILength: 500, 23 | CompressionAlgorithm: "GZIP", 24 | MaxChunkFileSize: 10000000, 25 | MaxProvisionalIndexFileSize: 1000000, 26 | MaxCoreIndexFileSize: 1000000, 27 | MaxProofFileSize: 2500000, 28 | Patches: []string{"add-public-keys", "remove-public-keys", "add-services", "remove-services", "add-also-known-as", "remove-also-known-as"}, //nolint:lll 29 | SignatureAlgorithms: []string{"EdDSA", "ES256", "ES256K"}, 30 | KeyAlgorithms: []string{"Ed25519", "P-256", "P-384", "secp256k1"}, 31 | MaxMemoryDecompressionFactor: 3, 32 | NonceSize: 16, 33 | } 34 | 35 | return p 36 | } 37 | -------------------------------------------------------------------------------- /pkg/protocolversion/versions/v1_0/config/protocol_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package config 8 | 9 | import ( 10 | "testing" 11 | 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestGetProtocolConfig(t *testing.T) { 16 | t.Run("success - maximum operation count", func(t *testing.T) { 17 | cfg := GetProtocolConfig() 18 | require.Equal(t, uint(10000), cfg.MaxOperationCount) 19 | }) 20 | 21 | t.Run("success - key algorithms", func(t *testing.T) { 22 | cfg := GetProtocolConfig() 23 | require.Equal(t, []string{"Ed25519", "P-256", "P-384", "secp256k1"}, cfg.KeyAlgorithms) 24 | }) 25 | } 26 | -------------------------------------------------------------------------------- /pkg/pubsub/amqp/pooledsubscriber_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package amqp 8 | 9 | import ( 10 | "context" 11 | "errors" 12 | "testing" 13 | "time" 14 | 15 | "github.com/ThreeDotsLabs/watermill/message" 16 | "github.com/stretchr/testify/require" 17 | 18 | "github.com/trustbloc/orb/pkg/mocks" 19 | ) 20 | 21 | func TestPooledSubscriber(t *testing.T) { 22 | const topic = "pooled" 23 | 24 | t.Run("Subscriber -> error", func(t *testing.T) { 25 | s := &mocks.PubSub{} 26 | 27 | errExpected := errors.New("injected subscriber error") 28 | 29 | s.SubscribeReturns(nil, errExpected) 30 | 31 | _, err := newPooledSubscriber(context.Background(), 10, s, topic) 32 | require.Error(t, err) 33 | require.Contains(t, err.Error(), errExpected.Error()) 34 | }) 35 | 36 | t.Run("Start/Stop", func(t *testing.T) { 37 | msgChan := make(chan *message.Message) 38 | 39 | pubSub := &mocks.PubSub{} 40 | pubSub.SubscribeReturns(msgChan, nil) 41 | 42 | ps, err := newPooledSubscriber(context.Background(), 10, pubSub, topic) 43 | require.NoError(t, err) 44 | require.NotNil(t, ps) 45 | 46 | ps.start() 47 | 48 | time.Sleep(50 * time.Millisecond) 49 | 50 | ps.stop() 51 | }) 52 | } 53 | -------------------------------------------------------------------------------- /pkg/pubsub/pubsub.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. 3 | 4 | This file contains software code that is the intellectual property of SecureKey. 5 | SecureKey reserves all rights in the code and you may not use it without 6 | written permission from SecureKey. 7 | */ 8 | 9 | package pubsub 10 | 11 | import ( 12 | "context" 13 | 14 | "github.com/ThreeDotsLabs/watermill" 15 | "github.com/ThreeDotsLabs/watermill/message" 16 | "go.opentelemetry.io/otel" 17 | 18 | "github.com/trustbloc/orb/pkg/observability/tracing/otelamqp" 19 | ) 20 | 21 | // ContextFromMessage returns a new Context which may include OpenTelemetry tracing data. 22 | func ContextFromMessage(msg *message.Message) context.Context { 23 | return otel.GetTextMapPropagator().Extract(context.Background(), otelamqp.NewMessageCarrier(msg)) 24 | } 25 | 26 | // NewMessage creates a new message which may include OpenTelemetry tracing data in the header. 27 | func NewMessage(ctx context.Context, payload []byte) *message.Message { 28 | msg := message.NewMessage(watermill.NewUUID(), payload) 29 | 30 | InjectContext(ctx, msg) 31 | 32 | return msg 33 | } 34 | 35 | // InjectContext adds OpenTelemetry tracing data to the message header (if available). 36 | func InjectContext(ctx context.Context, msg *message.Message) { 37 | otel.GetTextMapPropagator().Inject(ctx, otelamqp.NewMessageCarrier(msg)) 38 | } 39 | -------------------------------------------------------------------------------- /pkg/pubsub/pubsub_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. 3 | 4 | This file contains software code that is the intellectual property of SecureKey. 5 | SecureKey reserves all rights in the code and you may not use it without 6 | written permission from SecureKey. 7 | */ 8 | 9 | package pubsub 10 | 11 | import ( 12 | "context" 13 | "testing" 14 | 15 | "github.com/stretchr/testify/require" 16 | "go.opentelemetry.io/otel" 17 | "go.opentelemetry.io/otel/trace" 18 | 19 | "github.com/trustbloc/orb/pkg/internal/testutil" 20 | ) 21 | 22 | func TestContextFromMessage(t *testing.T) { 23 | testutil.InitTracer(t) 24 | 25 | ctx, span := otel.GetTracerProvider().Tracer("test").Start(context.Background(), "span1") 26 | 27 | msg := NewMessage(ctx, []byte("payload")) 28 | 29 | require.Equal(t, span.SpanContext().SpanID(), trace.SpanFromContext(ContextFromMessage(msg)).SpanContext().SpanID()) 30 | } 31 | -------------------------------------------------------------------------------- /pkg/pubsub/spi/spi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package spi 8 | 9 | import "time" 10 | 11 | // UndeliverableTopic is the topic to which to post undeliverable messages. 12 | const UndeliverableTopic = "orb.undeliverable.activities" 13 | 14 | // Options contains publisher/subscriber options. 15 | type Options struct { 16 | PoolSize int 17 | DeliveryDelay time.Duration 18 | } 19 | 20 | // Option specifies a publisher/subscriber option. 21 | type Option func(option *Options) 22 | 23 | // WithPool sets the pool size. 24 | func WithPool(size int) Option { 25 | return func(option *Options) { 26 | option.PoolSize = size 27 | } 28 | } 29 | 30 | // WithDeliveryDelay sets the delivery delay. 31 | // Note: Not all message brokers support this option. 32 | func WithDeliveryDelay(delay time.Duration) Option { 33 | return func(option *Options) { 34 | option.DeliveryDelay = delay 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /pkg/util/util.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package util 8 | 9 | import ( 10 | "crypto/ecdsa" 11 | "crypto/elliptic" 12 | "crypto/x509" 13 | "encoding/pem" 14 | "fmt" 15 | "strings" 16 | 17 | "github.com/hyperledger/aries-framework-go/pkg/kms" 18 | ) 19 | 20 | // EncodePublicKeyToPEM returns the PEM-encoding of the given public key. 21 | func EncodePublicKeyToPEM(pubKeyBytes []byte, keyType kms.KeyType) ([]byte, error) { 22 | keyBytes := pubKeyBytes 23 | 24 | pemKeyType := getPEMKeyType(keyType) 25 | 26 | if keyType == kms.ECDSAP256DER || keyType == kms.ECDSAP384DER || keyType == kms.ECDSAP521DER { 27 | curveMap := map[string]elliptic.Curve{ 28 | "P-256": elliptic.P256(), 29 | "P-384": elliptic.P384(), 30 | "P-521": elliptic.P521(), 31 | } 32 | 33 | key, err := x509.ParsePKIXPublicKey(pubKeyBytes) 34 | if err != nil { 35 | return nil, fmt.Errorf("parse PKIX public key: %w", err) 36 | } 37 | 38 | //nolint:forcetypeassert,staticcheck 39 | keyBytes = elliptic.Marshal(curveMap[pemKeyType], key.(*ecdsa.PublicKey).X, 40 | key.(*ecdsa.PublicKey).Y) 41 | } 42 | 43 | return pem.EncodeToMemory(&pem.Block{ 44 | Type: pemKeyType, 45 | Bytes: keyBytes, 46 | }), nil 47 | } 48 | 49 | func getPEMKeyType(keyType kms.KeyType) string { 50 | switch { 51 | case strings.HasPrefix(strings.ToUpper(string(keyType)), kms.ED25519): 52 | return "Ed25519" 53 | case keyType == kms.ECDSAP256IEEEP1363 || keyType == kms.ECDSAP256DER: 54 | return "P-256" 55 | case keyType == kms.ECDSAP384IEEEP1363 || keyType == kms.ECDSAP384DER: 56 | return "P-384" 57 | case keyType == kms.ECDSAP521IEEEP1363 || keyType == kms.ECDSAP521DER: 58 | return "P-521" 59 | default: 60 | return "" 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /pkg/util/util_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package util 8 | 9 | import ( 10 | "crypto/ecdsa" 11 | "crypto/elliptic" 12 | "crypto/rand" 13 | "testing" 14 | 15 | "github.com/hyperledger/aries-framework-go/pkg/kms" 16 | "github.com/stretchr/testify/require" 17 | ) 18 | 19 | func TestEncodePublicKeyToPEM(t *testing.T) { 20 | t.Run("ECDSAP384IEEEP1363 -> success", func(t *testing.T) { 21 | privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 22 | require.NoError(t, err) 23 | 24 | pubKey := elliptic.Marshal(elliptic.P256(), privKey.PublicKey.X, privKey.PublicKey.Y) //nolint:staticcheck 25 | 26 | pem, err := EncodePublicKeyToPEM(pubKey, kms.ECDSAP256IEEEP1363) 27 | require.NoError(t, err) 28 | require.NotNil(t, pem) 29 | }) 30 | 31 | t.Run("ED25519 -> success", func(t *testing.T) { 32 | pem, err := EncodePublicKeyToPEM(nil, kms.ED25519) 33 | require.NoError(t, err) 34 | require.NotNil(t, pem) 35 | }) 36 | 37 | t.Run("ECDSAP521IEEEP1363 -> success", func(t *testing.T) { 38 | pem, err := EncodePublicKeyToPEM(nil, kms.ECDSAP521IEEEP1363) 39 | require.NoError(t, err) 40 | require.NotNil(t, pem) 41 | }) 42 | 43 | t.Run("ECDSAP384IEEEP1363 -> success", func(t *testing.T) { 44 | pem, err := EncodePublicKeyToPEM(nil, kms.ECDSAP384IEEEP1363) 45 | require.NoError(t, err) 46 | require.NotNil(t, pem) 47 | }) 48 | 49 | t.Run("success", func(t *testing.T) { 50 | pem, err := EncodePublicKeyToPEM(nil, "") 51 | require.NoError(t, err) 52 | require.NotNil(t, pem) 53 | }) 54 | 55 | t.Run("ECDSAP256DER -> error", func(t *testing.T) { 56 | _, err := EncodePublicKeyToPEM(nil, kms.ECDSAP256DER) 57 | require.Error(t, err) 58 | }) 59 | } 60 | -------------------------------------------------------------------------------- /pkg/vct/logmonitoring/verifier/verifier.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package verifier 8 | 9 | import ( 10 | "github.com/google/trillian/merkle/logverifier" 11 | "github.com/transparency-dev/merkle/compact" 12 | "github.com/transparency-dev/merkle/rfc6962" 13 | "github.com/trustbloc/vct/pkg/controller/command" 14 | ) 15 | 16 | // LogVerifier wraps Trillian functionality for verifying consistency proof and getting root hash from entries. 17 | type LogVerifier struct{} 18 | 19 | // New returns new client for monitoring VCT log consistency. 20 | func New() *LogVerifier { 21 | return &LogVerifier{} 22 | } 23 | 24 | // GetRootHashFromEntries constructs Merkle tree from entries and calculates root hash. 25 | func (v *LogVerifier) GetRootHashFromEntries(entries []*command.LeafEntry) ([]byte, error) { 26 | hasher := rfc6962.DefaultHasher 27 | fact := compact.RangeFactory{Hash: hasher.HashChildren} 28 | cr := fact.NewEmptyRange(0) 29 | 30 | // We don't simply iterate the map, as we need to preserve the leaves order. 31 | for _, entry := range entries { 32 | err := cr.Append(hasher.HashLeaf(entry.LeafInput), nil) 33 | if err != nil { 34 | return nil, err 35 | } 36 | } 37 | 38 | return cr.GetRootHash(nil) 39 | } 40 | 41 | // VerifyConsistencyProof verifies consistency proof. 42 | func (v *LogVerifier) VerifyConsistencyProof(snapshot1, snapshot2 int64, root1, root2 []byte, proof [][]byte) error { 43 | logVerifier := logverifier.New(rfc6962.DefaultHasher) 44 | 45 | return logVerifier.VerifyConsistencyProof(snapshot1, snapshot2, root1, root2, proof) 46 | } 47 | -------------------------------------------------------------------------------- /pkg/vct/resthandler/openapi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package resthandler 8 | 9 | // swagger:parameters logGetReq 10 | type logGetReq struct { //nolint: unused 11 | } 12 | 13 | // swagger:response logGetResp 14 | type logGetResp struct { //nolint: unused 15 | Body string 16 | } 17 | 18 | // getLog swagger:route GET /log Log logGetReq 19 | // 20 | // Retrieves the current witness log. 21 | // 22 | // Responses: 23 | // 24 | // 200: logGetResp 25 | func getLog() { //nolint: unused 26 | } 27 | 28 | // swagger:parameters logPostReq 29 | type logPostReq struct { //nolint: unused 30 | // in: body 31 | Body string 32 | } 33 | 34 | // swagger:response logPostResp 35 | type logPostResp struct { //nolint: unused 36 | Body string 37 | } 38 | 39 | // postLog swagger:route Post /log Log logPostReq 40 | // 41 | // Sets the current witness log. 42 | // 43 | // Responses: 44 | // 45 | // 200: logPostResp 46 | func postLog() { //nolint: unused 47 | } 48 | -------------------------------------------------------------------------------- /pkg/versions/1_0/operationparser/validators/anchororigin/validator_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package anchororigin 8 | 9 | import ( 10 | "errors" 11 | "testing" 12 | "time" 13 | 14 | "github.com/stretchr/testify/require" 15 | 16 | "github.com/trustbloc/orb/pkg/protocolversion/mocks" 17 | ) 18 | 19 | func TestValidator_Validate(t *testing.T) { 20 | v := New(mocks.NewAllowedOriginsStore().FromString("*"), time.Second) 21 | 22 | t.Run("error - no anchor origin specified", func(t *testing.T) { 23 | err := v.Validate(nil) 24 | require.Error(t, err) 25 | require.Contains(t, err.Error(), "anchor origin must be specified") 26 | }) 27 | 28 | t.Run("success - allow all origins", func(t *testing.T) { 29 | err := v.Validate("test") 30 | require.NoError(t, err) 31 | }) 32 | 33 | t.Run("success - allowed origins specified", func(t *testing.T) { 34 | validator := New(mocks.NewAllowedOriginsStore().FromString("allowed"), time.Second) 35 | err := validator.Validate("allowed") 36 | require.NoError(t, err) 37 | }) 38 | 39 | t.Run("error - origin not in the allowed list", func(t *testing.T) { 40 | validator := New(mocks.NewAllowedOriginsStore().FromString("allowed"), time.Second) 41 | err := validator.Validate("not-allowed") 42 | require.Error(t, err) 43 | require.Contains(t, err.Error(), "origin not-allowed is not supported") 44 | }) 45 | } 46 | 47 | func TestValidator_ValidateError(t *testing.T) { 48 | t.Run("Store error", func(t *testing.T) { 49 | errExpected := errors.New("injected store error") 50 | 51 | v := New(mocks.NewAllowedOriginsStore().FromString("*").WithError(errExpected), time.Second) 52 | 53 | err := v.Validate("test") 54 | require.Error(t, err) 55 | require.Contains(t, err.Error(), errExpected.Error()) 56 | }) 57 | } 58 | -------------------------------------------------------------------------------- /pkg/versions/1_0/operationparser/validators/anchortime/validator.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package anchortime 8 | 9 | import ( 10 | "time" 11 | 12 | "github.com/trustbloc/sidetree-go/pkg/versions/1_0/operationparser" 13 | ) 14 | 15 | // New creates new anchor time validator. 16 | func New(maxDelta uint64) *Validator { 17 | return &Validator{maxDelta: maxDelta} 18 | } 19 | 20 | // Validator is used to validate anchor times (from, until) against server time. 21 | type Validator struct { 22 | maxDelta uint64 23 | } 24 | 25 | // Validate validates anchor times (from and until) against current time. 26 | func (v *Validator) Validate(from, until int64) error { 27 | if from == 0 && until == 0 { 28 | // from and until are not specified - no error 29 | return nil 30 | } 31 | 32 | serverTime := time.Now().Unix() 33 | 34 | if from > serverTime { 35 | return operationparser.ErrOperationEarly 36 | } 37 | 38 | if v.getAnchorUntil(from, until) <= serverTime { 39 | return operationparser.ErrOperationExpired 40 | } 41 | 42 | return nil 43 | } 44 | 45 | func (v *Validator) getAnchorUntil(from, until int64) int64 { 46 | if from != 0 && until == 0 { 47 | return from + int64(v.maxDelta) 48 | } 49 | 50 | return until 51 | } 52 | -------------------------------------------------------------------------------- /pkg/versions/1_0/operationparser/validators/anchortime/validator_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package anchortime 8 | 9 | import ( 10 | "testing" 11 | "time" 12 | 13 | "github.com/stretchr/testify/require" 14 | "github.com/trustbloc/sidetree-go/pkg/versions/1_0/operationparser" 15 | ) 16 | 17 | func TestValidator_Validate(t *testing.T) { 18 | const maxDelta = 10 * 60 19 | v := New(maxDelta) 20 | 21 | now := time.Now().Unix() 22 | 23 | const testDelta = 5 * 60 24 | 25 | t.Run("success - no anchoring times specified", func(t *testing.T) { 26 | err := v.Validate(0, 0) 27 | require.NoError(t, err) 28 | }) 29 | 30 | t.Run("success - anchoring times specified", func(t *testing.T) { 31 | err := v.Validate(now-testDelta, now+testDelta) 32 | require.NoError(t, err) 33 | }) 34 | 35 | t.Run("success - anchor until time is not specified (protocol op delta is used to calc until)", func(t *testing.T) { 36 | err := v.Validate(now-testDelta, 0) 37 | require.NoError(t, err) 38 | }) 39 | 40 | t.Run("error - anchor until time is not specified (delta is zero hence operation expired error)", func(t *testing.T) { 41 | v2 := New(0) 42 | err := v2.Validate(now-testDelta, 0) 43 | require.Equal(t, err, operationparser.ErrOperationExpired) 44 | }) 45 | 46 | t.Run("error - anchor from time is greater then anchoring time", func(t *testing.T) { 47 | err := v.Validate(now+testDelta, now+testDelta) 48 | require.Error(t, err) 49 | require.Equal(t, err, operationparser.ErrOperationEarly) 50 | }) 51 | 52 | t.Run("error - anchor until time is less then anchoring time", func(t *testing.T) { 53 | err := v.Validate(now-testDelta, now-testDelta) 54 | require.Error(t, err) 55 | require.Equal(t, err, operationparser.ErrOperationExpired) 56 | }) 57 | } 58 | -------------------------------------------------------------------------------- /pkg/webcas/openapi.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package webcas 8 | 9 | // swagger:parameters casGetReq 10 | type casGetReq struct { //nolint: unused 11 | // in: path 12 | ID string `json:"id"` 13 | } 14 | 15 | // swagger:response casGetResp 16 | type casGetResp struct { //nolint: unused 17 | Body string 18 | } 19 | 20 | // handleGet swagger:route GET /cas/{id} CAS casGetReq 21 | // 22 | // Returns content stored in the Content Addressable Storage (CAS). The ID is either an IPFS CID or the hash of the content. 23 | // 24 | // Responses: 25 | // 26 | // 200: casGetResp 27 | func casGetRequest() { //nolint: unused 28 | } 29 | -------------------------------------------------------------------------------- /pkg/webfinger/model/model.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package model 8 | 9 | import ( 10 | "fmt" 11 | ) 12 | 13 | // ErrResourceNotFound is an error type used to indicate that a given resource could not be found. 14 | var ErrResourceNotFound = fmt.Errorf("resource not found") 15 | -------------------------------------------------------------------------------- /samples/tutorial/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started Tutorial 2 | 3 | Please refer to the [Getting Started Tutorial](https://trustbloc.readthedocs.io/en/latest/orb/gettingstarted.html#getting-started-tutorial) 4 | on Read the Docs. 5 | -------------------------------------------------------------------------------- /samples/tutorial/cli.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 4 | # 5 | # SPDX-License-Identifier: Apache-2.0 6 | # 7 | 8 | set -e 9 | 10 | apt-get update 11 | apt-get --assume-yes install jq 12 | apt-get --assume-yes install curl 13 | sleep infinity 14 | -------------------------------------------------------------------------------- /samples/tutorial/create_publickeys.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "key1", 4 | "type": "Ed25519VerificationKey2018", 5 | "purposes": ["authentication"], 6 | "jwkPath": "jwk1.json" 7 | }, 8 | { 9 | "id": "key2", 10 | "type": "JsonWebKey2020", 11 | "purposes": ["authentication"], 12 | "jwkPath": "jwk2.json" 13 | } 14 | ] -------------------------------------------------------------------------------- /samples/tutorial/create_services.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "svc1", 4 | "type": "type1", 5 | "priority": 1, 6 | "recipientKeys": ["key1"], 7 | "serviceEndpoint": [ 8 | { 9 | "uri": "https://example.com", 10 | "routingKeys": ["key1"] 11 | } 12 | ] 13 | }, 14 | { 15 | "id": "svc2", 16 | "type": "type2", 17 | "priority": 2, 18 | "recipientKeys": ["key2"], 19 | "serviceEndpoint": [ 20 | { 21 | "uri": "https://example.com", 22 | "routingKeys": ["key2"] 23 | } 24 | ] 25 | } 26 | ] -------------------------------------------------------------------------------- /samples/tutorial/create_services2.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "svc3", 4 | "type": "type3", 5 | "priority": 1, 6 | "recipientKeys": ["key3"], 7 | "serviceEndpoint": [ 8 | { 9 | "uri": "https://example.com", 10 | "routingKeys": ["key3"] 11 | } 12 | ] 13 | } 14 | ] -------------------------------------------------------------------------------- /samples/tutorial/docker-compose-cli.yml: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | version: '2' 7 | 8 | services: 9 | cli: 10 | container_name: cli 11 | image: ubuntu 12 | restart: on-failure 13 | command: /orb/cli.sh 14 | volumes: 15 | - ../../.build/extract/orb-cli-linux-amd64:/usr/local/sbin/orb-cli 16 | - .:/orb 17 | networks: 18 | - "orbnet" 19 | -------------------------------------------------------------------------------- /samples/tutorial/jwk1.json: -------------------------------------------------------------------------------- 1 | { 2 | "kty":"OKP", 3 | "crv":"Ed25519", 4 | "x":"o1bG1U7G3CNbtALMafUiFOq8ODraTyVTmPtRDO1QUWg", 5 | "y":"" 6 | } -------------------------------------------------------------------------------- /samples/tutorial/jwk2.json: -------------------------------------------------------------------------------- 1 | { 2 | "kty":"EC", 3 | "crv":"P-256", 4 | "x":"bGM9aNufpKNPxlkyacU1hGhQXm_aC8hIzSVeKDpwjBw", 5 | "y":"PfdmCOtIdVY2B6ucR4oQkt6evQddYhOyHoDYCaI2BJA" 6 | } -------------------------------------------------------------------------------- /samples/tutorial/jwk3.json: -------------------------------------------------------------------------------- 1 | { 2 | "kty":"OKP", 3 | "crv":"Ed25519", 4 | "x":"o1bG1U7G3CNbtALMafUiFOq8ODraTyVTmPtRDO1QUWg", 5 | "y":"" 6 | } -------------------------------------------------------------------------------- /samples/tutorial/jwk4.json: -------------------------------------------------------------------------------- 1 | { 2 | "kty":"EC", 3 | "crv":"P-256", 4 | "x":"bGM9aNufpKNPxlkyacU1hGhQXm_aC8hIzSVeKDpwjBw", 5 | "y":"PfdmCOtIdVY2B6ucR4oQkt6evQddYhOyHoDYCaI2BJA" 6 | } -------------------------------------------------------------------------------- /samples/tutorial/nextupdate_publickey.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MCowBQYDK2VwAyEAub94qcAMx3B7cGmU4Mm4m2bAO27ZA0sj0bmt4rXITC0= 3 | -----END PUBLIC KEY----- -------------------------------------------------------------------------------- /samples/tutorial/recover_publickey.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MCowBQYDK2VwAyEAub94qcAMx3B7cGmU4Mm4m2bAO27ZA0sj0bmt4rXITC0= 3 | -----END PUBLIC KEY----- -------------------------------------------------------------------------------- /samples/tutorial/update_privatekey.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN EC PRIVATE KEY----- 2 | MC4CAQAwBQYDK2VwBCIEIOL28FbniQzChAnkQlDYGNwS9pwBQMH4/4MK0a94nuYs 3 | -----END EC PRIVATE KEY----- -------------------------------------------------------------------------------- /samples/tutorial/update_publickey.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MCowBQYDK2VwAyEA3FKE2r94LiR0GfqTTT9wttMyUfEQk/7yMtG2JIqzZyI= 3 | -----END PUBLIC KEY----- -------------------------------------------------------------------------------- /samples/tutorial/update_publickeys.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "key3", 4 | "type": "Ed25519VerificationKey2018", 5 | "purposes": ["authentication"], 6 | "jwkPath": "jwk3.json" 7 | }, 8 | { 9 | "id": "key4", 10 | "type": "JsonWebKey2020", 11 | "purposes": ["authentication"], 12 | "jwkPath": "jwk4.json" 13 | } 14 | ] -------------------------------------------------------------------------------- /scripts/build-cli.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 4 | # 5 | # SPDX-License-Identifier: Apache-2.0 6 | # 7 | 8 | set -e 9 | 10 | 11 | 12 | cd /opt/workspace/orb 13 | 14 | echo "Building orb cli binaries" 15 | 16 | cd cmd/orb-cli/;CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -o ../../.build/dist/bin/orb-cli-linux-amd64 main.go 17 | cd /opt/workspace/orb 18 | cd .build/dist/bin;tar cvzf orb-cli-linux-amd64.tar.gz orb-cli-linux-amd64;rm -rf orb-cli-linux-amd64 19 | cd /opt/workspace/orb 20 | 21 | 22 | cd cmd/orb-cli/;CC=aarch64-linux-gnu-gcc CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -o ../../.build/dist/bin/orb-cli-linux-arm64 main.go 23 | cd /opt/workspace/orb 24 | cd .build/dist/bin;tar cvzf orb-cli-linux-arm64.tar.gz orb-cli-linux-arm64;rm -rf orb-cli-linux-arm64 25 | cd /opt/workspace/orb 26 | 27 | 28 | cd cmd/orb-cli/;CC=o64-clang CXX=o64-clang++ CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 go build -o ../../.build/dist/bin/orb-cli-darwin-arm64 main.go 29 | cd /opt/workspace/orb 30 | cd .build/dist/bin;tar cvzf orb-cli-darwin-arm64.tar.gz orb-cli-darwin-arm64;rm -rf orb-cli-darwin-arm64 31 | cd /opt/workspace/orb 32 | 33 | cd cmd/orb-cli/;CC=o64-clang CXX=o64-clang++ CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 go build -o ../../.build/dist/bin/orb-cli-darwin-amd64 main.go 34 | cd /opt/workspace/orb 35 | cd .build/dist/bin;tar cvzf orb-cli-darwin-amd64.tar.gz orb-cli-darwin-amd64;rm -rf orb-cli-darwin-amd64 36 | cd /opt/workspace/orb 37 | -------------------------------------------------------------------------------- /scripts/check_license.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright IBM Corp. All Rights Reserved. 4 | # 5 | # SPDX-License-Identifier: Apache-2.0 6 | # 7 | 8 | CHECK=$(git diff --name-only HEAD --diff-filter=ACMRTUXB * | grep -v .png$ | grep -v .rst$ | grep -v .git \ 9 | | grep -v .pem$ | grep -v .block$ | grep -v .tx$ | grep -v ^LICENSE$ | grep -v _sk$ \ 10 | | grep -v .key$ | grep -v \\.gen.go$ | grep -v vendor_template/ | grep -v .csr$ | grep -v .srl$ \ 11 | | grep -v .md$ | grep -v .crt$ | grep -v .json$ | grep -v .lock$ | grep -v .toml$ | grep -v vendor/ | grep -v go.mod | grep -v go.sum | grep -v ^build/ | grep -v .pb.go$ \ 12 | | grep -v restapi/ | grep -v models/ | grep -v cmd/orb-server/ | sort -u) 13 | 14 | if [[ -z "$CHECK" ]]; then 15 | CHECK=$(git diff-tree --no-commit-id --name-only --diff-filter=ACMRTUXB -r $(git log -2 \ 16 | --pretty=format:"%h") | grep -v .png$ | grep -v .rst$ | grep -v .git \ 17 | | grep -v .pem$ | grep -v .block$ | grep -v .tx$ | grep -v ^LICENSE$ | grep -v _sk$ \ 18 | | grep -v .key$ | grep -v \\.gen.go$ | grep -v vendor_template/ | grep -v .csr$ | grep -v .srl$ \ 19 | | grep -v restapi/ | grep -v models/ |grep -v .md$ | grep -v .crt$ | grep -v .json$ |grep -v .lock$ | grep -v .toml$ | grep -v vendor/ | grep -v go.mod | grep -v go.sum | grep -v ^build/ | grep -v .pb.go$ | sort -u) 20 | fi 21 | 22 | if [[ -z "$CHECK" ]]; then 23 | exit 0 24 | fi 25 | 26 | echo "Checking committed files for Copyright headers ..." 27 | missing=`echo $CHECK | xargs grep -L "Copyright"` 28 | if [ -z "$missing" ]; then 29 | echo "All files have Copyright headers" 30 | exit 0 31 | fi 32 | echo "The following files are missing Copyright headers:" 33 | echo "$missing" 34 | echo 35 | exit 1 36 | -------------------------------------------------------------------------------- /scripts/check_lint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 4 | # 5 | # SPDX-License-Identifier: Apache-2.0 6 | # 7 | 8 | set -e 9 | 10 | echo "Running $0" 11 | 12 | DOCKER_CMD=${DOCKER_CMD:-docker} 13 | GOLANGCI_LINT_IMAGE="golangci/golangci-lint:v1.54.2" 14 | 15 | if [ ! $(command -v ${DOCKER_CMD}) ]; then 16 | exit 0 17 | fi 18 | 19 | echo "Linting pkg" 20 | ${DOCKER_CMD} run --rm -e GOPROXY=${GOPROXY} -v $(pwd):/opt/workspace -w /opt/workspace ${GOLANGCI_LINT_IMAGE} golangci-lint run --timeout 10m 21 | echo "Linting orb-server" 22 | ${DOCKER_CMD} run --rm -e GOPROXY=${GOPROXY} -v $(pwd):/opt/workspace -w /opt/workspace/cmd/orb-server ${GOLANGCI_LINT_IMAGE} golangci-lint run -c ../../.golangci.yml --timeout 10m 23 | echo "Linting orb-cli" 24 | ${DOCKER_CMD} run --rm -e GOPROXY=${GOPROXY} -v $(pwd):/opt/workspace -w /opt/workspace/cmd/orb-cli ${GOLANGCI_LINT_IMAGE} golangci-lint run -c ../../.golangci.yml --timeout 10m 25 | echo "Linting orb-driver" 26 | ${DOCKER_CMD} run --rm -e GOPROXY=${GOPROXY} -v $(pwd):/opt/workspace -w /opt/workspace/cmd/orb-driver ${GOLANGCI_LINT_IMAGE} golangci-lint run -c ../../.golangci.yml --timeout 10m 27 | -------------------------------------------------------------------------------- /scripts/generate_test_keys.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 4 | # 5 | # SPDX-License-Identifier: Apache-2.0 6 | # 7 | 8 | set -e 9 | 10 | 11 | echo "Generating orb Test PKI" 12 | 13 | cd /opt/workspace/orb 14 | mkdir -p test/bdd/fixtures/keys/tls 15 | tmp=$(mktemp) 16 | echo "subjectKeyIdentifier=hash 17 | authorityKeyIdentifier = keyid,issuer 18 | extendedKeyUsage = serverAuth 19 | keyUsage = Digital Signature, Key Encipherment 20 | subjectAltName = @alt_names 21 | [alt_names] 22 | DNS.1 = localhost 23 | DNS.2 = orb.domain1.com 24 | DNS.3 = orb2.domain1.com 25 | DNS.4 = orb.domain2.com 26 | DNS.5 = orb.domain3.com 27 | DNS.6 = orb.domain4.com 28 | DNS.7 = orb.domain5.com 29 | DNS.8 = orb.file-server.com" >> "$tmp" 30 | 31 | #create CA 32 | openssl ecparam -name prime256v1 -genkey -noout -out test/bdd/fixtures/keys/tls/ec-cakey.pem 33 | openssl req -new -x509 -key test/bdd/fixtures/keys/tls/ec-cakey.pem -subj "/C=CA/ST=ON/O=Example Internet CA Inc.:CA Sec/OU=CA Sec" -out test/bdd/fixtures/keys/tls/ec-cacert.pem 34 | 35 | #create TLS creds 36 | openssl ecparam -name prime256v1 -genkey -noout -out test/bdd/fixtures/keys/tls/ec-key.pem 37 | openssl req -new -key test/bdd/fixtures/keys/tls/ec-key.pem -subj "/C=CA/ST=ON/O=Example Inc.:orb/OU=orb/CN=localhost" -out test/bdd/fixtures/keys/tls/ec-key.csr 38 | openssl x509 -req -in test/bdd/fixtures/keys/tls/ec-key.csr -CA test/bdd/fixtures/keys/tls/ec-cacert.pem -CAkey test/bdd/fixtures/keys/tls/ec-cakey.pem -CAcreateserial -extfile "$tmp" -out test/bdd/fixtures/keys/tls/ec-pubCert.pem -days 365 39 | 40 | #create primary key for kms secret lock 41 | mkdir -p test/bdd/fixtures/keys/kms 42 | openssl rand 32 | base64 | sed 's/+/-/g; s/\//_/g' > test/bdd/fixtures/keys/kms/secret-lock.key 43 | 44 | echo "done generating orb PKI" 45 | -------------------------------------------------------------------------------- /scripts/integration_cas_ipfs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 4 | # 5 | # SPDX-License-Identifier: Apache-2.0 6 | # 7 | set -e 8 | 9 | echo "Running orb integration tests cas typeipfs..." 10 | PWD=`pwd` 11 | 12 | export DATABASE_TYPE=mongodb 13 | export DATABASE_URL=mongodb://localhost:27017 14 | export ORB_KMS_ENDPOINT=http://localhost:7878 15 | export CAS_TYPE=ipfs 16 | export COMPOSE_HTTP_TIMEOUT=120 17 | export PGUSER=postgres 18 | export PGPASSWORD=password 19 | export DOCKER_COMPOSE_FILE=docker-compose.yml 20 | 21 | cd test/bdd 22 | go test -run all -count=1 -v -cover . -p 1 -timeout=30m -race 23 | 24 | cd $PWD 25 | 26 | -------------------------------------------------------------------------------- /scripts/integration_cas_local.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 4 | # 5 | # SPDX-License-Identifier: Apache-2.0 6 | # 7 | set -e 8 | 9 | echo "Running orb integration tests cas type local..." 10 | PWD=`pwd` 11 | 12 | export DATABASE_TYPE=mongodb 13 | export DATABASE_URL=mongodb://localhost:27017 14 | export ORB_KMS_ENDPOINT=http://localhost:7878 15 | export CAS_TYPE=local 16 | export COMPOSE_HTTP_TIMEOUT=120 17 | export PGUSER=postgres 18 | export PGPASSWORD=password 19 | export DOCKER_COMPOSE_FILE=docker-compose.yml 20 | 21 | cd test/bdd 22 | go test -run all,local_cas -count=1 -v -cover . -p 1 -timeout=30m -race 23 | 24 | cd $PWD 25 | -------------------------------------------------------------------------------- /scripts/integration_versions_maintenance.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 4 | # 5 | # SPDX-License-Identifier: Apache-2.0 6 | # 7 | set -e 8 | 9 | echo "Running orb integration tests protocol versions..." 10 | PWD=`pwd` 11 | 12 | export DATABASE_TYPE=mongodb 13 | export DATABASE_URL=mongodb://localhost:27017 14 | export ORB_KMS_ENDPOINT=http://localhost:7878 15 | export CAS_TYPE=local 16 | export COMPOSE_HTTP_TIMEOUT=120 17 | export PGUSER=postgres 18 | export PGPASSWORD=password 19 | export DOCKER_COMPOSE_FILE=docker-compose-testver.yml 20 | export VERSION_TEST=true 21 | export MAINTENANCE_MODE=false 22 | 23 | cd test/bdd 24 | go test -tags "testver" -run versions_maintenance -count=1 -v -cover . -p 1 -timeout=30m -race 25 | 26 | cd $PWD 27 | 28 | -------------------------------------------------------------------------------- /scripts/unit.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 4 | # 5 | # SPDX-License-Identifier: Apache-2.0 6 | # 7 | set -e 8 | 9 | echo "Running $0" 10 | 11 | pwd=`pwd` 12 | touch "$pwd"/coverage.out 13 | 14 | amend_coverage_file () { 15 | if [ -f profile.out ]; then 16 | cat profile.out >> "$pwd"/coverage.out 17 | rm profile.out 18 | fi 19 | } 20 | 21 | # Running pkg unit tests 22 | PKGS=`go list github.com/trustbloc/orb/... 2> /dev/null | \ 23 | grep -v /mocks` 24 | go test $PKGS -count=1 -race -coverprofile=profile.out -covermode=atomic -timeout=10m 25 | amend_coverage_file 26 | 27 | # Running orb-server unit tests 28 | cd cmd/orb-server 29 | PKGS=`go list github.com/trustbloc/orb/cmd/orb-server/... 2> /dev/null | \ 30 | grep -v /mocks` 31 | go test $PKGS -count=1 -race -coverprofile=profile.out -covermode=atomic -timeout=10m 32 | amend_coverage_file 33 | cd "$pwd" 34 | 35 | # Running orb-cli unit tests 36 | cd cmd/orb-cli 37 | PKGS=`go list github.com/trustbloc/orb/cmd/orb-cli/... 2> /dev/null | \ 38 | grep -v /mocks` 39 | go test $PKGS -count=1 -race -coverprofile=profile.out -covermode=atomic -timeout=10m 40 | amend_coverage_file 41 | cd "$pwd" 42 | 43 | # Running orb-driver unit tests 44 | cd cmd/orb-driver 45 | PKGS=`go list github.com/trustbloc/orb/cmd/orb-driver/... 2> /dev/null | \ 46 | grep -v /mocks` 47 | go test $PKGS -count=1 -race -coverprofile=profile.out -covermode=atomic -timeout=10m 48 | amend_coverage_file 49 | cd "$pwd" 50 | -------------------------------------------------------------------------------- /test/bdd/context.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | 4 | SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | package bdd 8 | 9 | import ( 10 | "sync" 11 | 12 | "github.com/cucumber/messages-go/v10" 13 | ) 14 | 15 | // BDDContext bdd context. 16 | type BDDContext struct { 17 | composition *Composition 18 | mutex sync.RWMutex 19 | createdDID string 20 | } 21 | 22 | // NewBDDContext create new BDDContext 23 | func NewBDDContext() (*BDDContext, error) { 24 | instance := BDDContext{} 25 | return &instance, nil 26 | } 27 | 28 | // BeforeScenario execute code before bdd scenario 29 | func (b *BDDContext) BeforeScenario(*messages.Pickle) {} 30 | 31 | // AfterScenario execute code after bdd scenario 32 | func (b *BDDContext) AfterScenario(*messages.Pickle, error) {} 33 | 34 | // SetComposition sets the Docker composition in the context 35 | func (b *BDDContext) SetComposition(composition *Composition) { 36 | b.mutex.Lock() 37 | defer b.mutex.Unlock() 38 | 39 | if b.composition != nil { 40 | panic("composition is already set") 41 | } 42 | 43 | b.composition = composition 44 | } 45 | 46 | // Composition returns the Docker composition 47 | func (b *BDDContext) Composition() *Composition { 48 | b.mutex.RLock() 49 | defer b.mutex.RUnlock() 50 | 51 | return b.composition 52 | } 53 | -------------------------------------------------------------------------------- /test/bdd/driver_steps.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package bdd 7 | 8 | import ( 9 | "fmt" 10 | "strings" 11 | "time" 12 | 13 | "github.com/cucumber/godog" 14 | ariesdid "github.com/hyperledger/aries-framework-go/pkg/doc/did" 15 | ) 16 | 17 | // DriverSteps is steps for driver BDD tests. 18 | type DriverSteps struct { 19 | bddContext *BDDContext 20 | httpClient *httpClient 21 | } 22 | 23 | // NewDriverSteps returns new driver steps. 24 | func NewDriverSteps(ctx *BDDContext, state *state) *DriverSteps { 25 | return &DriverSteps{ 26 | bddContext: ctx, 27 | httpClient: newHTTPClient(state, ctx), 28 | } 29 | } 30 | 31 | // RegisterSteps registers agent steps. 32 | func (e *DriverSteps) RegisterSteps(s *godog.Suite) { 33 | s.Step(`^check cli created valid DID through universal resolver$`, e.checkCreatedDID) 34 | } 35 | 36 | func (e *DriverSteps) checkCreatedDID() error { 37 | _, err := e.resolveDIDUniversalResolver(e.bddContext.createdDID) 38 | if err != nil { 39 | return err 40 | } 41 | 42 | return nil 43 | } 44 | 45 | func (e *DriverSteps) resolveDIDUniversalResolver(did string) (*ariesdid.DocResolution, error) { 46 | const maxRetry = 10 47 | 48 | didURL := "http://localhost:8062/1.0/identifiers/" + did 49 | 50 | for i := 1; i <= maxRetry; i++ { 51 | resp, err := e.httpClient.Get(didURL) 52 | 53 | if err != nil { 54 | return nil, err 55 | } 56 | 57 | if resp.StatusCode == 200 { 58 | return ariesdid.ParseDocumentResolution(resp.Payload) 59 | } 60 | 61 | if !strings.Contains(resp.ErrorMsg, "DID does not exist") { 62 | return nil, fmt.Errorf("%d: %s", resp.StatusCode, resp.ErrorMsg) 63 | } 64 | 65 | if i == maxRetry { 66 | break 67 | } 68 | 69 | time.Sleep(1 * time.Second) 70 | } 71 | 72 | return nil, fmt.Errorf("DID does not exist") 73 | } 74 | -------------------------------------------------------------------------------- /test/bdd/features/loglevels.feature: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | 7 | @all 8 | @loglevels 9 | Feature: Log Levels 10 | Background: Setup 11 | Given host "orb.domain1.com" is mapped to "localhost:48326" 12 | And host "orb2.domain1.com" is mapped to "localhost:48526" 13 | And the authorization bearer token for "POST" requests to path "/loglevels" is set to "ADMIN_TOKEN" 14 | 15 | @loglevels_put_and_get 16 | Scenario: Tests the /loglevels endpoint 17 | When an HTTP GET is sent to "https://orb.domain1.com/loglevels" 18 | Then the response is saved to variable "originalLogLevels" 19 | 20 | When an HTTP POST is sent to "https://orb.domain1.com/loglevels" with content "xxx" of type "text/plain" and the returned status code is 400 21 | 22 | Given an HTTP POST is sent to "https://orb.domain1.com/loglevels" with content "test-module1=ERROR:test-module2=WARN:INFO" of type "text/plain" 23 | When an HTTP GET is sent to "https://orb.domain1.com/loglevels" 24 | Then the response contains ":INFO" 25 | And the response contains "test-module1=ERROR" 26 | And the response contains "test-module2=WARN" 27 | 28 | # Restore the log levels 29 | Given an HTTP POST is sent to "https://orb.domain1.com/loglevels" with content "${originalLogLevels}" of type "text/plain" 30 | -------------------------------------------------------------------------------- /test/bdd/features/nodeinfo.feature: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | 7 | @all 8 | @nodeinfo 9 | Feature: NodeInfo 10 | Background: Setup 11 | Given host "orb.domain1.com" is mapped to "localhost:48326" 12 | 13 | @node_info 14 | Scenario: Tests NodeInfo response from the server 15 | When an HTTP GET is sent to "https://orb.domain1.com/.well-known/nodeinfo" 16 | Then the JSON path "links.#.rel" of the response contains "http://nodeinfo.diaspora.software/ns/schema/2.0" 17 | And the JSON path "links.#.rel" of the response contains "http://nodeinfo.diaspora.software/ns/schema/2.1" 18 | And the JSON path "links.#.href" of the response contains "https://orb.domain1.com/nodeinfo/2.0" 19 | And the JSON path "links.#.href" of the response contains "https://orb.domain1.com/nodeinfo/2.1" 20 | 21 | When an HTTP GET is sent to "https://orb.domain1.com/nodeinfo/2.1" 22 | Then the JSON path "software.name" of the response equals "Orb" 23 | And the JSON path "software.repository" of the response equals "https://github.com/trustbloc/orb" 24 | And the JSON path "usage.users.total" of the numeric response equals "1" 25 | -------------------------------------------------------------------------------- /test/bdd/fixtures/.env: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | 7 | # This file contains the default images and tags used in the docker 8 | # The images and tags can be overridden using environment 9 | # variables. See docker compose documentation. 10 | 11 | # Default architecture 12 | ARCH=amd64 13 | COMPOSE_DIR=. 14 | 15 | # orb node 16 | ORB_FIXTURE_IMAGE=ghcr.io/trustbloc/orb 17 | ORB_TEST_FIXTURE_IMAGE=ghcr.io/trustbloc/orb-test 18 | 19 | # couch settings 20 | COUCHDB_IMAGE=couchdb 21 | COUCHDB_IMAGE_TAG=3.1.1 22 | COUCHDB_USERNAME=admin 23 | COUCHDB_PASSWORD=password 24 | 25 | COUCHDB_PORT=5984 26 | 27 | COUCHDB_KMS_PORT=5984 28 | COUCHDB_SHARED_PORT=5986 29 | 30 | # MongoDB settings 31 | MONGODB_IMAGE=mongo 32 | MONGODB_IMAGE_TAG=4.0.0 33 | 34 | # postgres settings 35 | PGUSER=postgres 36 | PGPASSWORD=password 37 | PGDATABASE=test 38 | 39 | CAS_TYPE=local 40 | 41 | CID_VERSION_DOMAIN1=1 42 | CID_VERSION_DOMAIN2=1 43 | CID_VERSION_DOMAIN3=1 44 | CID_VERSION_DOMAIN4=1 45 | 46 | RABBITMQ_USERNAME=admin 47 | RABBITMQ_PASSWORD=password 48 | 49 | -------------------------------------------------------------------------------- /test/bdd/fixtures/aws-config/init/seed.yaml: -------------------------------------------------------------------------------- 1 | Keys: 2 | Asymmetric: 3 | Ecc: 4 | - Metadata: 5 | KeyId: 800d5768-3fd7-4edd-a4b8-4c81c3e4c147 6 | KeyUsage: SIGN_VERIFY 7 | Description: ECC key with curve p256 8 | PrivateKeyPem: | 9 | -----BEGIN EC PRIVATE KEY----- 10 | MHcCAQEEIHgnqP6pOtH2kRlTJRWwMY3Hm/R7dSUUdxCTQOaWvbUZoAoGCCqGSM49 11 | AwEHoUQDQgAE2Di7Fea52hG12mc6VVhHIlbC/F2KMgh2fs6bweeHojWBCxzKoLya 12 | 5ty4ZmjM5agWMyTBvfrJ4leWAlCoCV2yvA== 13 | -----END EC PRIVATE KEY----- 14 | - Metadata: 15 | KeyId: 800d5768-3fd7-4edd-a4b8-4c81c3e4c148 16 | KeyUsage: SIGN_VERIFY 17 | Description: ECC key with curve p256 18 | PrivateKeyPem: | 19 | -----BEGIN EC PRIVATE KEY----- 20 | MHcCAQEEIBT16F5ICzCgLqFXwa3sD8CznDaEBNXyYw6S1tW7b6OLoAoGCCqGSM49 21 | AwEHoUQDQgAEYH7+MO+X0YPnGkvK1Nmy/4/r9HpgPPku9gjw3k3zOl+PTbu7iEL2 22 | gsiH/KHaFbeMoMcj5Tv0OkA/EKfuzd0imQ== 23 | -----END EC PRIVATE KEY----- 24 | - Metadata: 25 | KeyId: 800d5768-3fd7-4edd-a4b8-4c81c3e4c149 26 | KeyUsage: SIGN_VERIFY 27 | Description: ECC key with curve p256 28 | PrivateKeyPem: | 29 | -----BEGIN EC PRIVATE KEY----- 30 | MHcCAQEEIP2oNkt4/j9iyLS/zPmuINXBW2LuFs1e/6vp18rElQzToAoGCCqGSM49 31 | AwEHoUQDQgAEfCc/5CT+K59Dv7+r+MiVX+ARfMeFK9CwdLlicTyjoNJdhFfP4/wn 32 | VfXg+vLjrqBYFsYzgokTSTZBSk72WF1RrQ== 33 | -----END EC PRIVATE KEY----- 34 | Aliases: 35 | - AliasName: alias/vc-sign 36 | TargetKeyId: 800d5768-3fd7-4edd-a4b8-4c81c3e4c147 37 | 38 | - AliasName: alias/http-sign 39 | TargetKeyId: 800d5768-3fd7-4edd-a4b8-4c81c3e4c148 40 | 41 | - AliasName: alias/log-sign 42 | TargetKeyId: 800d5768-3fd7-4edd-a4b8-4c81c3e4c149 43 | -------------------------------------------------------------------------------- /test/bdd/fixtures/did-keys/create/key1_jwk.json: -------------------------------------------------------------------------------- 1 | { 2 | "kty":"OKP", 3 | "crv":"Ed25519", 4 | "x":"o1bG1U7G3CNbtALMafUiFOq8ODraTyVTmPtRDO1QUWg", 5 | "y":"" 6 | } 7 | -------------------------------------------------------------------------------- /test/bdd/fixtures/did-keys/create/key2_jwk.json: -------------------------------------------------------------------------------- 1 | { 2 | "kty":"EC", 3 | "crv":"P-256", 4 | "x":"bGM9aNufpKNPxlkyacU1hGhQXm_aC8hIzSVeKDpwjBw", 5 | "y":"PfdmCOtIdVY2B6ucR4oQkt6evQddYhOyHoDYCaI2BJA" 6 | } 7 | -------------------------------------------------------------------------------- /test/bdd/fixtures/did-keys/create/publickeys.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "key1", 4 | "type": "Ed25519VerificationKey2020", 5 | "purposes": ["authentication"], 6 | "jwkPath": "./fixtures/did-keys/create/key1_jwk.json" 7 | }, 8 | { 9 | "id": "key2", 10 | "type": "JsonWebKey2020", 11 | "purposes": ["capabilityInvocation"], 12 | "jwkPath": "./fixtures/did-keys/create/key2_jwk.json" 13 | }, 14 | { 15 | "id": "key5", 16 | "type": "Ed25519VerificationKey2020", 17 | "purposes": ["assertionMethod"], 18 | "b58Key": "36d8RkFy2SdabnGzcZ3LcCSDA8NP5T4bsoADwuXtoN3B" 19 | } 20 | ] 21 | -------------------------------------------------------------------------------- /test/bdd/fixtures/did-keys/recover/key1_jwk.json: -------------------------------------------------------------------------------- 1 | { 2 | "kty":"OKP", 3 | "crv":"Ed25519", 4 | "x":"o1bG1U7G3CNbtALMafUiFOq8ODraTyVTmPtRDO1QUWg", 5 | "y":"" 6 | } 7 | -------------------------------------------------------------------------------- /test/bdd/fixtures/did-keys/recover/publickeys.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "key-recover-id", 4 | "type": "Ed25519VerificationKey2020", 5 | "purposes": ["authentication"], 6 | "jwkPath": "./fixtures/did-keys/recover/key1_jwk.json" 7 | } 8 | ] 9 | -------------------------------------------------------------------------------- /test/bdd/fixtures/did-keys/update/key2_jwk.json: -------------------------------------------------------------------------------- 1 | { 2 | "kty":"EC", 3 | "crv":"P-256", 4 | "x":"bGM9aNufpKNPxlkyacU1hGhQXm_aC8hIzSVeKDpwjBw", 5 | "y":"PfdmCOtIdVY2B6ucR4oQkt6evQddYhOyHoDYCaI2BJA" 6 | } 7 | -------------------------------------------------------------------------------- /test/bdd/fixtures/did-keys/update/key3_jwk.json: -------------------------------------------------------------------------------- 1 | { 2 | "kty":"OKP", 3 | "crv":"Ed25519", 4 | "x":"o1bG1U7G3CNbtALMafUiFOq8ODraTyVTmPtRDO1QUWg", 5 | "y":"" 6 | } 7 | -------------------------------------------------------------------------------- /test/bdd/fixtures/did-keys/update/publickeys.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "key2", 4 | "type": "JsonWebKey2020", 5 | "purposes": ["capabilityInvocation"], 6 | "jwkPath": "./fixtures/did-keys/update/key2_jwk.json" 7 | }, 8 | { 9 | "id": "key3", 10 | "type": "Ed25519VerificationKey2020", 11 | "purposes": ["authentication"], 12 | "jwkPath": "./fixtures/did-keys/update/key3_jwk.json" 13 | } 14 | ] 15 | -------------------------------------------------------------------------------- /test/bdd/fixtures/did-services/create/services.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "svc1", 4 | "type": "type1", 5 | "priority": 1, 6 | "recipientKeys": ["key1"], 7 | "serviceEndpoint": [{ 8 | "uri": "https://example.com", 9 | "routingKeys": ["key1"] 10 | }] 11 | }, 12 | { 13 | "id": "svc2", 14 | "type": "type2", 15 | "priority": 2, 16 | "recipientKeys": ["key2"], 17 | "serviceEndpoint": [{ 18 | "uri": "https://example.com", 19 | "routingKeys": ["key1"] 20 | }] 21 | } 22 | ] 23 | -------------------------------------------------------------------------------- /test/bdd/fixtures/did-services/recover/services.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "svc-recover-id", 4 | "type": "type1", 5 | "priority": 1, 6 | "recipientKeys": ["key1"], 7 | "serviceEndpoint": [{ 8 | "uri": "https://example.com", 9 | "routingKeys": ["key1"] 10 | }] 11 | } 12 | ] 13 | -------------------------------------------------------------------------------- /test/bdd/fixtures/did-services/update/services.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "id": "svc3", 4 | "type": "type3", 5 | "priority": 3, 6 | "recipientKeys": ["key3"], 7 | "serviceEndpoint": [{ 8 | "uri": "https://example.com", 9 | "routingKeys": ["key3"] 10 | }] 11 | } 12 | ] 13 | -------------------------------------------------------------------------------- /test/bdd/fixtures/nginx-config/nginx.conf: -------------------------------------------------------------------------------- 1 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | 6 | events {} 7 | 8 | error_log /dev/stdout error; 9 | 10 | http { 11 | access_log /dev/null; 12 | 13 | upstream orb-domain2 { 14 | least_conn; 15 | server orb-domain2.backend max_fails=50 fail_timeout=30s; 16 | server orb1-domain2.backend max_fails=50 fail_timeout=30s; 17 | keepalive 8; 18 | } 19 | server { 20 | listen 443 ssl; 21 | listen 48426 ssl; 22 | ssl_certificate /etc/tls/ec-pubCert.pem; 23 | ssl_certificate_key /etc/tls/ec-key.pem; 24 | location / { 25 | proxy_pass http://orb-domain2; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /test/bdd/fixtures/prometheus-config/prometheus.yml: -------------------------------------------------------------------------------- 1 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | # 5 | 6 | # Global config 7 | global: 8 | scrape_interval: 2s # Set the scrape interval to every 15 seconds. Default is every 1 minute. 9 | evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute. 10 | # scrape_timeout is set to the global default (10s). 11 | 12 | # Alertmanager configuration 13 | alerting: 14 | alertmanagers: 15 | - static_configs: 16 | - targets: 17 | # - alertmanager:9093 18 | 19 | # Load rules once and periodically evaluate them according to the global 'evaluation_interval'. 20 | rule_files: 21 | # - "first_rules.yml" 22 | # - "second_rules.yml" 23 | 24 | # A scrape configuration containing exactly one endpoint to scrape: 25 | # Here it's Prometheus itself. 26 | scrape_configs: 27 | # The job name is added as a label `job=` to any timeseries scraped from this config. 28 | - job_name: 'prometheus' 29 | 30 | # metrics_path defaults to '/metrics' 31 | # scheme defaults to 'http'. 32 | scheme: http 33 | 34 | static_configs: 35 | - targets: ['orb.domain1.com:48327','orb2.domain1.com:48527', 36 | 'orb-domain2.backend:48827', 'orb1-domain2.backend:48927', 37 | 'orb.domain3.com:48627','orb.domain4.com:48727'] 38 | -------------------------------------------------------------------------------- /test/bdd/fixtures/rabbitmq-config/rabbitmq.conf: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright SecureKey Technologies Inc. All Rights Reserved. 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | # 6 | 7 | loopback_users.guest = false 8 | 9 | listeners.tcp.default = 5672 10 | 11 | management.tcp.port = 15672 12 | 13 | default_user = admin 14 | 15 | default_pass = password 16 | -------------------------------------------------------------------------------- /test/bdd/fixtures/testdata/keys/domain1/private-key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MC4CAQAwBQYDK2VwBCIEIOL28FbniQzChAnkQlDYGNwS9pwBQMH4/4MK0a94nuYs 3 | -----END PRIVATE KEY----- 4 | -------------------------------------------------------------------------------- /test/bdd/fixtures/testdata/keys/domain1/public-key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MCowBQYDK2VwAyEA3FKE2r94LiR0GfqTTT9wttMyUfEQk/7yMtG2JIqzZyI= 3 | -----END PUBLIC KEY----- 4 | -------------------------------------------------------------------------------- /test/bdd/fixtures/testdata/keys/domain2/private-key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MC4CAQAwBQYDK2VwBCIEILyqqoP1XmSKsSMEP7+wDJsRqrNVuONXzUY8JH9EQxw/ 3 | -----END PRIVATE KEY----- 4 | -------------------------------------------------------------------------------- /test/bdd/fixtures/testdata/keys/domain2/public-key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MCowBQYDK2VwAyEAub94qcAMx3B7cGmU4Mm4m2bAO27ZA0sj0bmt4rXITC0= 3 | -----END PUBLIC KEY----- 4 | -------------------------------------------------------------------------------- /test/bdd/fixtures/testdata/keys/domain3/private-key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MC4CAQAwBQYDK2VwBCIEILyqqoP1XmSKsSMEP7+wDJsRqrNVuONXzUY8JH9EQxw/ 3 | -----END PRIVATE KEY----- 4 | -------------------------------------------------------------------------------- /test/bdd/fixtures/testdata/keys/domain3/public-key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MCowBQYDK2VwAyEAub94qcAMx3B7cGmU4Mm4m2bAO27ZA0sj0bmt4rXITC0= 3 | -----END PUBLIC KEY----- 4 | -------------------------------------------------------------------------------- /test/bdd/fixtures/uni-resolver-web/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "drivers": [ 3 | { 4 | "pattern": "^(did:orb:.+)$", 5 | "url": "http://orb.driver:8070/1.0/identifiers/$1" 6 | } 7 | ] 8 | } 9 | --------------------------------------------------------------------------------