@verii/server-credentialagent 1.1.0-pre.1775532512 → 1.1.0-pre.1775534926

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verii/server-credentialagent",
3
- "version": "1.1.0-pre.1775532512",
3
+ "version": "1.1.0-pre.1775534926",
4
4
  "description": "Credential Agent application",
5
5
  "main": "src/index.js",
6
6
  "repository": "https://github.com/LFDT-Verii/core",
@@ -40,31 +40,31 @@
40
40
  "@fastify/view": "^11.0.0",
41
41
  "@spencejs/spence-factories": "^0.10.2",
42
42
  "@spencejs/spence-mongo-repos": "^0.10.2",
43
- "@verii/auth": "1.1.0-pre.1775532512",
44
- "@verii/base-contract-io": "1.1.0-pre.1775532512",
45
- "@verii/blockchain-functions": "1.1.0-pre.1775532512",
46
- "@verii/common-fetchers": "1.1.0-pre.1775532512",
47
- "@verii/common-functions": "1.1.0-pre.1775532512",
48
- "@verii/common-schemas": "1.1.0-pre.1775532512",
49
- "@verii/config": "1.1.0-pre.1775532512",
50
- "@verii/contract-permissions": "1.1.0-pre.1775532512",
51
- "@verii/crypto": "1.1.0-pre.1775532512",
52
- "@verii/csv-parser": "1.1.0-pre.1775532512",
53
- "@verii/db-kms": "1.1.0-pre.1775532512",
54
- "@verii/did-doc": "1.1.0-pre.1775532512",
55
- "@verii/fastify-plugins": "1.1.0-pre.1775532512",
56
- "@verii/http-client": "1.1.0-pre.1775532512",
57
- "@verii/jwt": "1.1.0-pre.1775532512",
58
- "@verii/metadata-registration": "1.1.0-pre.1775532512",
59
- "@verii/organizations-registry": "1.1.0-pre.1775532512",
60
- "@verii/rest-queries": "1.1.0-pre.1775532512",
61
- "@verii/server-provider": "1.1.0-pre.1775532512",
62
- "@verii/spencer-mongo-extensions": "1.1.0-pre.1775532512",
63
- "@verii/test-regexes": "1.1.0-pre.1775532512",
64
- "@verii/validation": "1.1.0-pre.1775532512",
65
- "@verii/vc-checks": "1.1.0-pre.1775532512",
66
- "@verii/verii-issuing": "1.1.0-pre.1775532512",
67
- "@verii/verii-verification": "1.1.0-pre.1775532512",
43
+ "@verii/auth": "1.1.0-pre.1775534926",
44
+ "@verii/base-contract-io": "1.1.0-pre.1775534926",
45
+ "@verii/blockchain-functions": "1.1.0-pre.1775534926",
46
+ "@verii/common-fetchers": "1.1.0-pre.1775534926",
47
+ "@verii/common-functions": "1.1.0-pre.1775534926",
48
+ "@verii/common-schemas": "1.1.0-pre.1775534926",
49
+ "@verii/config": "1.1.0-pre.1775534926",
50
+ "@verii/contract-permissions": "1.1.0-pre.1775534926",
51
+ "@verii/crypto": "1.1.0-pre.1775534926",
52
+ "@verii/csv-parser": "1.1.0-pre.1775534926",
53
+ "@verii/db-kms": "1.1.0-pre.1775534926",
54
+ "@verii/did-doc": "1.1.0-pre.1775534926",
55
+ "@verii/fastify-plugins": "1.1.0-pre.1775534926",
56
+ "@verii/http-client": "1.1.0-pre.1775534926",
57
+ "@verii/jwt": "1.1.0-pre.1775534926",
58
+ "@verii/metadata-registration": "1.1.0-pre.1775534926",
59
+ "@verii/organizations-registry": "1.1.0-pre.1775534926",
60
+ "@verii/rest-queries": "1.1.0-pre.1775534926",
61
+ "@verii/server-provider": "1.1.0-pre.1775534926",
62
+ "@verii/spencer-mongo-extensions": "1.1.0-pre.1775534926",
63
+ "@verii/test-regexes": "1.1.0-pre.1775534926",
64
+ "@verii/validation": "1.1.0-pre.1775534926",
65
+ "@verii/vc-checks": "1.1.0-pre.1775534926",
66
+ "@verii/verii-issuing": "1.1.0-pre.1775534926",
67
+ "@verii/verii-verification": "1.1.0-pre.1775534926",
68
68
  "ajv": "8.18.0",
