Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import {
IsArray,
ValidateIf,
IsEmpty,
ArrayNotEmpty
ArrayNotEmpty,
IsDefined,
NotEquals
} from 'class-validator';
import { ApiExtraModels, ApiProperty, ApiPropertyOptional, getSchemaPath, PartialType } from '@nestjs/swagger';
import { Type } from 'class-transformer';
Expand Down Expand Up @@ -216,12 +218,11 @@ export class CreateCredentialTemplateDto {
@IsString()
description?: string;

@ApiProperty({
description: 'Signer option (did or x509)',
enum: SignerOption,
example: SignerOption.DID
})
@ApiProperty({ enum: SignerOption, description: 'Signer option type' })
@IsEnum(SignerOption)
@ValidateIf((o) => o.format === CredentialFormat.Mdoc)
@IsDefined({ message: 'signerOption is required when format is Mdoc' })
@NotEquals(SignerOption.DID, { message: 'signerOption must NOT be DID when format is Mdoc' })
signerOption!: SignerOption;

@ApiProperty({ enum: CredentialFormat, description: 'Credential format type' })
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString } from 'class-validator';
export class Oid4vpPresentationWhDto {
@ApiProperty()
@IsString()
id!: string;

@ApiProperty()
@IsString()
state!: string;

@ApiProperty()
@IsString()
authorizationRequestId!: string;

@ApiProperty()
@IsString()
createdAt!: string;

@ApiProperty()
@IsString()
updatedAt!: string;

@ApiProperty()
@IsString()
contextCorrelationId!: string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,15 @@ import {
ApiBearerAuth,
ApiForbiddenResponse,
ApiUnauthorizedResponse,
ApiQuery
ApiQuery,
ApiExcludeEndpoint
} from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { ApiResponseDto } from '../dtos/apiResponse.dto';
import { UnauthorizedErrorDto } from '../dtos/unauthorized-error.dto';
import { ForbiddenErrorDto } from '../dtos/forbidden-error.dto';
import { Response } from 'express';
import { IResponse } from '@credebl/common/interfaces/response.interface';
import IResponseType, { IResponse } from '@credebl/common/interfaces/response.interface';
import { User } from '../authz/decorators/user.decorator';
import { ResponseMessages } from '@credebl/common/response-messages';
import { Roles } from '../authz/decorators/roles.decorator';
Expand All @@ -46,6 +47,7 @@ import { user } from '@prisma/client';
import { Oid4vcVerificationService } from './oid4vc-verification.service';
import { CreateVerifierDto, UpdateVerifierDto } from './dtos/oid4vc-verifier.dto';
import { PresentationRequestDto, VerificationPresentationQueryDto } from './dtos/oid4vc-verifier-presentation.dto';
import { Oid4vpPresentationWhDto } from '../oid4vc-issuance/dtos/oid4vp-presentation-wh.dto';
@Controller()
@UseFilters(CustomExceptionFilter)
@ApiTags('OID4VP')
Expand Down Expand Up @@ -296,7 +298,7 @@ export class Oid4vcVerificationController {

const finalResponse: IResponse = {
statusCode: HttpStatus.CREATED,
message: ResponseMessages.oid4vp.success.create,
message: ResponseMessages.oid4vpSession.success.create,
data: presentation
};
return res.status(HttpStatus.CREATED).json(finalResponse);
Expand Down Expand Up @@ -408,4 +410,30 @@ export class Oid4vcVerificationController {
throw new BadRequestException(error.message || 'Failed to fetch verifier presentation response details.');
}
}
/**
* Catch issue credential webhook responses
* @param oid4vpPresentationWhDto The details of the oid4vp presentation webhook
* @param id The ID of the organization
* @param res The response object
* @returns The details of the oid4vp presentation webhook
*/
@Post('wh/:id/openid4vc-verification')
@ApiExcludeEndpoint()
@ApiOperation({
summary: 'Catch OID4VP presentation states',
description: 'Handles webhook responses for OID4VP presentation states.'
})
async storePresentationWebhook(
@Body() oid4vpPresentationWhDto: Oid4vpPresentationWhDto,
@Param('id') id: string,
@Res() res: Response
): Promise<Response> {
await this.oid4vcVerificationService.oid4vpPresentationWebhook(oid4vpPresentationWhDto, id);
const finalResponse: IResponseType = {
statusCode: HttpStatus.CREATED,
message: ResponseMessages.issuance.success.create,
data: []
};
return res.status(HttpStatus.CREATED).json(finalResponse);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { LoggerModule } from '@credebl/logger';
{
name: 'NATS_CLIENT',
transport: Transport.NATS,
options: getNatsOptions(CommonConstants.ISSUANCE_SERVICE, process.env.API_GATEWAY_NKEY_SEED)
options: getNatsOptions(CommonConstants.OIDC4VC_VERIFICATION_SERVICE, process.env.API_GATEWAY_NKEY_SEED)
}
])
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { BaseService } from 'libs/service/base.service';
import { oid4vp_verifier, user } from '@prisma/client';
import { CreateVerifierDto, UpdateVerifierDto } from './dtos/oid4vc-verifier.dto';
import { VerificationPresentationQueryDto } from './dtos/oid4vc-verifier-presentation.dto';
import { Oid4vpPresentationWhDto } from '../oid4vc-issuance/dtos/oid4vp-presentation-wh.dto';

