arocapi 5.0.0-beta.2 → 5.0.0-beta.3

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.
Files changed (117) hide show
  1. package/README.md +37 -824
  2. package/dist/app.d.ts +20 -7
  3. package/dist/app.js +42 -28
  4. package/dist/app.js.map +1 -1
  5. package/dist/app.test.js +41 -56
  6. package/dist/app.test.js.map +1 -1
  7. package/dist/errorHandling.test.d.ts +1 -0
  8. package/dist/errorHandling.test.js +222 -0
  9. package/dist/errorHandling.test.js.map +1 -0
  10. package/dist/index.dev.js +4 -3
  11. package/dist/index.dev.js.map +1 -1
  12. package/dist/routes/capabilities.test.js +8 -8
  13. package/dist/routes/capabilities.test.js.map +1 -1
  14. package/dist/routes/crate.test.js +67 -19
  15. package/dist/routes/crate.test.js.map +1 -1
  16. package/dist/routes/entities.d.ts +5 -2
  17. package/dist/routes/entities.js +31 -49
  18. package/dist/routes/entities.js.map +1 -1
  19. package/dist/routes/entities.test.js +16 -12
  20. package/dist/routes/entities.test.js.map +1 -1
  21. package/dist/routes/entity.d.ts +7 -2
  22. package/dist/routes/entity.js +14 -29
  23. package/dist/routes/entity.js.map +1 -1
  24. package/dist/routes/entity.test.js +19 -13
  25. package/dist/routes/entity.test.js.map +1 -1
  26. package/dist/routes/file.d.ts +6 -0
  27. package/dist/routes/file.js +67 -59
  28. package/dist/routes/file.js.map +1 -1
  29. package/dist/routes/file.test.js +99 -22
  30. package/dist/routes/file.test.js.map +1 -1
  31. package/dist/routes/files.d.ts +5 -2
  32. package/dist/routes/files.js +24 -39
  33. package/dist/routes/files.js.map +1 -1
  34. package/dist/routes/files.test.js +44 -21
  35. package/dist/routes/files.test.js.map +1 -1
  36. package/dist/routes/metadata.d.ts +6 -0
  37. package/dist/routes/metadata.js +49 -54
  38. package/dist/routes/metadata.js.map +1 -1
  39. package/dist/routes/search.d.ts +6 -2
  40. package/dist/routes/search.js +95 -99
  41. package/dist/routes/search.js.map +1 -1
  42. package/dist/routes/search.test.js +85 -39
  43. package/dist/routes/search.test.js.map +1 -1
  44. package/dist/test/helpers/fastify.js +2 -3
  45. package/dist/test/helpers/fastify.js.map +1 -1
  46. package/dist/test/integration.setup.d.ts +18 -0
  47. package/dist/test/integration.setup.js +15 -7
  48. package/dist/test/integration.setup.js.map +1 -1
  49. package/dist/test/integration.test.js +368 -2
  50. package/dist/test/integration.test.js.map +1 -1
  51. package/dist/transformers/default.d.ts +10 -18
  52. package/dist/transformers/default.js +41 -15
  53. package/dist/transformers/default.js.map +1 -1
  54. package/dist/transformers/default.test.js +109 -47
  55. package/dist/transformers/default.test.js.map +1 -1
  56. package/dist/transformers/transformer.test.js +12 -34
  57. package/dist/transformers/transformer.test.js.map +1 -1
  58. package/dist/types/access.d.ts +9 -0
  59. package/dist/types/access.js +2 -0
  60. package/dist/types/access.js.map +1 -0
  61. package/dist/types/context.d.ts +6 -0
  62. package/dist/types/context.js +2 -0
  63. package/dist/types/context.js.map +1 -0
  64. package/dist/types/fileHandlers.d.ts +5 -9
  65. package/dist/types/transformers.d.ts +4 -10
  66. package/dist/types/visibility.d.ts +5 -0
  67. package/dist/types/visibility.js +2 -0
  68. package/dist/types/visibility.js.map +1 -0
  69. package/dist/utils/access.d.ts +17 -0
  70. package/dist/utils/access.js +41 -0
  71. package/dist/utils/access.js.map +1 -0
  72. package/dist/utils/errors.d.ts +13 -4
  73. package/dist/utils/errors.js +44 -8
  74. package/dist/utils/errors.js.map +1 -1
  75. package/dist/utils/errors.test.js +14 -1
  76. package/dist/utils/errors.test.js.map +1 -1
  77. package/dist/utils/validation.d.ts +2 -0
  78. package/dist/utils/validation.js +8 -0
  79. package/dist/utils/validation.js.map +1 -0
  80. package/dist/utils/visibility.d.ts +18 -0
  81. package/dist/utils/visibility.js +16 -0
  82. package/dist/utils/visibility.js.map +1 -0
  83. package/package.json +5 -4
  84. package/src/app.test.ts +45 -66
  85. package/src/app.ts +85 -54
  86. package/src/errorHandling.test.ts +288 -0
  87. package/src/index.dev.ts +6 -4
  88. package/src/routes/__snapshots__/search.test.ts.snap +2 -2
  89. package/src/routes/capabilities.test.ts +8 -8
  90. package/src/routes/crate.test.ts +80 -19
  91. package/src/routes/entities.test.ts +16 -12
  92. package/src/routes/entities.ts +40 -59
  93. package/src/routes/entity.test.ts +19 -13
  94. package/src/routes/entity.ts +22 -35
  95. package/src/routes/file.test.ts +117 -22
  96. package/src/routes/file.ts +84 -62
  97. package/src/routes/files.test.ts +52 -26
  98. package/src/routes/files.ts +31 -47
  99. package/src/routes/metadata.ts +64 -58
  100. package/src/routes/search.test.ts +88 -39
  101. package/src/routes/search.ts +123 -119
  102. package/src/test/helpers/fastify.ts +2 -3
  103. package/src/test/integration.setup.ts +18 -7
  104. package/src/test/integration.test.ts +472 -1
  105. package/src/transformers/default.test.ts +139 -47
  106. package/src/transformers/default.ts +103 -83
  107. package/src/transformers/transformer.test.ts +18 -44
  108. package/src/types/access.ts +20 -0
  109. package/src/types/context.ts +15 -0
  110. package/src/types/fileHandlers.ts +5 -13
  111. package/src/types/transformers.ts +4 -32
  112. package/src/types/visibility.ts +18 -0
  113. package/src/utils/access.ts +80 -0
  114. package/src/utils/errors.test.ts +16 -1
  115. package/src/utils/errors.ts +67 -10
  116. package/src/utils/validation.ts +11 -0
  117. package/src/utils/visibility.ts +56 -0