69
69
  "canonicalize": "^2.1.0",
70
70
  "date-fns": "~4.1.0",
@@ -83,10 +83,10 @@
83
83
  },
84
84
  "devDependencies": {
85
85
  "@spencejs/spence-config": "0.10.2",
86
- "@verii/endpoints-organizations-registrar": "1.1.0-pre.1775532512",
87
- "@verii/sample-data": "1.1.0-pre.1775532512",
86
+ "@verii/endpoints-organizations-registrar": "1.1.0-pre.1775534926",
87
+ "@verii/sample-data": "1.1.0-pre.1775534926",
88
88
  "@verii/test-regexes": "0.5.0-build",
89
- "@verii/tests-helpers": "1.1.0-pre.1775532512",
89
+ "@verii/tests-helpers": "1.1.0-pre.1775534926",
90
90
  "cheerio": "1.2.0",
91
91
  "dotenv": "16.6.1",
92
92
  "eslint": "9.39.4",
@@ -108,5 +108,5 @@
108
108
  "prettier": "3.8.1",
109
109
  "qs": "6.15.0"
110
110
  },
111
- "gitHead": "8f2895f4eb63fbf76a1fc812b1ece8d1ee6613fa"
111
+ "gitHead": "b3405f6fa22cf94a249da7281d7fcbd06f4b7b7c"
112
112
  }
@@ -19,6 +19,7 @@ const { genericConfig, abi } = require('@verii/config');
19
19
  const packageJson = require('../../package.json');
20
20
 
21
21
  const { isTest } = genericConfig;
22
+ const secret = env.get('SECRET').required(!isTest).asString();
22
23
 
