Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(anoncreds): auto create link secret #1521

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions demo/src/Alice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,6 @@ export class Alice extends BaseAgent {
}

public async acceptCredentialOffer(credentialRecord: CredentialExchangeRecord) {
const linkSecretIds = await this.agent.modules.anoncreds.getLinkSecretIds()
if (linkSecretIds.length === 0) {
await this.agent.modules.anoncreds.createLinkSecret()
}

await this.agent.credentials.acceptOffer({
credentialRecordId: credentialRecord.id,
})
Expand Down
11 changes: 11 additions & 0 deletions packages/anoncreds-rs/src/AnonCredsRsModuleConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ export interface AnonCredsRsModuleConfigOptions {
* ```
*/
anoncreds: Anoncreds

/**
* Create a default link secret if there are no created link secrets.
* @defaultValue true
*/
autoCreateLinkSecret?: boolean
}

/**
Expand All @@ -55,4 +61,9 @@ export class AnonCredsRsModuleConfig {
public get anoncreds() {
return this.options.anoncreds
}

/** See {@link AnonCredsModuleConfigOptions.autoCreateLinkSecret} */
public get autoCreateLinkSecret() {
return this.options.autoCreateLinkSecret ?? true
}
}
17 changes: 12 additions & 5 deletions packages/anoncreds-rs/src/services/AnonCredsRsHolderService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
AnonCredsRestrictionWrapper,
unqualifiedCredentialDefinitionIdRegex,
AnonCredsRegistryService,
storeLinkSecret,
} from '@aries-framework/anoncreds'
import { AriesFrameworkError, JsonTransformer, TypedArrayEncoder, injectable, utils } from '@aries-framework/core'
import {
Expand All @@ -47,6 +48,7 @@ import {
anoncreds,
} from '@hyperledger/anoncreds-shared'

import { AnonCredsRsModuleConfig } from '../AnonCredsRsModuleConfig'
import { AnonCredsRsError } from '../errors/AnonCredsRsError'

@injectable()
Expand Down Expand Up @@ -198,15 +200,20 @@ export class AnonCredsRsHolderService implements AnonCredsHolderService {
const linkSecretRepository = agentContext.dependencyManager.resolve(AnonCredsLinkSecretRepository)

// If a link secret is specified, use it. Otherwise, attempt to use default link secret
const linkSecretRecord = options.linkSecretId
let linkSecretRecord = options.linkSecretId
? await linkSecretRepository.getByLinkSecretId(agentContext, options.linkSecretId)
: await linkSecretRepository.findDefault(agentContext)

// No default link secret. Automatically create one if set on module config
if (!linkSecretRecord) {
// No default link secret
throw new AnonCredsRsError(
'No link secret provided to createCredentialRequest and no default link secret has been found'
)
const moduleConfig = agentContext.dependencyManager.resolve(AnonCredsRsModuleConfig)
if (!moduleConfig.autoCreateLinkSecret) {
throw new AnonCredsRsError(
'No link secret provided to createCredentialRequest and no default link secret has been found'
)
}
const { linkSecretId, linkSecretValue } = await this.createLinkSecret(agentContext, {})
linkSecretRecord = await storeLinkSecret(agentContext, { linkSecretId, linkSecretValue, setAsDefault: true })
}

if (!linkSecretRecord.value) {
Expand Down
27 changes: 9 additions & 18 deletions packages/anoncreds/src/AnonCredsApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import {
AnonCredsCredentialDefinitionPrivateRepository,
AnonCredsKeyCorrectnessProofRecord,
AnonCredsKeyCorrectnessProofRepository,
AnonCredsLinkSecretRecord,
AnonCredsLinkSecretRepository,
} from './repository'
import { AnonCredsCredentialDefinitionRecord } from './repository/AnonCredsCredentialDefinitionRecord'
Expand All @@ -40,6 +39,7 @@ import {
AnonCredsIssuerServiceSymbol,
} from './services'
import { AnonCredsRegistryService } from './services/registry/AnonCredsRegistryService'
import { storeLinkSecret } from './utils'

@injectable()
export class AnonCredsApi {
Expand Down Expand Up @@ -81,30 +81,21 @@ export class AnonCredsApi {

/**
* Create a Link Secret, optionally indicating its ID and if it will be the default one
* If there is no default Link Secret, this will be set as default (even if setAsDefault is true).
* If there is no default Link Secret, this will be set as default (even if setAsDefault is false).
*
*/
public async createLinkSecret(options?: AnonCredsCreateLinkSecretOptions) {
public async createLinkSecret(options?: AnonCredsCreateLinkSecretOptions): Promise<string> {
const { linkSecretId, linkSecretValue } = await this.anonCredsHolderService.createLinkSecret(this.agentContext, {
linkSecretId: options?.linkSecretId,
})

// In some cases we don't have the linkSecretValue. However we still want a record so we know which link secret ids are valid
const linkSecretRecord = new AnonCredsLinkSecretRecord({ linkSecretId, value: linkSecretValue })

// If it is the first link secret registered, set as default
const defaultLinkSecretRecord = await this.anonCredsLinkSecretRepository.findDefault(this.agentContext)
if (!defaultLinkSecretRecord || options?.setAsDefault) {
linkSecretRecord.setTag('isDefault', true)
}

// Set the current default link secret as not default
if (defaultLinkSecretRecord && options?.setAsDefault) {
defaultLinkSecretRecord.setTag('isDefault', false)
await this.anonCredsLinkSecretRepository.update(this.agentContext, defaultLinkSecretRecord)
}
await storeLinkSecret(this.agentContext, {
linkSecretId,
linkSecretValue,
setAsDefault: options?.setAsDefault,
})

await this.anonCredsLinkSecretRepository.save(this.agentContext, linkSecretRecord)
return linkSecretId
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { agentDependencies, getAgentConfig, getAgentContext } from '../../../../
import {
IndySdkHolderService,
IndySdkIssuerService,
IndySdkModuleConfig,
IndySdkStorageService,
IndySdkVerifierService,
IndySdkWallet,
Expand Down Expand Up @@ -63,6 +64,7 @@ const agentContext = getAgentContext({
[AnonCredsRegistryService, new AnonCredsRegistryService()],
[AnonCredsModuleConfig, anonCredsModuleConfig],
[AnonCredsLinkSecretRepository, anonCredsLinkSecretRepository],
[IndySdkModuleConfig, new IndySdkModuleConfig({ indySdk, autoCreateLinkSecret: false })],
],
agentConfig,
wallet,
Expand Down
1 change: 1 addition & 0 deletions packages/anoncreds/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ export * from './AnonCredsApiOptions'
export { generateLegacyProverDidLikeString } from './utils/proverDid'
export * from './utils/indyIdentifiers'
export { assertBestPracticeRevocationInterval } from './utils/revocationInterval'
export { storeLinkSecret } from './utils/linkSecret'
Original file line number Diff line number Diff line change
Expand Up @@ -448,11 +448,6 @@ describe('V1 Proofs - Connectionless - Indy', () => {
expect(faberConnection.isReady).toBe(true)
expect(aliceConnection.isReady).toBe(true)

await aliceAgent.modules.anoncreds.createLinkSecret({
linkSecretId: 'default',
setAsDefault: true,
})

await issueLegacyAnonCredsCredential({
issuerAgent: faberAgent as AnonCredsTestsAgent,
issuerReplay: faberReplay,
Expand Down
1 change: 1 addition & 0 deletions packages/anoncreds/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export { encodeCredentialValue, checkValidCredentialValueEncoding } from './cred
export { IsMap } from './isMap'
export { composeCredentialAutoAccept, composeProofAutoAccept } from './composeAutoAccept'
export { areCredentialPreviewAttributesEqual } from './credentialPreviewAttributes'
export { storeLinkSecret } from './linkSecret'
export {
unqualifiedCredentialDefinitionIdRegex,
unqualifiedIndyDidRegex,
Expand Down
30 changes: 30 additions & 0 deletions packages/anoncreds/src/utils/linkSecret.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { AgentContext } from '@aries-framework/core'

import { AnonCredsLinkSecretRecord, AnonCredsLinkSecretRepository } from '../repository'

export async function storeLinkSecret(
agentContext: AgentContext,
options: { linkSecretId: string; linkSecretValue?: string; setAsDefault?: boolean }
) {
const { linkSecretId, linkSecretValue, setAsDefault } = options
const linkSecretRepository = agentContext.dependencyManager.resolve(AnonCredsLinkSecretRepository)

// In some cases we don't have the linkSecretValue. However we still want a record so we know which link secret ids are valid
const linkSecretRecord = new AnonCredsLinkSecretRecord({ linkSecretId, value: linkSecretValue })

// If it is the first link secret registered, set as default
const defaultLinkSecretRecord = await linkSecretRepository.findDefault(agentContext)
if (!defaultLinkSecretRecord || setAsDefault) {
linkSecretRecord.setTag('isDefault', true)
}

// Set the current default link secret as not default
if (defaultLinkSecretRecord && setAsDefault) {
defaultLinkSecretRecord.setTag('isDefault', false)
await linkSecretRepository.update(agentContext, defaultLinkSecretRecord)
}

await linkSecretRepository.save(agentContext, linkSecretRecord)

return linkSecretRecord
}
1 change: 1 addition & 0 deletions packages/anoncreds/tests/anoncreds.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ const agent = new Agent({
modules: {
indySdk: new IndySdkModule({
indySdk,
autoCreateLinkSecret: false,
}),
anoncreds: new AnonCredsModule({
registries: [
Expand Down
6 changes: 0 additions & 6 deletions packages/anoncreds/tests/legacyAnonCredsSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@

// Helper type to get the type of the agents (with the custom modules) for the credential tests
export type AnonCredsTestsAgent =
| Agent<ReturnType<typeof getLegacyAnonCredsModules> & { mediationRecipient?: any; mediator?: any }>

Check warning on line 77 in packages/anoncreds/tests/legacyAnonCredsSetup.ts

View workflow job for this annotation

GitHub Actions / Validate

Unexpected any. Specify a different type

Check warning on line 77 in packages/anoncreds/tests/legacyAnonCredsSetup.ts

View workflow job for this annotation

GitHub Actions / Validate

Unexpected any. Specify a different type
| Agent<ReturnType<typeof getAskarAnonCredsIndyModules> & { mediationRecipient?: any; mediator?: any }>

Check warning on line 78 in packages/anoncreds/tests/legacyAnonCredsSetup.ts

View workflow job for this annotation

GitHub Actions / Validate

Unexpected any. Specify a different type

Check warning on line 78 in packages/anoncreds/tests/legacyAnonCredsSetup.ts

View workflow job for this annotation

GitHub Actions / Validate

Unexpected any. Specify a different type

export const getLegacyAnonCredsModules = ({
autoAcceptCredentials,
Expand Down Expand Up @@ -402,12 +402,6 @@
await holderAgent.initialize()
if (verifierAgent) await verifierAgent.initialize()

// Create default link secret for holder
await holderAgent.modules.anoncreds.createLinkSecret({
linkSecretId: 'default',
setAsDefault: true,
})

const { credentialDefinition, schema } = await prepareForAnonCredsIssuance(issuerAgent, {
attributeNames,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,6 @@ describe('V2 Connectionless Credentials', () => {
aliceAgent.registerOutboundTransport(new SubjectOutboundTransport(subjectMap))
await aliceAgent.initialize()

// Create link secret for alice
await aliceAgent.modules.anoncreds.createLinkSecret({
linkSecretId: 'default',
setAsDefault: true,
})

const { credentialDefinition } = await prepareForAnonCredsIssuance(faberAgent, {
attributeNames: ['name', 'age'],
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,12 +169,6 @@ describe('V2 Credentials - JSON-LD - Ed25519', () => {
await aliceAgent.initialize()
;[, { id: aliceConnectionId }] = await makeConnection(faberAgent, aliceAgent)

// Create link secret for alice
await aliceAgent.modules.anoncreds.createLinkSecret({
linkSecretId: 'default',
setAsDefault: true,
})

const { credentialDefinition } = await prepareForAnonCredsIssuance(faberAgent, {
attributeNames: ['name', 'age', 'profile_picture', 'x-ray'],
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -345,11 +345,6 @@ describe('V2 Connectionless Proofs - Indy', () => {
)
agents = [aliceAgent, faberAgent, mediatorAgent]

await aliceAgent.modules.anoncreds.createLinkSecret({
linkSecretId: 'default',
setAsDefault: true,
})

const { credentialDefinition } = await prepareForAnonCredsIssuance(faberAgent, {
attributeNames: ['name', 'age', 'image_0', 'image_1'],
})
Expand Down
11 changes: 11 additions & 0 deletions packages/indy-sdk/src/IndySdkModuleConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ export interface IndySdkModuleConfigOptions {
* ```
*/
networks?: IndySdkPoolConfig[]

/**
* Create a default link secret if there are no created link secrets.
* @defaultValue true
*/
autoCreateLinkSecret?: boolean
}

export class IndySdkModuleConfig {
Expand All @@ -67,4 +73,9 @@ export class IndySdkModuleConfig {
public get networks() {
return this.options.networks ?? []
}

/** See {@link AnonCredsModuleConfigOptions.autoCreateLinkSecret} */
public get autoCreateLinkSecret() {
return this.options.autoCreateLinkSecret ?? true
}
}
17 changes: 12 additions & 5 deletions packages/indy-sdk/src/anoncreds/services/IndySdkHolderService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ import {
parseIndyCredentialDefinitionId,
AnonCredsLinkSecretRepository,
generateLegacyProverDidLikeString,
storeLinkSecret,
} from '@aries-framework/anoncreds'
import { AriesFrameworkError, injectable, inject, utils } from '@aries-framework/core'

import { IndySdkModuleConfig } from '../../IndySdkModuleConfig'
import { IndySdkError, isIndyError } from '../../error'
import { IndySdk, IndySdkSymbol } from '../../types'
import { assertIndySdkWallet } from '../../utils/assertIndySdkWallet'
Expand Down Expand Up @@ -283,15 +285,20 @@ export class IndySdkHolderService implements AnonCredsHolderService {
const proverDid = generateLegacyProverDidLikeString()

// If a link secret is specified, use it. Otherwise, attempt to use default link secret
const linkSecretRecord = options.linkSecretId
let linkSecretRecord = options.linkSecretId
? await linkSecretRepository.getByLinkSecretId(agentContext, options.linkSecretId)
: await linkSecretRepository.findDefault(agentContext)

// No default link secret. Automatically create one if set on module config
if (!linkSecretRecord) {
// No default link secret
throw new AriesFrameworkError(
'No link secret provided to createCredentialRequest and no default link secret has been found'
)
const moduleConfig = agentContext.dependencyManager.resolve(IndySdkModuleConfig)
if (!moduleConfig.autoCreateLinkSecret) {
throw new AriesFrameworkError(
'No link secret provided to createCredentialRequest and no default link secret has been found'
)
}
const { linkSecretId } = await this.createLinkSecret(agentContext, {})
linkSecretRecord = await storeLinkSecret(agentContext, { linkSecretId, setAsDefault: true })
}

try {
Expand Down
3 changes: 0 additions & 3 deletions tests/e2e-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,6 @@ export async function e2eTest({
const [recipientSenderConnection, senderRecipientConnection] = await makeConnection(recipientAgent, senderAgent)
expect(recipientSenderConnection).toBeConnectedWith(senderRecipientConnection)

// Create link secret with default options. This should create a default link secret.
await recipientAgent.modules.anoncreds.createLinkSecret()

// Issue credential from sender to recipient
const { credentialDefinition } = await prepareForAnonCredsIssuance(senderAgent, {
attributeNames: ['name', 'age', 'dateOfBirth'],
Expand Down
Loading