@@ -0,0 +1,288 @@
1
+ import sensible from '@fastify/sensible';
2
+ import Fastify from 'fastify';
3
+ import { serializerCompiler, validatorCompiler, type ZodTypeProvider } from 'fastify-type-provider-zod';
4
+ import { describe, expect, it, vi } from 'vitest';
5
+ import { z } from 'zod';
6
+
7
+ import arocapi, {
8
+ AllPublicAccess,
9
+ AllVisibleEntityFilter,
10
+ AllVisibleSearchFilter,
11
+ errorHandler,
12
+ notFoundHandler,
13
+ } from './app.js';
14
+ import { opensearch, prisma } from './test/helpers/fastify.js';
15
+
16
+ const arocapiOptions = {
17
+ prisma,
18
+ opensearch,
19
+ access: AllPublicAccess,
20
+ fileHandler: { get: vi.fn(), head: vi.fn() },
21
+ roCrateHandler: { get: vi.fn(), head: vi.fn() },
22
+ entityVisibilityFilter: AllVisibleEntityFilter,
23
+ searchVisibilityFilter: AllVisibleSearchFilter,
24
+ };
25
+
26
+ const internalErrorBody = { error: { code: 'INTERNAL_ERROR', message: 'Internal server error' } };
27
+ const notFoundBody = { error: { code: 'NOT_FOUND', message: 'The requested resource was not found' } };
28
+ const message = 'Something specific went wrong';
29
+
30
+ const buildConsumer = () => {
31
+ const logs: Record<string, unknown>[] = [];
32
+ const fastify = Fastify({
33
+ logger: {
34
+ level: 'info',
35
+ stream: { write: (line: string) => logs.push(JSON.parse(line) as Record<string, unknown>) },
36
+ },
37
+ });
38
+
39
+ fastify.setValidatorCompiler(validatorCompiler);
40
+ fastify.setSerializerCompiler(serializerCompiler);
41
+ fastify.setErrorHandler(errorHandler);
42
+ fastify.setNotFoundHandler(notFoundHandler);
43
+
44
+ return { fastify, logs };
45
+ };
46
+
47
+ describe('Error handling for consumer routes', () => {
48
+ it('hides unexpected errors behind a generic 500 and logs them', async () => {
49
+ const { fastify, logs } = buildConsumer();
50
+ fastify.get('/boom', async () => {
51
+ throw new Error('db password is hunter2');
52
+ });
53
+
54
+ const response = await fastify.inject({ method: 'GET', url: '/boom' });
55
+
56
+ expect(response.statusCode).toBe(500);
57
+ expect(response.json()).toEqual(internalErrorBody);
58
+ expect(
59
+ logs.some((l) => l.level === 50 && (l.err as { message: string }).message === 'db password is hunter2'),
60
+ ).toBe(true);
61
+ });
62
+
63
+ it.each([
64
+ [400, 400, { error: { code: 'VALIDATION_ERROR', message } }],
65
+ [401, 401, { error: { code: 'UNAUTHORIZED', message } }],
66
+ [403, 403, { error: { code: 'FORBIDDEN', message } }],
67
+ [404, 404, { error: { code: 'NOT_FOUND', message } }],
68
+ [405, 405, { error: { code: 'VALIDATION_ERROR', message } }],
69
+ [409, 409, { error: { code: 'CONFLICT', message } }],
70
+ [413, 413, { error: { code: 'VALIDATION_ERROR', message } }],
71
+ [416, 416, { error: { code: 'RANGE_NOT_SATISFIABLE', message } }],
72
+ [422, 422, { error: { code: 'VALIDATION_ERROR', message } }],
73
+ [429, 429, { error: { code: 'RATE_LIMIT_EXCEEDED', message } }],
74
+ [503, 500, internalErrorBody],
75
+ ])('answers a thrown %i http error with %i in the spec shape', async (thrown, status, body) => {
76
+ const { fastify } = buildConsumer();
77
+ await fastify.register(sensible);
78
+ fastify.get('/fail', async () => {
79
+ throw fastify.httpErrors.createError(thrown, message);
80
+ });
81
+
82
+ const response = await fastify.inject({ method: 'GET', url: '/fail' });
83
+
84
+ expect(response.statusCode).toBe(status);
85
+ expect(response.json()).toEqual(body);
86
+ });
87
+
88
+ it('keeps headers carried by the error', async () => {
89
+ const { fastify } = buildConsumer();
90
+ await fastify.register(sensible);
91
+ fastify.get('/fail', async () => {
92
+ throw fastify.httpErrors.createError(401, message, { headers: { 'www-authenticate': 'Bearer' } });
93
+ });
94
+
95
+ const response = await fastify.inject({ method: 'GET', url: '/fail' });
96
+
97
+ expect(response.statusCode).toBe(401);
98
+ expect(response.headers['www-authenticate']).toBe('Bearer');
99
+ });
100
+
101
+ it('hides a library error with a 4xx status behind a generic 500 and logs it with its stack', async () => {
102
+ const { fastify, logs } = buildConsumer();
103
+ const raw = 'index_not_found_exception: no such index [items-v2]';
104
+ fastify.get('/fail', async () => {
105
+ throw Object.assign(new Error(raw), { name: 'ResponseError', statusCode: 404, meta: { statusCode: 404 } });
106
+ });
107
+
108
+ const response = await fastify.inject({ method: 'GET', url: '/fail' });
109
+
110
+ expect(response.statusCode).toBe(500);
111
+ expect(response.json()).toEqual(internalErrorBody);
112
+ expect(response.body).not.toContain('items-v2');
113
+ const logged = logs.find((l) => l.level === 50)?.err as { message: string; stack: string } | undefined;
114
+ expect(logged?.message).toBe(raw);
115
+ expect(logged?.stack).toContain(raw);
116
+ });
117
+
118
+ it('keeps the status and message of a custom error marked expose', async () => {
119
+ class ConflictError extends Error {
120
+ statusCode = 409;
121
+ expose = true;
122
+ }
123
+ const { fastify } = buildConsumer();
124
+ fastify.get('/fail', async () => {
125
+ throw new ConflictError(message);
126
+ });
127
+
128
+ const response = await fastify.inject({ method: 'GET', url: '/fail' });
129
+
130
+ expect(response.statusCode).toBe(409);
131
+ expect(response.json()).toEqual({ error: { code: 'CONFLICT', message } });
132
+ });
133
+
134
+ it.each([
135
+ ['an invalid JSON body', { 'content-type': 'application/json' }, '{"broken', 400],
136
+ ['an oversized body', { 'content-type': 'application/json' }, JSON.stringify({ big: 'x'.repeat(200) }), 413],
137
+ ['an unsupported media type', { 'content-type': 'application/x-unknown' }, 'whatever', 415],
138
+ ])("keeps Fastify's own client error for %s", async (_label, headers, payload, status) => {
139
+ const { fastify } = buildConsumer();
140
+ fastify.post('/things', { bodyLimit: 100 }, async () => ({}));
141
+
142
+ const response = await fastify.inject({ method: 'POST', url: '/things', headers, payload });
143
+
144
+ expect(response.statusCode).toBe(status);
145
+ expect(response.json().error.code).toBe('VALIDATION_ERROR');
146
+ expect(response.json().error.message).not.toBe('');
147
+ });
148
+
149
+ it('hides errors that carry only a status behind a generic 500', async () => {
150
+ const { fastify } = buildConsumer();
151
+ fastify.get('/fail', async () => {
152
+ throw Object.assign(new Error(message), { status: 403 });
153
+ });
154
+
155
+ const response = await fastify.inject({ method: 'GET', url: '/fail' });
156
+
157
+ expect(response.statusCode).toBe(500);
158
+ expect(response.json()).toEqual(internalErrorBody);
159
+ });
160
+
161
+ it('maps a thrown plain object marked expose with no message', async () => {
162
+ const { fastify } = buildConsumer();
163
+ fastify.get('/fail', async () => {
164
+ throw { statusCode: 404, expose: true };
165
+ });
166
+
167
+ const response = await fastify.inject({ method: 'GET', url: '/fail' });
168
+
169
+ expect(response.statusCode).toBe(404);
170
+ expect(response.json()).toEqual({ error: { code: 'NOT_FOUND', message: '' } });
171
+ });
172
+
173
+ it('hides an error with a non-string code behind a generic 500', async () => {
174
+ const { fastify } = buildConsumer();
175
+ fastify.get('/fail', async () => {
176
+ throw Object.assign(new Error(message), { code: 14, statusCode: 400 });
177
+ });
178
+
179
+ const response = await fastify.inject({ method: 'GET', url: '/fail' });
180
+
181
+ expect(response.statusCode).toBe(500);
182
+ expect(response.json()).toEqual(internalErrorBody);
183
+ });
184
+
185
+ it('hides a thrown plain object with a status behind a generic 500', async () => {
186
+ const { fastify } = buildConsumer();
187
+ fastify.get('/fail', async () => {
188
+ throw { statusCode: 404 };
189
+ });
190
+
191
+ const response = await fastify.inject({ method: 'GET', url: '/fail' });
192
+
193
+ expect(response.statusCode).toBe(500);
194
+ expect(response.json()).toEqual(internalErrorBody);
195
+ });
196
+
197
+ it.each([null, undefined])('answers a thrown %s with a generic 500', async (thrown) => {
198
+ const { fastify } = buildConsumer();
199
+ fastify.get('/fail', async () => {
200
+ throw thrown;
201
+ });
202
+
203
+ const response = await fastify.inject({ method: 'GET', url: '/fail' });
204
+
205
+ expect(response.statusCode).toBe(500);
206
+ expect(response.json()).toEqual(internalErrorBody);
207
+ });
208
+
209
+ it('answers Zod validation failures with VALIDATION_ERROR violations', async () => {
210
+ const { fastify } = buildConsumer();
211
+ fastify
212
+ .withTypeProvider<ZodTypeProvider>()
213
+ .get('/things', { schema: { querystring: z.object({ limit: z.coerce.number().int() }) } }, async () => ({}));
214
+
215
+ const response = await fastify.inject({ method: 'GET', url: '/things?limit=abc' });
216
+
217
+ expect(response.statusCode).toBe(400);
218
+ expect(response.json()).toMatchObject({
219
+ error: {
220
+ code: 'VALIDATION_ERROR',
221
+ message: 'The request parameters are invalid',
222
+ details: { violations: [{ field: '/limit' }] },
223
+ },
224
+ });
225
+ });
226
+
227
+ it('answers unknown routes with NOT_FOUND', async () => {
228
+ const { fastify } = buildConsumer();
229
+
230
+ const response = await fastify.inject({ method: 'GET', url: '/nowhere' });
231
+
232
+ expect(response.statusCode).toBe(404);
233
+ expect(response.json()).toEqual(notFoundBody);
234
+ });
235
+
236
+ it.each([
237
+ ['without a prefix', undefined, '/entities'],
238
+ ['under a prefix', '/api', '/api/entities'],
239
+ ])('answers arocapi routes registered %s in the spec shape', async (_label, prefix, url) => {
240
+ const { fastify } = buildConsumer();
241
+ await fastify.register(arocapi, { ...arocapiOptions, prefix });
242
+
243
+ const invalid = await fastify.inject({ method: 'GET', url: `${url}?limit=abc` });
244
+ const unknown = await fastify.inject({ method: 'GET', url: `${url}/nowhere/else` });
245
+
246
+ expect(invalid.statusCode).toBe(400);
247
+ expect(invalid.json().error.code).toBe('VALIDATION_ERROR');
248
+ expect(unknown.statusCode).toBe(404);
249
+ expect(unknown.json().error.code).toBe('NOT_FOUND');
250
+ });
251
+
252
+ it('leaves 404s to a prefixed consumer scope that mounts arocapi without its own prefix', async () => {
253
+ const { fastify } = buildConsumer();
254
+ await fastify.register(
255
+ async (api) => {
256
+ api.setNotFoundHandler((_request, reply) => reply.code(404).send({ scope: 'api' }));
257
+ await api.register(arocapi, arocapiOptions);
258
+ },
259
+ { prefix: '/api' },
260
+ );
261
+
262
+ const response = await fastify.inject({ method: 'GET', url: '/api/nowhere' });
263
+
264
+ expect(response.statusCode).toBe(404);
265
+ expect(response.json()).toEqual({ scope: 'api' });
266
+ });
267
+ it("leaves the consumer's root 404s alone when arocapi is registered with prefix '/'", async () => {
268
+ const fastify = Fastify({ logger: false });
269
+ fastify.setNotFoundHandler((_request, reply) => reply.code(404).send({ scope: 'root' }));
270
+ await fastify.register(arocapi, { ...arocapiOptions, prefix: '/' });
271
+
272
+ const response = await fastify.inject({ method: 'GET', url: '/nowhere' });
273
+
274
+ expect(response.json()).toEqual({ scope: 'root' });
275
+ });
276
+ });
277
+
278
+ describe('Error handling for arocapi on its own', () => {
279
+ it('answers unknown paths under its prefix with NOT_FOUND', async () => {
280
+ const fastify = Fastify({ logger: false });
281
+ await fastify.register(arocapi, { ...arocapiOptions, prefix: '/api' });
282
+
283
+ const response = await fastify.inject({ method: 'GET', url: '/api/nowhere' });
284
+
285
+ expect(response.statusCode).toBe(404);
286
+ expect(response.json()).toEqual(notFoundBody);
287
+ });
288
+ });
package/src/index.dev.ts CHANGED
@@ -5,8 +5,9 @@ import { PrismaMariaDb } from '@prisma/adapter-mariadb';
5
5
  import Fastify from 'fastify';