23
24
  const swaggerConfig = {
24
25
  swaggerInfo: {
@@ -70,7 +71,11 @@ const coreConfig = {
70
71
  .default('http://34.244.131.79:8547')
71
72
  .asString(),
72
73
  chainId: env.get('CHAIN_ID').default(2020).asInt(),
73
- secret: env.get('SECRET').required(!isTest).asString(),
74
+ secret,
75
+ issuingChallengeSecret: env
76
+ .get('ISSUING_CHALLENGE_SECRET')
77
+ .default(secret)
78
+ .asString(),
74
79
  vnfClientId: env.get('VNF_OAUTH_CLIENT_ID').required(!isTest).asString(),
75
80
  vnfClientSecret: env
76
81
  .get('VNF_OAUTH_CLIENT_SECRET')
@@ -91,7 +96,7 @@ const coreConfig = {
91
96
  enableProfiling: env.get('ENABLE_PROFILING').default('false').asBool(),
92
97
  enableSentryDebug: env.get('ENABLE_SENTRY_DEBUG').default('false').asBool(),
93
98
  deepLinkProtocol: env.get('DEEP_LINK_PROTOCOL').required().asString(),
94
- oidcTokensExpireIn: env.get('OIDC_TOKENS_EXPIRE_IN').asInt(),
99
+ oidcTokensExpireIn: env.get('OIDC_TOKENS_EXPIRE_IN').default(600).asInt(),
95
100
  enableOfferValidation: env
96
101
  .get('ENABLE_OFFER_VALIDATION')
97
102
  .default('true')
@@ -103,17 +103,14 @@ const controller = async (fastify) => {
103
103
  },
104
104
  }),
105
105
  },
106
- // eslint-disable-next-line complexity
106
+
107
107
  async (req, reply) => {
108
108
  const {
109
109
  user: { vendorUserId },
110
110
  body: { types = [], offerHashes = [] },
111
111
  exchange,
112
112
  repos,
113
- log,
114
113
  } = req;
115
- const { challenge, challengeIssuedAt } = generateIssuingChallenge();
116
-
117
114
  await repos.exchanges.addState(
118
115
  exchange._id,
119
116
  ExchangeStates.OFFERS_REQUESTED,
@@ -133,32 +130,24 @@ const controller = async (fastify) => {
133
130
  req,
134
131
  );
135
132
 
136
- if (status === 202) {
137
- await repos.exchanges.addState(
138
- exchange._id,
139
- ExchangeStates.OFFERS_WAITING_ON_VENDOR,
140
- { offerHashes, vendorUserId },
141
- );
142
- } else {
143
- const $set = {
144
- vendorUserId,
145
- offerIds: map('_id', offers),
146
- challenge,
147
- challengeIssuedAt,
148
- };
149
- if (!isEmpty(vendorOfferStatuses)) {
150
- $set.vendorOfferStatuses = vendorOfferStatuses;
151
- log.info({
133
+ const { challenge, exchangeState, exchangeStateData } =
134
+ await loadExchangeStateResult(
135
+ {
152
136
  exchangeId: exchange._id,
137
+ offers,
138
+ offerHashes,
139
+ status,
153
140
  vendorOfferStatuses,
154
- });
155
- }
156
- await repos.exchanges.addState(
157
- exchange._id,
158
- ExchangeStates.OFFERS_SENT,
159
- $set,
141
+ vendorUserId,
142
+ },
143
+ req,
160
144
  );
161
- }
145
+
146
+ await repos.exchanges.addState(
147
+ exchange._id,
148
+ exchangeState,
149
+ exchangeStateData,
150
+ );
162
151
 
163
152
  validateInvalidWebhookOffers(vendorOfferStatuses, req);
164
153
 
@@ -184,6 +173,46 @@ const controller = async (fastify) => {
184
173
  return offerMode;
185
174
  };
186
175
 
176
+ const loadExchangeStateResult = async (
177
+ {
178
+ exchangeId,
179
+ offers,
180
+ offerHashes,
181
+ status,
182
+ vendorOfferStatuses,
183
+ vendorUserId,
184
+ },
185
+ context,
186
+ ) => {
187
+ if (status === 202) {
188
+ return {
189
+ challenge: undefined,
190
+ exchangeState: ExchangeStates.OFFERS_WAITING_ON_VENDOR,
191
+ exchangeStateData: { offerHashes, vendorUserId },
192
+ };
193
+ }
194
+
195
+ const { challenge } = await generateIssuingChallenge(exchangeId, context);
196
+ const exchangeStateData = {
197
+ vendorUserId,
198
+ offerIds: map('_id', offers),
199
+ };
200
+
201
+ if (!isEmpty(vendorOfferStatuses)) {
202
+ exchangeStateData.vendorOfferStatuses = vendorOfferStatuses;
203
+ context.log.info({
204
+ exchangeId,
205
+ vendorOfferStatuses,
206
+ });
207
+ }
208
+
209
+ return {
210
+ challenge,
211
+ exchangeState: ExchangeStates.OFFERS_SENT,
212
+ exchangeStateData,
213
+ };
214
+ };
215
+
187
216
  const loadAllOffers = async (
188
217
  { vendorUserId, types, offerHashes },
189
218
  context,
@@ -35,8 +35,6 @@ const exchangeRepoDefaultProjection = {
35
35
  vendorOfferStatuses: 1,
36
36
  finalizedOfferIds: 1,
37
37
  credentialTypes: 1,
38
- challenge: 1,
39
- challengeIssuedAt: 1,
40
38
  err: 1,
41
39
  };
42
40
 
@@ -16,11 +16,28 @@
16
16
 
17
17
  const { getUnixTime } = require('date-fns/fp');
18
18
  const { nanoid } = require('nanoid');
19
- const { ISSUING_CHALLENGE_SIZE } = require('./constants');
19
+ const { jwtSign } = require('@verii/jwt');
20
20
 
21
- const generateIssuingChallenge = () => ({
22
- challenge: nanoid(ISSUING_CHALLENGE_SIZE),
23
- challengeIssuedAt: getUnixTime(new Date()),
24
- });
21
+ const generateIssuingChallenge = async (
22
+ exchangeId,
23
+ { config: { hostUrl, oidcTokensExpireIn, issuingChallengeSecret } },
24
+ ) => {
25
+ const challengeIssuedAt = getUnixTime(new Date());
26
+
27
+ return {
28
+ challenge: await jwtSign(
29
+ { exchangeId: exchangeId.toString() },
30
+ issuingChallengeSecret,
31
+ {
32
+ alg: 'HS256',
33
+ audience: hostUrl,
34
+ exp: challengeIssuedAt + oidcTokensExpireIn,
35
+ iat: challengeIssuedAt,
36
+ issuer: hostUrl,
37
+ jti: nanoid(),
38
+ },
39
+ ),
40
+ };
41
+ };
25
42
 
26
43
  module.exports = { generateIssuingChallenge };
@@ -17,8 +17,8 @@
17
17
  const { first, startsWith, isEmpty, lastIndexOf } = require('lodash/fp');
18
18
  const { jwtVerify, jwtHeaderDecode, jwkThumbprint } = require('@verii/jwt');
19
19
  const newError = require('http-errors');
20
- const { getUnixTime } = require('date-fns/fp');
21
20
  const { resolveDidJwkDocument } = require('@verii/did-doc');
21
+ const { verifyIssuingChallenge } = require('./verify-issuing-challenge');
22
22
 
23
23
  const resolveSubject = async (proof, context) => {
24
24
  verifyProofStructure(proof);
@@ -101,10 +101,10 @@ const extractDidJwkWithoutSuffix = (jwkIdentifier) => {
101
101
  };
102
102
 
103
103
  const verifyProofJwt = async (
104
- { challenge, challengeIssuedAt },
104
+ exchange,
105
105
  { jwt },
106
106
  jwk,
107
- { config: { hostUrl, oidcTokensExpireIn } },
107
+ { config: { hostUrl, issuingChallengeSecret } },
108
108
  ) => {
109
109
  let payload;
110
110
  try {
@@ -122,21 +122,38 @@ const verifyProofJwt = async (
122
122
  });
123
123
  }
124
124
 
125
- if (payload.nonce !== challenge) {
126
- throw newError(
127
- 400,
128
- 'The nonce in the jwt does not match the supplied c_nonce',
129
- {
130
- errorCode: 'proof_challenge_mismatch',
131
- },
132
- );
125
+ try {
126
+ await verifyIssuingChallenge(payload.nonce, exchange._id, {
127
+ hostUrl,
128
+ issuingChallengeSecret,
129
+ });
130
+ } catch (error) {
131
+ throwChallengeVerificationError(error);
133
132
  }
133
+ };
134
134
 
135
- if (challengeIssuedAt + oidcTokensExpireIn < getUnixTime(new Date())) {
136
- throw newError(400, 'The c_nonce in the jwt has expired', {
137
- errorCode: 'proof_challenge_expired',
138
- });
135
+ const throwExpiredChallengeError = () => {
136
+ throw newError(400, 'The c_nonce in the jwt has expired', {
137
+ errorCode: 'proof_challenge_expired',
138
+ });
139
+ };
140
+
141
+ const throwChallengeMismatchError = () => {
142
+ throw newError(
143
+ 400,
144
+ 'The nonce in the jwt does not match the supplied c_nonce',
145
+ {
146
+ errorCode: 'proof_challenge_mismatch',
147
+ },
148
+ );
149
+ };
150
+
151
+ const throwChallengeVerificationError = (error) => {
152
+ if (error?.code === 'ERR_JWT_EXPIRED' || error?.name === 'JWTExpired') {
153
+ throwExpiredChallengeError();
139
154
  }
155
+
156
+ throwChallengeMismatchError();
140
157
  };
141
158
 
142
159
  module.exports = { resolveSubject };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Copyright 2023 Velocity Team
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ const { jwtVerify } = require('@verii/jwt');
18
+
19
+ const verifyIssuingChallenge = async (
20
+ challenge,
21
+ exchangeId,
22
+ { hostUrl, issuingChallengeSecret },
23
+ ) => {
24
+ const { payload } = await jwtVerify(challenge, issuingChallengeSecret, {
25
+ algorithms: ['HS256'],
26
+ audience: hostUrl,
27
+ issuer: hostUrl,
28
+ });
29
+
30
+ if (payload.exchangeId !== exchangeId.toString()) {
31
+ throw new Error('challenge_exchange_mismatch');
32
+ }
33
+
34
+ return payload;
35
+ };
36
+
37
+ module.exports = { verifyIssuingChallenge };
@@ -217,8 +217,6 @@ describe('e2e issuing tests', { timeout: 45000 }, () => {
217
217
  },
218
218
  ],
219
219
  vendorUserId: user.vendorUserId,
220
- challenge: 'challenge',
221
- challengeIssuedAt: 12341,
222
220
  });
223
221
 
224
222
  authToken = await genAuthToken(tenant, tenantKeys, exchange, user, keyPair);
@@ -522,8 +522,6 @@ describe('Holder Issuing Test Suite', () => {
522
522
  overrides: {
523
523
  err: `Exchange ${emptyExchange._id} is in an invalid state`,
524
524
  offerIds: undefined,
525
- challenge: undefined,
526
- challengeIssuedAt: undefined,
527
525
  },
528
526
  states: [
529
527
  ExchangeStates.NEW,
@@ -713,10 +711,6 @@ describe('Holder Issuing Test Suite', () => {
713
711
  exchangeId,
714
712
  disclosure,
715
713
  user,
716
- overrides: {
717
- challenge: undefined,
718
- challengeIssuedAt: undefined,
719
- },
720
714
  states: [
721
715
  ExchangeStates.NEW,
722
716
  ExchangeStates.IDENTIFIED,
@@ -1026,8 +1020,6 @@ describe('Holder Issuing Test Suite', () => {
1026
1020
  overrides: {
1027
1021
  err: '2 offer(s) without offerId received from vendor',
1028
1022
  offerIds: undefined,
1029
- challenge: undefined,
1030
- challengeIssuedAt: undefined,
1031
1023
  },
1032
1024
  }),
1033
1025
  );
@@ -2132,8 +2124,6 @@ describe('Holder Issuing Test Suite', () => {
2132
2124
  ],
2133
2125
  overrides: {
2134
2126
  offerHashes: [],
2135
- challenge: undefined,
2136
- challengeIssuedAt: undefined,
2137
2127
  },
2138
2128
  omitList: ['offerIds'],
2139
2129
  }),
@@ -3119,17 +3109,25 @@ describe('Holder Issuing Test Suite', () => {
3119
3109
  vendorOfferStatuses: {
3120
3110
  [vendorOffer.offerId]: 'OK',
3121
3111
  },
3122
- challenge: expect.any(String),
3123
- challengeIssuedAt: expect.any(Number),
3124
3112
  },
3125
3113
  }),
3126
3114
  );
3127
- expect(exchangeFromDb.challenge).toHaveLength(16);
3128
- expect(exchangeFromDb.challengeIssuedAt).toBeLessThanOrEqual(
3129
- getUnixTime(new Date()),
3115
+ const { header: challengeHeader, payload: challengePayload } = jwtDecode(
3116
+ response.json.challenge,
3130
3117
  );
3131
- expect(exchangeFromDb.challengeIssuedAt).toBeGreaterThan(
3132
- getUnixTime(new Date()) - 5,
3118
+ expect(response.json.challenge.split('.')).toHaveLength(3);
3119
+ expect(challengeHeader).toEqual(
3120
+ expect.objectContaining({
3121
+ alg: 'HS256',
3122
+ typ: 'JWT',
3123
+ }),
3124
+ );
3125
+ expect(challengePayload).toEqual(
3126
+ expect.objectContaining({
3127
+ exchangeId: exchangeId.toString(),
3128
+ iss: fastify.config.hostUrl,
3129
+ aud: fastify.config.hostUrl,
3130
+ }),
3133
3131
  );
3134
3132
  expect(getSchemaNock.isDone()).toEqual(true);
3135
3133
  });
@@ -4425,8 +4423,6 @@ describe('Holder Issuing Test Suite', () => {
4425
4423
  beforeEach(async () => {
4426
4424
  await exchangeRepo.update(exchangeId, {
4427
4425
  vendorUserId: user.vendorUserId,
4428
- challenge: 'challenge',
4429
- challengeIssuedAt: 12341,
4430
4426
  });
4431
4427
  nockCredentialTypes();
4432
4428
  offer0 = await persistFinalizableOffer({
@@ -6407,8 +6403,13 @@ describe('Holder Issuing Test Suite', () => {
6407
6403
  let joseKeyPair;
6408
6404
  let proofKeyPair;
6409
6405
  let didJwk;
6406
+ const loadChallengeConfig = () => ({
6407
+ challengeIssuer: fastify.config.hostUrl,
6408
+ challengeSecret: fastify.config.issuingChallengeSecret,
6409
+ challengeTtl: fastify.config.oidcTokensExpireIn,
6410
+ });
6410
6411
 
6411
- const prepareData = async (challengeIssuedAt) => {
6412
+ const prepareData = async () => {
6412
6413
  exchange = await persistOfferExchange({
6413
6414
  tenant,
6414
6415
  disclosure,
@@ -6420,8 +6421,6 @@ describe('Holder Issuing Test Suite', () => {
6420
6421
  },
6421
6422
  ],
6422
6423
  vendorUserId: 'abcdefg123454',
6423
- challenge: 'mockchallenge',
6424
- challengeIssuedAt: challengeIssuedAt ?? new Date().valueOf() / 1000,
6425
6424
  });
6426
6425
  offer = offer0;
6427
6426
  exchangeId = exchange._id;
@@ -6429,6 +6428,43 @@ describe('Holder Issuing Test Suite', () => {
6429
6428
  authToken = await genAuthToken(tenant, exchange);
6430
6429
  };
6431
6430
 
6431
+ const buildSignedChallenge = async (
6432
+ challengePayload = {},
6433
+ challengeOptions = {},
6434
+ ) => {
6435
+ const { challengeIssuer, challengeSecret, challengeTtl } =
6436
+ loadChallengeConfig();
6437
+ const issuedAt = challengeOptions.iat ?? getUnixTime(new Date());
6438
+ return jwtSign(
6439
+ { exchangeId: exchangeId.toString(), ...challengePayload },
6440
+ challengeSecret,
6441
+ {
6442
+ alg: 'HS256',
6443
+ audience: challengeIssuer,
6444
+ exp: challengeOptions.exp ?? issuedAt + challengeTtl,
6445
+ iat: issuedAt,
6446
+ issuer: challengeIssuer,
6447
+ jti: challengeOptions.jti ?? nanoid(),
6448
+ },
6449
+ );
6450
+ };
6451
+
6452
+ const postCredentialOffers = async (
6453
+ payload = {
6454
+ exchangeId,
6455
+ types: castArray(offer.type),
6456
+ },
6457
+ ) =>
6458
+ fastify.injectJson({
6459
+ method: 'POST',
6460
+ url: issuingUrl(tenant, 'credential-offers'),
6461
+ payload,
6462
+ headers: {
6463
+ authorization: `Bearer ${authToken}`,
6464
+ 'x-vnf-protocol-version': '2',
6465
+ },
6466
+ });
6467
+
6432
6468
  beforeEach(async () => {
6433
6469
  await prepareData();
6434
6470
  joseKeyPair = await joseGenerateKeyPair('ES256K');
@@ -6653,13 +6689,36 @@ describe('Holder Issuing Test Suite', () => {
6653
6689
  }),
6654
6690
  );
6655
6691
  });
6656
- it('should return error if challenge is expired', async () => {
6657
- await prepareData(getUnixTime(subYears(25, new Date())));
6692
+ it('should return 200 if signed challenge remains valid after duplicate credential-offers calls', async () => {
6693
+ const firstOffersResponse = await postCredentialOffers();
6694
+ const secondOffersResponse = await postCredentialOffers();
6695
+
6696
+ expect(firstOffersResponse.statusCode).toEqual(200);
6697
+ expect(secondOffersResponse.statusCode).toEqual(200);
6658
6698
  const response = await postFinalizeOffers({
6659
6699
  exchangeId,
6660
6700
  approvedOfferIds: [offer._id],
6661
- proof: await buildProof(didJwk, proofKeyPair, exchange.challenge),
6701
+ proof: await buildProof(
6702
+ didJwk,
6703
+ proofKeyPair,
6704
+ firstOffersResponse.json.challenge,
6705
+ ),
6662
6706
  });
6707
+
6708
+ expect(response.statusCode).toEqual(200);
6709
+ });
6710
+ it('should return error if signed challenge token is expired', async () => {
6711
+ const issuedAt = getUnixTime(subYears(25, new Date()));
6712
+ const response = await postFinalizeOffers({
6713
+ exchangeId,
6714
+ approvedOfferIds: [offer._id],
6715
+ proof: await buildProof(
6716
+ didJwk,
6717
+ proofKeyPair,
6718
+ await buildSignedChallenge({}, { exp: issuedAt, iat: issuedAt }),
6719
+ ),
6720
+ });
6721
+
6663
6722
  expect(response.statusCode).toEqual(400);
6664
6723
  expect(response.json).toEqual(
6665
6724
  errorResponseMatcher({
@@ -6670,11 +6729,54 @@ describe('Holder Issuing Test Suite', () => {
6670
6729
  }),
6671
6730
  );
6672
6731
  });
6732
+ it('should return error if signed challenge token exchange is invalid', async () => {
6733
+ const response = await postFinalizeOffers({
6734
+ exchangeId,
6735
+ approvedOfferIds: [offer._id],
6736
+ proof: await buildProof(
6737
+ didJwk,
6738
+ proofKeyPair,
6739
+ await buildSignedChallenge({
6740
+ exchangeId: new ObjectId().toString(),
6741
+ }),
6742
+ ),
6743
+ });
6744
+
6745
+ expect(response.statusCode).toEqual(400);
6746
+ expect(response.json).toEqual(
6747
+ errorResponseMatcher({
6748
+ error: 'Bad Request',
6749
+ errorCode: 'proof_challenge_mismatch',
6750
+ message: 'The nonce in the jwt does not match the supplied c_nonce',
6751
+ statusCode: 400,
6752
+ }),
6753
+ );
6754
+ });
6755
+ it('should return error if signed challenge token is tampered', async () => {
6756
+ const signedChallenge = await buildSignedChallenge();
6757
+ const tamperedChallenge = `${signedChallenge}a`;
6758
+ const response = await postFinalizeOffers({
6759
+ exchangeId,
6760
+ approvedOfferIds: [offer._id],
6761
+ proof: await buildProof(didJwk, proofKeyPair, tamperedChallenge),
6762
+ });
6763
+
6764
+ expect(response.statusCode).toEqual(400);
6765
+ expect(response.json).toEqual(
6766
+ errorResponseMatcher({
6767
+ error: 'Bad Request',
6768
+ errorCode: 'proof_challenge_mismatch',
6769
+ message: 'The nonce in the jwt does not match the supplied c_nonce',
6770
+ statusCode: 400,
6771
+ }),
6772
+ );
6773
+ });
6673
6774
  it('should return 200 and approve offer ES256K alg', async () => {
6775
+ const challenge = await buildSignedChallenge();
6674
6776
  const response = await postFinalizeOffers({
6675
6777
  exchangeId,
6676
6778
  approvedOfferIds: [offer._id],
6677
- proof: await buildProof(didJwk, proofKeyPair, exchange.challenge),
6779
+ proof: await buildProof(didJwk, proofKeyPair, challenge),
6678
6780
  });
6679
6781
  expect(response.statusCode).toEqual(200);
6680
6782
  expect(response.json).toHaveLength(1);
@@ -6726,8 +6828,6 @@ describe('Holder Issuing Test Suite', () => {
6726
6828
  offerIds: [offer._id],
6727
6829
  overrides: {
6728
6830
  finalizedOfferIds: mapToObjectId([offer._id]),
6729
- challenge: exchange.challenge,
6730
- challengeIssuedAt: exchange.challengeIssuedAt,
6731
6831
  vendorUserId: exchange.vendorUserId,
6732
6832
  },
6733
6833
  }),
@@ -6740,10 +6840,11 @@ describe('Holder Issuing Test Suite', () => {
6740
6840
  publicKey: await exportJWK(joseKeyPair.publicKey),
6741
6841
  };
6742
6842
  didJwk = getDidUriFromJwk(proofKeyPair.publicKey);
6843
+ const challenge = await buildSignedChallenge();
6743
6844
  const response = await postFinalizeOffers({
6744
6845
  exchangeId,
6745
6846
  approvedOfferIds: [offer._id],
6746
- proof: await buildProof(didJwk, proofKeyPair, exchange.challenge),
6847
+ proof: await buildProof(didJwk, proofKeyPair, challenge),
6747
6848
  });
6748
6849
  expect(response.statusCode).toEqual(200);
6749
6850
  expect(response.json).toHaveLength(1);
@@ -6795,23 +6896,17 @@ describe('Holder Issuing Test Suite', () => {
6795
6896
  offerIds: [offer._id],
6796
6897
  overrides: {
6797
6898
  finalizedOfferIds: mapToObjectId([offer._id]),
6798
- challenge: exchange.challenge,
6799
- challengeIssuedAt: exchange.challengeIssuedAt,
6800
6899
  vendorUserId: exchange.vendorUserId,
6801
6900
  },
6802
6901
  }),
6803
6902
  );
6804
6903
  });
6805
6904
  it('should return 200 and approve offer with credential subject id jwkThumbprint format', async () => {
6905
+ const challenge = await buildSignedChallenge();
6806
6906
  const response = await postFinalizeOffers({
6807
6907
  exchangeId,
6808
6908
  approvedOfferIds: [offer._id],
6809
- proof: await buildProof(
6810
- didJwk,
6811
- proofKeyPair,
6812
- exchange.challenge,
6813
- false,
6814
- ),
6909
+ proof: await buildProof(didJwk, proofKeyPair, challenge, false),
6815
6910
  });
6816
6911
  const didJwkThumbprint = await jwkThumbprint(proofKeyPair.publicKey);
6817
6912
  expect(response.statusCode).toEqual(200);
@@ -6864,8 +6959,6 @@ describe('Holder Issuing Test Suite', () => {
6864
6959
  offerIds: [offer._id],
6865
6960
  overrides: {
6866
6961
  finalizedOfferIds: mapToObjectId([offer._id]),
6867
- challenge: exchange.challenge,
6868
- challengeIssuedAt: exchange.challengeIssuedAt,
6869
6962
  vendorUserId: exchange.vendorUserId,
6870
6963
  },
6871
6964
  }),
@@ -7048,8 +7141,6 @@ const exchangeExpectation = ({
7048
7141
  offerHashes: [],
7049
7142
  offerIds: expect.arrayContaining(mapToObjectId(offerIds)),
7050
7143
  vendorUserId: user?.vendorUserId,
7051
- challenge: expect.any(String),
7052
- challengeIssuedAt: expect.any(Number),
7053
7144
  ...credentialTypesObject,
7054
7145
  createdAt: expect.any(Date),
7055
7146
  updatedAt: expect.any(Date),
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Copyright 2023 Velocity Team
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ const { describe, it } = require('node:test');
18
+ const { expect } = require('expect');
19
+
20
+ const {
21
+ resolveSubject,
22
+ } = require('../../src/entities/offers/domains/resolve-subject');
23
+
24
+ describe('resolveSubject', () => {
25
+ it('should throw error if proof is missing', async () => {
26
+ await expect(resolveSubject(null, {})).rejects.toMatchObject({
27
+ errorCode: 'invalid_or_missing_proof',
28
+ message: 'proof is missing',
29
+ statusCode: 400,
30
+ });
31
+ });
32
+
33
+ it("should throw error if proof_type isn't jwt", async () => {
34
+ await expect(
35
+ resolveSubject(
36
+ {
37
+ proof_type: 'cwt',
38
+ jwt: 'unused',
39
+ },
40
+ {},
41
+ ),
42
+ ).rejects.toMatchObject({
43
+ errorCode: 'proof_type_invalid',
44
+ message: "proof_type isn't set to jwt",
45
+ statusCode: 400,
46
+ });
47
+ });
48
+ });