@Injectable()
export class Oid4vcVerificationService extends BaseService {
Expand Down Expand Up @@ -81,4 +82,14 @@ export class Oid4vcVerificationService extends BaseService {
);
return this.natsClient.sendNatsMessage(this.oid4vpProxy, 'oid4vp-verification-session-create', payload);
}

oid4vpPresentationWebhook(
oid4vpPresentationWhDto: Oid4vpPresentationWhDto,
id: string
): Promise<{
response: object;
}> {
const payload = { oid4vpPresentationWhDto, id };
return this.natsClient.sendNats(this.oid4vpProxy, 'webhook-oid4vp-presentation', payload);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export interface IssuerInitialConfig {
authorizationServerConfigs: AuthorizationServerConfig | {};
accessTokenSignerKeyType: AccessTokenSignerKeyType;
dpopSigningAlgValuesSupported: string[];
batchCredentialIssuance: object;
batchCredentialIssuance?: object;
credentialConfigurationsSupported: object;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ function buildMdocCredential(
) {
throw new UnprocessableEntityException(`${ResponseMessages.oidcIssuerSession.error.missingValidityInfo}`);
}

//TODO: add validation, signerOptions must be x5c for mdoc.
const certificateDetail = activeCertificateDetails.find((x) => x.certificateBase64 === signerOptions[0].x5c[0]);
const validationResult = validateCredentialDatesInCertificateWindow(
credentialRequest.validityInfo,
Expand Down
2 changes: 1 addition & 1 deletion apps/oid4vc-issuance/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const logger = new Logger();
async function bootstrap(): Promise<void> {
const app = await NestFactory.createMicroservice<MicroserviceOptions>(Oid4vcIssuanceModule, {
transport: Transport.NATS,
options: getNatsOptions(CommonConstants.OIDC4VC_ISSUANCE_SERVICE, process.env.ISSUANCE_NKEY_SEED)
options: getNatsOptions(CommonConstants.OIDC4VC_ISSUANCE_SERVICE, process.env.OIDC4VC_ISSUANCE_NKEY_SEED)
});
app.useLogger(app.get(NestjsLoggerServiceAdapter));
app.useGlobalFilters(new HttpExceptionFilter());
Expand Down
21 changes: 8 additions & 13 deletions apps/oid4vc-issuance/src/oid4vc-issuance.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,14 @@ export class Oid4vcIssuanceService {
authorizationServerConfigs: issuerCreation?.authorizationServerConfigs || undefined,
accessTokenSignerKeyType,
dpopSigningAlgValuesSupported,
batchCredentialIssuance: {
batchSize: batchCredentialIssuanceSize ?? batchCredentialIssuanceDefault
},
credentialConfigurationsSupported
credentialConfigurationsSupported,
...(batchCredentialIssuanceSize && 0 < batchCredentialIssuanceSize
? {
batchCredentialIssuance: {
batchSize: batchCredentialIssuanceSize
}
}
: {})
};
let createdIssuer;
try {
Expand Down Expand Up @@ -694,7 +698,6 @@ export class Oid4vcIssuanceService {

return updateCredentialOfferOnAgent.response;
} catch (error) {
this.logger.error(`[createOidcCredentialOffer] - error: ${JSON.stringify(error)}`);
throw new RpcException(error.response ?? error);
}
}
Expand Down Expand Up @@ -967,13 +970,9 @@ export class Oid4vcIssuanceService {
credentialOfferPayload,
issuedCredentials
} = CredentialOfferWebhookPayload ?? {};

// ensure we only store credential_configuration_ids in the payload for logging and storage
const cfgIds: string[] = Array.isArray(credentialOfferPayload?.credential_configuration_ids)
? credentialOfferPayload.credential_configuration_ids
: [];

// convert issuedCredentials to string[] when schema expects string[]
const issuedCredentialsArr: string[] | undefined =
Array.isArray(issuedCredentials) && 0 < issuedCredentials.length
? issuedCredentials.map((c: any) => ('string' === typeof c ? c : JSON.stringify(c)))
Expand All @@ -989,17 +988,13 @@ export class Oid4vcIssuanceService {
};

console.log('Storing OID4VC Credential Webhook:', JSON.stringify(sanitized, null, 2));

// resolve orgId (unchanged logic)
let orgId: string;
if ('default' !== contextCorrelationId) {
const getOrganizationId = await this.oid4vcIssuanceRepository.getOrganizationByTenantId(contextCorrelationId);
orgId = getOrganizationId?.orgId;
} else {
orgId = issuanceSessionId;
}

// hand off to repository for persistence (repository will perform the upsert)
const agentDetails = await this.oid4vcIssuanceRepository.storeOidcCredentialDetails(
CredentialOfferWebhookPayload,
orgId
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export interface Oid4vpPresentationWh {
id: string;
state: string;
createdAt: string;
updatedAt: string;
contextCorrelationId: string;
authorizationRequestId: string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { user } from '@prisma/client';
import { CreateVerifier, UpdateVerifier } from '@credebl/common/interfaces/oid4vp-verification';
import { MessagePattern } from '@nestjs/microservices';
import { VerificationSessionQuery } from '../interfaces/oid4vp-verifier.interfaces';
import { Oid4vpPresentationWh } from '../interfaces/oid4vp-verification-sessions.interfaces';

@Controller()
export class Oid4vpVerificationController {
Expand Down Expand Up @@ -91,4 +92,12 @@ export class Oid4vpVerificationController {
userDetails
);
}

@MessagePattern({ cmd: 'webhook-oid4vp-presentation' })
async oid4vpPresentationWebhook(payload: {
oid4vpPresentationWhDto: Oid4vpPresentationWh;
id: string;
}): Promise<object> {
return this.oid4vpVerificationService.oid4vpPresentationWebhook(payload.oid4vpPresentationWhDto, payload.id);
}
}
38 changes: 38 additions & 0 deletions apps/oid4vc-verification/src/oid4vc-verification.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { oid4vp_verifier, org_agents } from '@prisma/client';
import { PrismaService } from '@credebl/prisma-service';
import { ResponseMessages } from '@credebl/common/response-messages';
import { OrgAgent } from '../interfaces/oid4vp-verifier.interfaces';
import { Oid4vpPresentationWh } from '../interfaces/oid4vp-verification-sessions.interfaces';

@Injectable()
export class Oid4vpRepository {
Expand Down Expand Up @@ -188,4 +189,41 @@ export class Oid4vpRepository {
throw error;
}
}

async storeOid4vpPresentationDetails(
oid4vpPresentationPayload: Oid4vpPresentationWh,
orgId: string
): Promise<object> {
try {
const {
state,
id: verificationSessionId,
contextCorrelationId,
authorizationRequestId
} = oid4vpPresentationPayload;
const credentialDetails = await this.prisma.oid4vp_presentations.upsert({
where: {
verificationSessionId
},
update: {
lastChangedBy: orgId,
state
},
create: {
lastChangedBy: orgId,
createdBy: orgId,
state,
orgId,
contextCorrelationId,
verificationSessionId,
presentationId: authorizationRequestId
}
});

return credentialDetails;
} catch (error) {
this.logger.error(`Error in storeOid4vpPresentationDetails in oid4vp-presentation repository: ${error.message} `);
throw error;
}
}
}
28 changes: 24 additions & 4 deletions apps/oid4vc-verification/src/oid4vc-verification.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { buildUrlWithQuery } from '@credebl/common/cast.helper';
import { VerificationSessionQuery } from '../interfaces/oid4vp-verifier.interfaces';
import { RequestSignerMethod } from '@credebl/enum/enum';
import { BaseService } from 'libs/service/base.service';
import { Oid4vpPresentationWh } from '../interfaces/oid4vp-verification-sessions.interfaces';

@Injectable()
export class Oid4vpVerificationService extends BaseService {
Expand Down Expand Up @@ -282,10 +283,11 @@ export class Oid4vpVerificationService extends BaseService {
throw new NotFoundException(ResponseMessages.issuance.error.agentEndPointNotFound);
}
const { agentEndPoint, id } = agentDetails;

const url = getAgentUrl(agentEndPoint, CommonConstants.OIDC_VERIFIER_SESSION_GET_BY_ID, verificationSessionId);
this.logger.debug(`[getVerificationSessionResponse] calling agent URL=${url}`);

const url = getAgentUrl(
agentEndPoint,
CommonConstants.OIDC_VERIFIER_SESSION_RESPONSE_GET_BY_ID,
verificationSessionId
);
const verifiers = await await this._getOid4vpVerifierSession(url, orgId);
if (!verifiers || 0 === verifiers.length) {
throw new NotFoundException(ResponseMessages.oid4vp.error.notFound);
Expand All @@ -298,6 +300,24 @@ export class Oid4vpVerificationService extends BaseService {
}
}

async oid4vpPresentationWebhook(oid4vpPresentation: Oid4vpPresentationWh, id: string): Promise<object> {
try {
const { contextCorrelationId } = oid4vpPresentation ?? {};
let orgId: string;
if ('default' !== contextCorrelationId) {
const getOrganizationId = await this.oid4vpRepository.getOrganizationByTenantId(contextCorrelationId);
orgId = getOrganizationId?.orgId;
} else {
orgId = id;
}
const agentDetails = await this.oid4vpRepository.storeOid4vpPresentationDetails(oid4vpPresentation, orgId);
return agentDetails;
} catch (error) {
this.logger.error(`[storeOidcCredentialWebhook] - error: ${JSON.stringify(error)}`);
throw error;
}
}

async _createOid4vpVerifier(verifierDetails: CreateVerifier, url: string, orgId: string): Promise<any> {
this.logger.debug(`[_createOid4vpVerifier] sending NATS message for orgId=${orgId}`);
try {
Expand Down
2 changes: 1 addition & 1 deletion libs/common/src/common.constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ export enum CommonConstants {
URL_OIDC_VERIFIER_GET = '/openid4vc/verifier/#',
URL_OIDC_VERIFIER_SESSION_GET_BY_ID = '/openid4vc/verification-sessions/#',
URL_OIDC_VERIFIER_SESSION_GET_BY_QUERY = '/openid4vc/verification-sessions',
URL_OIDC_VERIFIER_SESSION_RESPONSE_GET_BY_ID = '/openid4vc/verification-sessions/response#',
URL_OIDC_VERIFIER_SESSION_RESPONSE_GET_BY_ID = '/openid4vc/verification-sessions/response/#',
URL_OID4VP_VERIFICATION_SESSION = '/openid4vc/verification-sessions/create-presentation-request',

//X509 agent API URLs
Expand Down
Loading