Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(api-keys): add endpoint to check current API key (#718)

Corentin Thomasset8d70a7b3c36b
diff --git a/.changeset/true-olives-beam.md b/.changeset/true-olives-beam.md
new file mode 100644
index 00000000..e7f3c274
--- /dev/null
+++ b/.changeset/true-olives-beam.md
@@ -0,0 +1,5 @@
+---
+"@papra/docker": patch
+---
+
+Added api endpoint to check current API key (GET /api/api-keys/current)
diff --git a/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx b/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx
index 1b387cea..01e5a17b 100644
--- a/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx
+++ b/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx
@@ -66,6 +66,19 @@ When creating an API key, you can select from the following permissions:
## Endpoints
+### Check current API key
+
+**GET** `/api/api-keys/current`
+
+Get information about the currently used API key.
+
+- Required API key permissions: none
+- Response (JSON)
+ - `apiKey`: The current API key information.
+ - `id`: The API key ID.
+ - `name`: The API key name.
+ - `permissions`: The list of permissions associated with the API key.
+
### List organizations
**GET** `/api/organizations`
diff --git a/apps/papra-server/src/modules/api-keys/api-keys.errors.ts b/apps/papra-server/src/modules/api-keys/api-keys.errors.ts
new file mode 100644
index 00000000..9a167d0b
--- /dev/null
+++ b/apps/papra-server/src/modules/api-keys/api-keys.errors.ts
@@ -0,0 +1,8 @@
+import { createErrorFactory } from '../shared/errors/errors';
+
+// Error when the authentication is not using an API key but the route is api-key only
+export const createNotApiKeyAuthError = createErrorFactory({
+ code: 'api_keys.authentication_not_api_key',
+ message: 'Authentication must be done using an API key to access this resource',
+ statusCode: 401,
+});
diff --git a/apps/papra-server/src/modules/api-keys/api-keys.routes.ts b/apps/papra-server/src/modules/api-keys/api-keys.routes.ts
index bfd50131..61527a29 100644
--- a/apps/papra-server/src/modules/api-keys/api-keys.routes.ts
+++ b/apps/papra-server/src/modules/api-keys/api-keys.routes.ts
@@ -1,17 +1,21 @@
import type { RouteDefinitionContext } from '../app/server.types';
import type { ApiKeyPermissions } from './api-keys.types';
import { z } from 'zod';
+import { createUnauthorizedError } from '../app/auth/auth.errors';
import { requireAuthentication } from '../app/auth/auth.middleware';
import { getUser } from '../app/auth/auth.models';
import { createError } from '../shared/errors/errors';
+import { isNil } from '../shared/utils';
import { validateJsonBody, validateParams } from '../shared/validation/validation';
import { API_KEY_PERMISSIONS_VALUES } from './api-keys.constants';
+import { createNotApiKeyAuthError } from './api-keys.errors';
import { createApiKeysRepository } from './api-keys.repository';
import { apiKeyIdSchema } from './api-keys.schemas';
import { createApiKey } from './api-keys.usecases';
export function registerApiKeysRoutes(context: RouteDefinitionContext) {
setupCreateApiKeyRoute(context);
+ setupGetCurrentApiKeyRoute(context); // Should be before the get api keys route otherwise it conflicts ("current" as apiKeyId)
setupGetApiKeysRoute(context);
setupDeleteApiKeyRoute(context);
}
@@ -82,6 +86,38 @@ function setupGetApiKeysRoute({ app, db }: RouteDefinitionContext) {
);
}
+// Mainly use for authentication verification in client SDKs
+function setupGetCurrentApiKeyRoute({ app }: RouteDefinitionContext) {
+ app.get(
+ '/api/api-keys/current',
+ async (context) => {
+ const authType = context.get('authType');
+ const apiKey = context.get('apiKey');
+
+ if (isNil(authType)) {
+ throw createUnauthorizedError();
+ }
+
+ if (authType !== 'api-key') {
+ throw createNotApiKeyAuthError();
+ }
+
+ if (isNil(apiKey)) {
+ // Should not happen as authType is 'api-key', but for type safety
+ throw createUnauthorizedError();
+ }
+
+ return context.json({
+ apiKey: {
+ id: apiKey.id,
+ name: apiKey.name,
+ permissions: apiKey.permissions,
+ },
+ });
+ },
+ );
+}
+
function setupDeleteApiKeyRoute({ app, db }: RouteDefinitionContext) {
app.delete(
'/api/api-keys/:apiKeyId',
diff --git a/apps/papra-server/src/modules/api-keys/e2e/current-api-key.e2e.test.ts b/apps/papra-server/src/modules/api-keys/e2e/current-api-key.e2e.test.ts
new file mode 100644
index 00000000..b02bb56f
--- /dev/null
+++ b/apps/papra-server/src/modules/api-keys/e2e/current-api-key.e2e.test.ts
@@ -0,0 +1,169 @@
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../../app/database/database.test-utils';
+import { createServer } from '../../app/server';
+import { createTestServerDependencies } from '../../app/server.test-utils';
+import { overrideConfig } from '../../config/config.test-utils';
+import { ORGANIZATION_ROLES } from '../../organizations/organizations.constants';
+import { API_KEY_ID_PREFIX, API_KEY_TOKEN_LENGTH } from '../api-keys.constants';
+
+describe('api-key e2e', () => {
+ describe('get /api/api-keys/current', () => {
+ test('when using an api key, one can request the /api/api-keys/current route to check that the api key is valid', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_111111111111111111111111', email: '[email protected]' }],
+ organizations: [{ id: 'org_222222222222222222222222', name: 'Org 1' }],
+ organizationMembers: [{ organizationId: 'org_222222222222222222222222', userId: 'usr_111111111111111111111111', role: ORGANIZATION_ROLES.OWNER }],
+ });
+
+ const { app } = createServer(createTestServerDependencies({
+ db,
+ config: overrideConfig({
+ env: 'test',
+ documentsStorage: {
+ driver: 'in-memory',
+ },
+ }),
+ }));
+
+ const createApiKeyResponse = await app.request(
+ '/api/api-keys',
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'Test API Key',
+ permissions: ['documents:create'],
+ }),
+ },
+ { loggedInUserId: 'usr_111111111111111111111111' },
+ );
+
+ expect(createApiKeyResponse.status).toBe(200);
+ const { token, apiKey } = await createApiKeyResponse.json() as { token: string; apiKey: { id: string } };
+
+ const getCurrentApiKeyResponse = await app.request(
+ '/api/api-keys/current',
+ {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ },
+ );
+
+ const response = await getCurrentApiKeyResponse.json();
+
+ expect(response).to.deep.equal({
+ apiKey: {
+ id: apiKey.id,
+ name: 'Test API Key',
+ permissions: ['documents:create'],
+ },
+ });
+
+ expect(getCurrentApiKeyResponse.status).toBe(200);
+ });
+
+ test('when not using an api key, requesting the /api/api-keys/current route returns an error', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_111111111111111111111111', email: '[email protected]' }],
+ organizations: [{ id: 'org_222222222222222222222222', name: 'Org 1' }],
+ organizationMembers: [{ organizationId: 'org_222222222222222222222222', userId: 'usr_111111111111111111111111', role: ORGANIZATION_ROLES.OWNER }],
+ });
+
+ const { app } = createServer(createTestServerDependencies({
+ db,
+ config: overrideConfig({
+ env: 'test',
+ documentsStorage: {
+ driver: 'in-memory',
+ },
+ }),
+ }));
+
+ const getCurrentApiKeyResponse = await app.request(
+ '/api/api-keys/current',
+ {
+ method: 'GET',
+ },
+ { loggedInUserId: 'usr_111111111111111111111111' },
+ );
+
+ expect(getCurrentApiKeyResponse.status).toBe(401);
+ const response = await getCurrentApiKeyResponse.json();
+
+ expect(response).to.deep.equal({
+ error: {
+ code: 'api_keys.authentication_not_api_key',
+ message: 'Authentication must be done using an API key to access this resource',
+ },
+ });
+ });
+
+ test('when not authenticated at all, requesting the /api/api-keys/current route returns an error', async () => {
+ const { db } = await createInMemoryDatabase();
+
+ const { app } = createServer(createTestServerDependencies({
+ db,
+ config: overrideConfig({
+ env: 'test',
+ documentsStorage: {
+ driver: 'in-memory',
+ },
+ }),
+ }));
+
+ const getCurrentApiKeyResponse = await app.request(
+ '/api/api-keys/current',
+ {
+ method: 'GET',
+ },
+ );
+
+ expect(getCurrentApiKeyResponse.status).toBe(401);
+ const response = await getCurrentApiKeyResponse.json();
+
+ expect(response).to.deep.equal({
+ error: {
+ code: 'auth.unauthorized',
+ message: 'Unauthorized',
+ },
+ });
+ });
+
+ test('if the api key used is invalid, requesting the /api/api-keys/current route returns an error', async () => {
+ const { db } = await createInMemoryDatabase();
+ const invalidButLegitApiKeyToken = `${API_KEY_ID_PREFIX}_${'x'.repeat(API_KEY_TOKEN_LENGTH)}`;
+
+ const { app } = createServer(createTestServerDependencies({
+ db,
+ config: overrideConfig({
+ env: 'test',
+ documentsStorage: {
+ driver: 'in-memory',
+ },
+ }),
+ }));
+
+ const getCurrentApiKeyResponse = await app.request(
+ '/api/api-keys/current',
+ {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${invalidButLegitApiKeyToken}`,
+ },
+ },
+ );
+
+ expect(getCurrentApiKeyResponse.status).toBe(401);
+ const response = await getCurrentApiKeyResponse.json();
+
+ expect(response).to.deep.equal({
+ error: {
+ code: 'auth.unauthorized',
+ message: 'Unauthorized',
+ },
+ });
+ });
+ });
+});