6
6
 
7
7
  import arocapi, {
8
- AllPublicAccessTransformer,
9
- AllPublicFileAccessTransformer,
8
+ AllPublicAccess,
9
+ AllVisibleEntityFilter,
10
+ AllVisibleSearchFilter,
10
11
  type EntityTransformer,
11
12
  type FileHandler,
12
13
  type RoCrateHandler,
@@ -184,9 +185,10 @@ fastify.register(arocapi, {
184
185
  opensearch,
185
186
  fileHandler,
186
187
  roCrateHandler,
187
- accessTransformer: AllPublicAccessTransformer,
188
+ access: AllPublicAccess,
188
189
  entityTransformers: [oniTransformer],
189
- fileAccessTransformer: AllPublicFileAccessTransformer,
190
+ entityVisibilityFilter: AllVisibleEntityFilter,
191
+ searchVisibilityFilter: AllVisibleSearchFilter,
190
192
  });
191
193
 
192
194
  const start = async () => {
@@ -32,7 +32,7 @@ exports[`Search Route > POST /search > should handle id explicitly set to undefi
32
32
  {
33
33
  "error": {
34
34
  "code": "INTERNAL_ERROR",
35
- "message": "Search failed",
35
+ "message": "Internal server error",
36
36
  },
37
37
  }
38
38
  `;
@@ -41,7 +41,7 @@ exports[`Search Route > POST /search > should handle opensearch errors 1`] = `
41
41
  {
42
42
  "error": {
43
43
  "code": "INTERNAL_ERROR",
44
- "message": "Search failed",
44
+ "message": "Internal server error",
45
45
  },
46
46
  }
47
47
  `;
@@ -1,8 +1,7 @@
1
1
  import { afterEach, describe, expect, it, vi } from 'vitest';
2
2
 
3
- import app, { AllPublicFileAccessTransformer, type Options } from '../app.js';
3
+ import app, { AllPublicAccess, AllVisibleEntityFilter, AllVisibleSearchFilter, type Options } from '../app.js';
4
4
  import { fastify, fastifyAfter, fastifyBefore, opensearch, prisma } from '../test/helpers/fastify.js';
5
- import { AllPublicAccessTransformer } from '../transformers/default.js';
6
5
  import { OpensearchQueryBuilder, type SearchCapability } from '../utils/queryBuilder.js';
7
6
 
8
7
  const registerApp = async (options: Partial<Options> = {}) => {
@@ -10,10 +9,11 @@ const registerApp = async (options: Partial<Options> = {}) => {
10
9
  await fastify.register(app, {
11
10
  prisma,
12
11
  opensearch,
13
- accessTransformer: AllPublicAccessTransformer,
14
- fileAccessTransformer: AllPublicFileAccessTransformer,
12
+ access: AllPublicAccess,
15
13
  fileHandler: { get: vi.fn(), head: vi.fn() },
16
14
  roCrateHandler: { get: vi.fn(), head: vi.fn() },
15
+ entityVisibilityFilter: AllVisibleEntityFilter,
16
+ searchVisibilityFilter: AllVisibleSearchFilter,
17
17
  ...options,
18
18
  });
19
19
  };
@@ -86,17 +86,17 @@ describe('Capabilities Route', () => {
86
86
  expect(body.search).toEqual(labelled);
87
87
  });
88
88
 
89
- it('should not run the access transformer', async () => {
90
- const accessTransformer = vi.fn(() => {
89
+ it('should not run the access function', async () => {
90
+ const access = vi.fn(() => {
91
91
  throw new Error('Unauthorised');
92
92
  });
93
93
 
94
- await registerApp({ accessTransformer });
94
+ await registerApp({ access });
95
95
 
96
96
  const { statusCode } = await getCapabilities();
97
97
 
98
98
  expect(statusCode).toBe(200);
99
- expect(accessTransformer).not.toHaveBeenCalled();
99
+ expect(access).not.toHaveBeenCalled();
100
100
  });
101
101
  });
102
102
  });
@@ -2,8 +2,11 @@ import { createReadStream } from 'node:fs';
2
2
  import { Readable } from 'node:stream';
3
3
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4
4
  import { fastify, fastifyAfter, fastifyBefore, prisma } from '../test/helpers/fastify.js';
5
+ import type { AccessFunction } from '../types/access.js';
5
6
  import type { FileResult, RoCrateHandler } from '../types/fileHandlers.js';
7
+ import { AllPublicAccess } from '../utils/access.js';
6
8
  import type { StandardErrorResponse } from '../utils/errors.js';
9
+ import { AllVisibleEntityFilter } from '../utils/visibility.js';
7
10
  import metadataRoute from './metadata.js';
8
11
 
9
12
  vi.mock('node:fs', () => ({
@@ -15,11 +18,20 @@ describe('Crate Route', () => {
15
18
  get: vi.fn(),
16
19
  head: vi.fn(),
17
20
  };
21
+ const mockAccess = vi.fn<AccessFunction>();
18
22
 
19
23
  beforeEach(async () => {
20
24
  await fastifyBefore();
21
- await fastify.register(metadataRoute, { prisma, roCrateHandler: mockRoCrateHandler });
25
+ await fastify.register(metadataRoute, {
26
+ access: mockAccess,
27
+ entityVisibilityFilter: AllVisibleEntityFilter,
28
+ refusal: { promptLoginForHidden: false },
29
+ prisma,
30
+ roCrateHandler: mockRoCrateHandler,
31
+ });
22
32
  vi.clearAllMocks();
33
+ mockAccess.mockImplementation(AllPublicAccess);
34
+ prisma.entity.findMany.mockResolvedValue([]);
23
35
  });
24
36
 
25
37
  afterEach(async () => {
@@ -60,7 +72,7 @@ describe('Crate Route', () => {
60
72
 
61
73
  describe('GET /entity/:id/metadata', () => {
62
74
  it('should stream RO-Crate metadata for File entity', async () => {
63
- prisma.entity.findUnique.mockResolvedValue(mockFileEntity);
75
+ prisma.entity.findFirst.mockResolvedValue(mockFileEntity);
64
76
 
65
77
  const mockStream = Readable.from(['{"@context": "https://w3id.org/ro/crate/1.1/context"}']);
66
78
  const mockResult: FileResult = {
@@ -96,7 +108,7 @@ describe('Crate Route', () => {
96
108
  });
97
109
 
98
110
  it('should stream RO-Crate metadata for Collection entity', async () => {
99
- prisma.entity.findUnique.mockResolvedValue(mockCollectionEntity);
111
+ prisma.entity.findFirst.mockResolvedValue(mockCollectionEntity);
100
112
 
101
113
  const mockStream = Readable.from(['{"@context": "https://w3id.org/ro/crate/1.1/context"}']);
102
114
  const mockResult: FileResult = {
@@ -120,7 +132,7 @@ describe('Crate Route', () => {
120
132
  });
121
133
 
122
134
  it('should stream RO-Crate metadata for Object entity', async () => {
123
- prisma.entity.findUnique.mockResolvedValue(mockObjectEntity);
135
+ prisma.entity.findFirst.mockResolvedValue(mockObjectEntity);
124
136
 
125
137
  const mockStream = Readable.from(['{"@context": "https://w3id.org/ro/crate/1.1/context"}']);
126
138
  const mockResult: FileResult = {
@@ -144,7 +156,7 @@ describe('Crate Route', () => {
144
156
  });
145
157
 
146
158
  it('should handle redirect response', async () => {
147
- prisma.entity.findUnique.mockResolvedValue(mockFileEntity);
159
+ prisma.entity.findFirst.mockResolvedValue(mockFileEntity);
148
160
 
149
161
  const mockResult: FileResult = {
150
162
  type: 'redirect',
@@ -162,7 +174,7 @@ describe('Crate Route', () => {
162
174
  });
163
175
 
164
176
  it('should handle file path response without nginx X-Accel-Redirect', async () => {
165
- prisma.entity.findUnique.mockResolvedValue(mockCollectionEntity);
177
+ prisma.entity.findFirst.mockResolvedValue(mockCollectionEntity);
166
178
 
167
179
  const mockStream = Readable.from(['rocrate content']);
168
180
  vi.mocked(createReadStream).mockReturnValue(mockStream as never);
@@ -190,7 +202,7 @@ describe('Crate Route', () => {
190
202
  });
191
203
 
192
204
  it('should handle file path response with nginx X-Accel-Redirect', async () => {
193
- prisma.entity.findUnique.mockResolvedValue(mockFileEntity);
205
+ prisma.entity.findFirst.mockResolvedValue(mockFileEntity);
194
206
 
195
207
  const mockResult: FileResult = {
196
208
  type: 'file',
@@ -215,7 +227,7 @@ describe('Crate Route', () => {
215
227
  });
216
228
 
217
229
  it('should return 404 when entity not found', async () => {
218
- prisma.entity.findUnique.mockResolvedValue(null);
230
+ prisma.entity.findFirst.mockResolvedValue(null);
219
231
 
220
232
  const response = await fastify.inject({
221
233
  method: 'GET',
@@ -229,8 +241,44 @@ describe('Crate Route', () => {
229
241
  expect(mockRoCrateHandler.get).not.toHaveBeenCalled();
230
242
  });
231
243
 
244
+ it('should decide access on the entity without looking up its parents', async () => {
245
+ prisma.entity.findFirst.mockResolvedValue(mockObjectEntity);
246
+ vi.mocked(mockRoCrateHandler.get).mockResolvedValue({ type: 'redirect', url: 'https://example.com/ro-crate' });
247
+
248
+ await fastify.inject({
249
+ method: 'GET',
250
+ url: `/entity/${encodeURIComponent('http://example.com/object')}/metadata`,
251
+ });
252
+
253
+ expect(mockAccess).toHaveBeenCalledWith(
254
+ expect.objectContaining({
255
+ id: 'http://example.com/object',
256
+ memberOf: 'http://example.com/collection',
257
+ rootCollection: 'http://example.com/collection',
258
+ }),
259
+ expect.objectContaining({ request: expect.any(Object), fastify: expect.any(Object) }),
260
+ );
261
+ expect(prisma.entity.findMany).not.toHaveBeenCalled();
262
+ });
263
+
264
+ it('should return 403 when the metadata is not accessible', async () => {
265
+ prisma.entity.findFirst.mockResolvedValue(mockFileEntity);
266
+ mockAccess.mockReturnValue({ metadata: false, content: true });
267
+
268
+ const response = await fastify.inject({
269
+ method: 'GET',
270
+ url: `/entity/${encodeURIComponent('http://example.com/entity/file.wav')}/metadata`,
271
+ });
272
+ const body = JSON.parse(response.body) as { error: { code: string; message: string } };
273
+
274
+ expect(response.statusCode).toBe(403);
275
+ expect(body.error.code).toBe('FORBIDDEN');
276
+ expect(body.error.message).toBe('You do not have permission to access this resource');
277
+ expect(mockRoCrateHandler.get).not.toHaveBeenCalled();
278
+ });
279
+
232
280
  it('should return 404 when handler returns false', async () => {
233
- prisma.entity.findUnique.mockResolvedValue(mockFileEntity);
281
+ prisma.entity.findFirst.mockResolvedValue(mockFileEntity);
234
282
  vi.mocked(mockRoCrateHandler.get).mockResolvedValue(false);
235
283
 
236
284
  const response = await fastify.inject({
@@ -245,7 +293,7 @@ describe('Crate Route', () => {
245
293
  });
246
294
 
247
295
  it('should return 500 when database error occurs', async () => {
248
- prisma.entity.findUnique.mockRejectedValue(new Error('Database connection failed'));
296
+ prisma.entity.findFirst.mockRejectedValue(new Error('Database connection failed'));
249
297
 
250
298
  const response = await fastify.inject({
251
299
  method: 'GET',
@@ -258,7 +306,7 @@ describe('Crate Route', () => {
258
306
  });
259
307
 
260
308
  it('should return 500 when roCrateHandler throws error', async () => {
261
- prisma.entity.findUnique.mockResolvedValue(mockFileEntity);
309
+ prisma.entity.findFirst.mockResolvedValue(mockFileEntity);
262
310
  vi.mocked(mockRoCrateHandler.get).mockRejectedValue(new Error('RO-Crate error'));
263
311
 
264
312
  const response = await fastify.inject({
@@ -279,13 +327,13 @@ describe('Crate Route', () => {
279
327
  const body = JSON.parse(response.body) as StandardErrorResponse;
280
328
 
281
329
  expect(response.statusCode).toBe(400);
282
- expect(body.error).toBe('Bad Request');
330
+ expect(body.error.code).toBe('VALIDATION_ERROR');
283
331
  });
284
332
  });
285
333
 
286
334
  describe('HEAD /entity/:id/metadata', () => {
287
335
  it('should return RO-Crate metadata headers for File entity', async () => {
288
- prisma.entity.findUnique.mockResolvedValue(mockFileEntity);
336
+ prisma.entity.findFirst.mockResolvedValue(mockFileEntity);
289
337
 
290
338
  const mockMetadata = {
291
339
  contentType: 'application/ld+json',
@@ -316,7 +364,7 @@ describe('Crate Route', () => {
316
364
  });
317
365
 
318
366
  it('should return RO-Crate metadata headers for Collection entity', async () => {
319
- prisma.entity.findUnique.mockResolvedValue(mockCollectionEntity);
367
+ prisma.entity.findFirst.mockResolvedValue(mockCollectionEntity);
320
368
 
321
369
  const mockMetadata = {
322
370
  contentType: 'text/plain',
@@ -336,7 +384,7 @@ describe('Crate Route', () => {
336
384
  });
337
385
 
338
386
  it('should return RO-Crate metadata headers for Object entity', async () => {
339
- prisma.entity.findUnique.mockResolvedValue(mockObjectEntity);
387
+ prisma.entity.findFirst.mockResolvedValue(mockObjectEntity);
340
388
 
341
389
  const mockMetadata = {
342
390
  contentType: 'application/json',
@@ -356,7 +404,7 @@ describe('Crate Route', () => {
356
404
  });
357
405
 
358
406
  it('should return 404 when entity not found', async () => {
359
- prisma.entity.findUnique.mockResolvedValue(null);
407
+ prisma.entity.findFirst.mockResolvedValue(null);
360
408
 
361
409
  const response = await fastify.inject({
362
410
  method: 'HEAD',
@@ -369,8 +417,21 @@ describe('Crate Route', () => {
369
417
  expect(mockRoCrateHandler.head).not.toHaveBeenCalled();
370
418
  });
371
419
 
420
+ it('should return 403 when the metadata is not accessible', async () => {
421
+ prisma.entity.findFirst.mockResolvedValue(mockFileEntity);
422
+ mockAccess.mockReturnValue({ metadata: false, content: true });
423
+
424
+ const response = await fastify.inject({
425
+ method: 'HEAD',
426
+ url: `/entity/${encodeURIComponent('http://example.com/entity/file.wav')}/metadata`,
427
+ });
428
+
429
+ expect(response.statusCode).toBe(403);
430
+ expect(mockRoCrateHandler.head).not.toHaveBeenCalled();
431
+ });
432
+
372
433
  it('should return 404 when head handler returns false', async () => {
373
- prisma.entity.findUnique.mockResolvedValue(mockFileEntity);
434
+ prisma.entity.findFirst.mockResolvedValue(mockFileEntity);
374
435
  vi.mocked(mockRoCrateHandler.head).mockResolvedValue(false);
375
436
 
376
437
  const response = await fastify.inject({
@@ -385,7 +446,7 @@ describe('Crate Route', () => {
385
446
  });
386
447
 
387
448
  it('should return 500 when head handler throws error', async () => {
388
- prisma.entity.findUnique.mockResolvedValue(mockFileEntity);
449
+ prisma.entity.findFirst.mockResolvedValue(mockFileEntity);
389
450
  vi.mocked(mockRoCrateHandler.head).mockRejectedValue(new Error('Metadata error'));
390
451
 
391
452
  const response = await fastify.inject({
@@ -401,7 +462,7 @@ describe('Crate Route', () => {
401
462
 
402
463
  describe('GET /entity/:id/metadata - exhaustiveness check', () => {
403
464
  it('should handle unexpected RO-Crate result type', async () => {
404
- prisma.entity.findUnique.mockResolvedValue(mockFileEntity);
465
+ prisma.entity.findFirst.mockResolvedValue(mockFileEntity);
405
466
 
406
467
  // Mock an invalid result type to test exhaustiveness check
407
468
  const invalidResult = {