From 60f396bb8dff043468f3a832576d150b74a00c10 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 10:08:33 -0300 Subject: [PATCH 01/14] fix(openapi): align the contract with what the controllers return Adjust the PHP annotations whose cause is in LibreSign so generated clients describe the real API: - rename the ID document schema `File` to `IdDocFile`: the name collides with the global TypeScript `File`, and typescript-axios renamed the model without updating its references, leaving `Array`; - declare literal media types for the CRL (application/pkix-crl) and the admin background (image/png); - document only `MessageResponse` for the 422 of request-signature POST and PATCH, which always return `{message}`, and drop two `anyOf`; - document `MessageResponse` for the 422 of removeSigner and remove the 422 that deleteFile and deleteSignatureRequest never return; - make `DetailedFile.nodeId` nullable like `libresign_file.node_id`. The notify 422 `anyOf` stays: canRequestSign() throws an action/errors body and other validations a message body. Specs and TypeScript types are regenerated, not hand-edited. Contract tests cover the new shapes. Signed-off-by: Luis Amorim --- lib/Controller/AccountController.php | 2 +- lib/Controller/AdminController.php | 2 +- lib/Controller/CrlController.php | 2 +- lib/Controller/FileController.php | 5 +- lib/Controller/IdDocsController.php | 2 +- lib/Controller/RequestSignatureController.php | 14 +- lib/ResponseDefinitions.php | 8 +- openapi-administration.json | 12 +- openapi-full.json | 345 +++++++----------- openapi.json | 333 +++++++---------- .../views/Documents/IdDocsValidation.spec.ts | 2 +- src/types/openapi/openapi-administration.ts | 3 +- src/types/openapi/openapi-full.ts | 113 +++--- src/types/openapi/openapi.ts | 110 +++--- src/views/Documents/IdDocsValidation.vue | 2 +- .../openapi/OpenApiBinaryMediaTypesTest.php | 46 +++ .../openapi/OpenApiErrorBodyContractTest.php | 91 +++++ tests/php/openapi/OpenApiIdDocSchemaTest.php | 42 +++ tests/php/openapi/phpunit.xml | 3 + 19 files changed, 568 insertions(+), 569 deletions(-) create mode 100644 tests/php/openapi/OpenApiBinaryMediaTypesTest.php create mode 100644 tests/php/openapi/OpenApiErrorBodyContractTest.php create mode 100644 tests/php/openapi/OpenApiIdDocSchemaTest.php diff --git a/lib/Controller/AccountController.php b/lib/Controller/AccountController.php index 57d6d0ebd4..17f330f145 100644 --- a/lib/Controller/AccountController.php +++ b/lib/Controller/AccountController.php @@ -44,7 +44,7 @@ * @psalm-import-type LibresignConfigValueResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignUserConfigValue from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignCreateToSignResponse from \OCA\Libresign\ResponseDefinitions - * @psalm-import-type LibresignFile from \OCA\Libresign\ResponseDefinitions + * @psalm-import-type LibresignIdDocFile from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignMessageResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignPagination from \OCA\Libresign\ResponseDefinitions */ diff --git a/lib/Controller/AdminController.php b/lib/Controller/AdminController.php index 8f6ddf7a12..242dd8e6da 100644 --- a/lib/Controller/AdminController.php +++ b/lib/Controller/AdminController.php @@ -336,7 +336,7 @@ public function signatureBackgroundSave(): DataResponse { /** * Get custom background image * - * @return FileDisplayResponse + * @return FileDisplayResponse * * 200: Image returned */ diff --git a/lib/Controller/CrlController.php b/lib/Controller/CrlController.php index 5be9f3a801..6ac70dbeb9 100644 --- a/lib/Controller/CrlController.php +++ b/lib/Controller/CrlController.php @@ -42,7 +42,7 @@ public function __construct( * @param string $instanceId Instance identifier * @param int $generation Generation identifier * @param string $engineType Engine type identifier - * @return DataDownloadResponse|DataResponse + * @return DataDownloadResponse|DataResponse * * 200: CRL retrieved successfully in DER format * 500: Failed to generate CRL diff --git a/lib/Controller/FileController.php b/lib/Controller/FileController.php index 503d4ca5aa..3dbc716e02 100644 --- a/lib/Controller/FileController.php +++ b/lib/Controller/FileController.php @@ -50,7 +50,7 @@ use Psr\Log\LoggerInterface; /** - * @psalm-import-type LibresignFile from \OCA\Libresign\ResponseDefinitions + * @psalm-import-type LibresignIdDocFile from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignDetailedFile from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignDetailedFileResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignActionErrorResponse from \OCA\Libresign\ResponseDefinitions @@ -887,11 +887,10 @@ private function extractFileName(array $fileData): string { * * @param integer $fileId LibreSign file ID * @param boolean $deleteFile Whether to delete the physical file from Nextcloud (default: true) - * @return DataResponse|DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: OK * 401: Failed - * 422: Failed */ #[NoAdminRequired] #[NoCSRFRequired] diff --git a/lib/Controller/IdDocsController.php b/lib/Controller/IdDocsController.php index 4cea12a79d..4ddc24d686 100644 --- a/lib/Controller/IdDocsController.php +++ b/lib/Controller/IdDocsController.php @@ -29,7 +29,7 @@ use Psr\Log\LoggerInterface; /** - * @psalm-import-type LibresignFile from \OCA\Libresign\ResponseDefinitions + * @psalm-import-type LibresignIdDocFile from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignIdDocs from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignIdDocsApprovalListResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignIdDocsListResponse from \OCA\Libresign\ResponseDefinitions diff --git a/lib/Controller/RequestSignatureController.php b/lib/Controller/RequestSignatureController.php index 4d27495eca..320bb2a04b 100644 --- a/lib/Controller/RequestSignatureController.php +++ b/lib/Controller/RequestSignatureController.php @@ -31,7 +31,6 @@ * @psalm-import-type LibresignNewSigner from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignDetailedFile from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignDetailedFileResponse from \OCA\Libresign\ResponseDefinitions - * @psalm-import-type LibresignActionErrorResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignMessageResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignFolderSettings from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignSettings from \OCA\Libresign\ResponseDefinitions @@ -67,10 +66,10 @@ public function __construct( * @param list $files Multiple files to create an envelope (optional, use either file or files). Each file supports nodeId, url, base64 or path. * @param integer|null $status Numeric code of status * 0 - no signers * 1 - signed * 2 - pending * @param LibresignRequestPolicy|null $policy Structured policy payload with request-level overrides and active context. - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: OK - * 422: Unauthorized + * 422: Request cannot be processed */ #[NoAdminRequired] #[NoCSRFRequired] @@ -138,10 +137,10 @@ public function requestSignature( * @param string|null $name The name of file to sign * @param LibresignFolderSettings $settings Settings to define how and where the file should be stored * @param list $files Multiple files to create an envelope (optional, use either file or files). Each file supports nodeId, url, base64 or path. - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: OK - * 422: Unauthorized + * 422: Request cannot be processed */ #[NoAdminRequired] #[NoCSRFRequired] @@ -212,7 +211,7 @@ public function updateSignatureRequest( * * @param integer $fileId LibreSign file ID * @param integer $signRequestId The sign request id - * @return DataResponse|DataResponse|DataResponse + * @return DataResponse|DataResponse|DataResponse * * 200: OK * 401: Failed @@ -258,11 +257,10 @@ public function removeSigner(int $fileId, int $signRequestId): DataResponse { * You can only request exclusion as any sign * * @param integer $fileId LibreSign file ID - * @return DataResponse|DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: OK * 401: Failed - * 422: Failed */ #[NoAdminRequired] #[NoCSRFRequired] diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index 81fe277cdf..f7cf4b5f00 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -778,7 +778,7 @@ * files: list, * filesCount: int<0, max>, * id: int, - * nodeId: int, + * nodeId: ?int, * uuid: string, * name: non-falsy-string, * status: int, @@ -805,7 +805,7 @@ * * Account, elements, and ID document contracts * - * @psalm-type LibresignFile = array{ + * @psalm-type LibresignIdDocFile = array{ * account: array{ * userId: string, * displayName: string, @@ -882,11 +882,11 @@ * } * @psalm-type LibresignIdDocsListResponse = array{ * pagination: LibresignPagination, - * data: list, + * data: list, * } * @psalm-type LibresignIdDocsApprovalListResponse = array{ * pagination: LibresignPagination, - * data: list, + * data: list, * } * @psalm-type LibresignCreateToSignPdfReference = array{ * url: string, diff --git a/openapi-administration.json b/openapi-administration.json index d4ce2ce7d4..f699fd9c72 100644 --- a/openapi-administration.json +++ b/openapi-administration.json @@ -2013,8 +2013,18 @@ "responses": { "200": { "description": "Image returned", + "headers": { + "Content-Disposition": { + "schema": { + "type": "string", + "enum": [ + "attachment; filename=\"background.png\"" + ] + } + } + }, "content": { - "*/*": { + "image/png": { "schema": { "type": "string", "format": "binary" diff --git a/openapi-full.json b/openapi-full.json index c7c79e3450..eb2e759c59 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -809,7 +809,8 @@ }, "nodeId": { "type": "integer", - "format": "int64" + "format": "int64", + "nullable": true }, "uuid": { "type": "string" @@ -1183,126 +1184,6 @@ } } }, - "File": { - "type": "object", - "required": [ - "account", - "file_type", - "created_at", - "file" - ], - "properties": { - "account": { - "type": "object", - "required": [ - "userId", - "displayName" - ], - "properties": { - "userId": { - "type": "string" - }, - "displayName": { - "type": "string" - } - } - }, - "file_type": { - "type": "object", - "required": [ - "type", - "name", - "description" - ], - "properties": { - "type": { - "type": "string" - }, - "name": { - "type": "string" - }, - "description": { - "type": "string", - "nullable": true - } - } - }, - "created_at": { - "type": "string" - }, - "file": { - "type": "object", - "required": [ - "name", - "status", - "statusText", - "created_at", - "file", - "uuid", - "signers" - ], - "properties": { - "name": { - "type": "string" - }, - "status": { - "type": "integer", - "format": "int64", - "enum": [ - 0, - 1, - 2, - 3, - 4, - 6 - ] - }, - "statusText": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "file": { - "type": "object", - "required": [ - "type", - "nodeId", - "signedNodeId", - "url" - ], - "properties": { - "type": { - "type": "string" - }, - "nodeId": { - "type": "integer", - "format": "int64", - "minimum": 0 - }, - "signedNodeId": { - "type": "integer", - "format": "int64", - "minimum": 0 - }, - "url": { - "type": "string" - } - } - }, - "uuid": { - "type": "string" - }, - "signers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SignerDetail" - } - } - } - } - } - }, "FileElementIdResponse": { "type": "object", "required": [ @@ -1780,6 +1661,126 @@ } } }, + "IdDocFile": { + "type": "object", + "required": [ + "account", + "file_type", + "created_at", + "file" + ], + "properties": { + "account": { + "type": "object", + "required": [ + "userId", + "displayName" + ], + "properties": { + "userId": { + "type": "string" + }, + "displayName": { + "type": "string" + } + } + }, + "file_type": { + "type": "object", + "required": [ + "type", + "name", + "description" + ], + "properties": { + "type": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string", + "nullable": true + } + } + }, + "created_at": { + "type": "string" + }, + "file": { + "type": "object", + "required": [ + "name", + "status", + "statusText", + "created_at", + "file", + "uuid", + "signers" + ], + "properties": { + "name": { + "type": "string" + }, + "status": { + "type": "integer", + "format": "int64", + "enum": [ + 0, + 1, + 2, + 3, + 4, + 6 + ] + }, + "statusText": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "file": { + "type": "object", + "required": [ + "type", + "nodeId", + "signedNodeId", + "url" + ], + "properties": { + "type": { + "type": "string" + }, + "nodeId": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "signedNodeId": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "url": { + "type": "string" + } + } + }, + "uuid": { + "type": "string" + }, + "signers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SignerDetail" + } + } + } + } + } + }, "IdDocs": { "type": "object", "required": [ @@ -1810,7 +1811,7 @@ "data": { "type": "array", "items": { - "$ref": "#/components/schemas/File" + "$ref": "#/components/schemas/IdDocFile" } } } @@ -1828,7 +1829,7 @@ "data": { "type": "array", "items": { - "$ref": "#/components/schemas/File" + "$ref": "#/components/schemas/IdDocFile" } } } @@ -4282,7 +4283,7 @@ "200": { "description": "CRL retrieved successfully in DER format", "content": { - "*/*": { + "application/pkix-crl": { "schema": { "type": "string", "format": "binary" @@ -7266,36 +7267,6 @@ } } } - }, - "422": { - "description": "Failed", - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "ocs" - ], - "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/ActionErrorResponse" - } - } - } - } - } - } - } } } } @@ -12354,7 +12325,7 @@ } }, "422": { - "description": "Unauthorized", + "description": "Request cannot be processed", "content": { "application/json": { "schema": { @@ -12374,14 +12345,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "anyOf": [ - { - "$ref": "#/components/schemas/MessageResponse" - }, - { - "$ref": "#/components/schemas/ActionErrorResponse" - } - ] + "$ref": "#/components/schemas/MessageResponse" } } } @@ -12573,7 +12537,7 @@ } }, "422": { - "description": "Unauthorized", + "description": "Request cannot be processed", "content": { "application/json": { "schema": { @@ -12593,14 +12557,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "anyOf": [ - { - "$ref": "#/components/schemas/MessageResponse" - }, - { - "$ref": "#/components/schemas/ActionErrorResponse" - } - ] + "$ref": "#/components/schemas/MessageResponse" } } } @@ -12807,7 +12764,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/ActionErrorResponse" + "$ref": "#/components/schemas/MessageResponse" } } } @@ -12954,36 +12911,6 @@ } } } - }, - "422": { - "description": "Failed", - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "ocs" - ], - "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/ActionErrorResponse" - } - } - } - } - } - } - } } } }, @@ -16148,8 +16075,18 @@ "responses": { "200": { "description": "Image returned", + "headers": { + "Content-Disposition": { + "schema": { + "type": "string", + "enum": [ + "attachment; filename=\"background.png\"" + ] + } + } + }, "content": { - "*/*": { + "image/png": { "schema": { "type": "string", "format": "binary" diff --git a/openapi.json b/openapi.json index 6b4e635e67..47c46370de 100644 --- a/openapi.json +++ b/openapi.json @@ -536,7 +536,8 @@ }, "nodeId": { "type": "integer", - "format": "int64" + "format": "int64", + "nullable": true }, "uuid": { "type": "string" @@ -856,126 +857,6 @@ } } }, - "File": { - "type": "object", - "required": [ - "account", - "file_type", - "created_at", - "file" - ], - "properties": { - "account": { - "type": "object", - "required": [ - "userId", - "displayName" - ], - "properties": { - "userId": { - "type": "string" - }, - "displayName": { - "type": "string" - } - } - }, - "file_type": { - "type": "object", - "required": [ - "type", - "name", - "description" - ], - "properties": { - "type": { - "type": "string" - }, - "name": { - "type": "string" - }, - "description": { - "type": "string", - "nullable": true - } - } - }, - "created_at": { - "type": "string" - }, - "file": { - "type": "object", - "required": [ - "name", - "status", - "statusText", - "created_at", - "file", - "uuid", - "signers" - ], - "properties": { - "name": { - "type": "string" - }, - "status": { - "type": "integer", - "format": "int64", - "enum": [ - 0, - 1, - 2, - 3, - 4, - 6 - ] - }, - "statusText": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "file": { - "type": "object", - "required": [ - "type", - "nodeId", - "signedNodeId", - "url" - ], - "properties": { - "type": { - "type": "string" - }, - "nodeId": { - "type": "integer", - "format": "int64", - "minimum": 0 - }, - "signedNodeId": { - "type": "integer", - "format": "int64", - "minimum": 0 - }, - "url": { - "type": "string" - } - } - }, - "uuid": { - "type": "string" - }, - "signers": { - "type": "array", - "items": { - "$ref": "#/components/schemas/SignerDetail" - } - } - } - } - } - }, "FileElementIdResponse": { "type": "object", "required": [ @@ -1405,6 +1286,126 @@ } ] }, + "IdDocFile": { + "type": "object", + "required": [ + "account", + "file_type", + "created_at", + "file" + ], + "properties": { + "account": { + "type": "object", + "required": [ + "userId", + "displayName" + ], + "properties": { + "userId": { + "type": "string" + }, + "displayName": { + "type": "string" + } + } + }, + "file_type": { + "type": "object", + "required": [ + "type", + "name", + "description" + ], + "properties": { + "type": { + "type": "string" + }, + "name": { + "type": "string" + }, + "description": { + "type": "string", + "nullable": true + } + } + }, + "created_at": { + "type": "string" + }, + "file": { + "type": "object", + "required": [ + "name", + "status", + "statusText", + "created_at", + "file", + "uuid", + "signers" + ], + "properties": { + "name": { + "type": "string" + }, + "status": { + "type": "integer", + "format": "int64", + "enum": [ + 0, + 1, + 2, + 3, + 4, + 6 + ] + }, + "statusText": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "file": { + "type": "object", + "required": [ + "type", + "nodeId", + "signedNodeId", + "url" + ], + "properties": { + "type": { + "type": "string" + }, + "nodeId": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "signedNodeId": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "url": { + "type": "string" + } + } + }, + "uuid": { + "type": "string" + }, + "signers": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SignerDetail" + } + } + } + } + } + }, "IdDocs": { "type": "object", "required": [ @@ -1435,7 +1436,7 @@ "data": { "type": "array", "items": { - "$ref": "#/components/schemas/File" + "$ref": "#/components/schemas/IdDocFile" } } } @@ -1453,7 +1454,7 @@ "data": { "type": "array", "items": { - "$ref": "#/components/schemas/File" + "$ref": "#/components/schemas/IdDocFile" } } } @@ -3740,7 +3741,7 @@ "200": { "description": "CRL retrieved successfully in DER format", "content": { - "*/*": { + "application/pkix-crl": { "schema": { "type": "string", "format": "binary" @@ -6724,36 +6725,6 @@ } } } - }, - "422": { - "description": "Failed", - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "ocs" - ], - "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/ActionErrorResponse" - } - } - } - } - } - } - } } } } @@ -11617,7 +11588,7 @@ } }, "422": { - "description": "Unauthorized", + "description": "Request cannot be processed", "content": { "application/json": { "schema": { @@ -11637,14 +11608,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "anyOf": [ - { - "$ref": "#/components/schemas/MessageResponse" - }, - { - "$ref": "#/components/schemas/ActionErrorResponse" - } - ] + "$ref": "#/components/schemas/MessageResponse" } } } @@ -11836,7 +11800,7 @@ } }, "422": { - "description": "Unauthorized", + "description": "Request cannot be processed", "content": { "application/json": { "schema": { @@ -11856,14 +11820,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "anyOf": [ - { - "$ref": "#/components/schemas/MessageResponse" - }, - { - "$ref": "#/components/schemas/ActionErrorResponse" - } - ] + "$ref": "#/components/schemas/MessageResponse" } } } @@ -12070,7 +12027,7 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/ActionErrorResponse" + "$ref": "#/components/schemas/MessageResponse" } } } @@ -12217,36 +12174,6 @@ } } } - }, - "422": { - "description": "Failed", - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "ocs" - ], - "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/ActionErrorResponse" - } - } - } - } - } - } - } } } }, diff --git a/src/tests/views/Documents/IdDocsValidation.spec.ts b/src/tests/views/Documents/IdDocsValidation.spec.ts index 639e6386cc..696022d0c9 100644 --- a/src/tests/views/Documents/IdDocsValidation.spec.ts +++ b/src/tests/views/Documents/IdDocsValidation.spec.ts @@ -110,7 +110,7 @@ vi.mock('@nextcloud/vue/components/NcIconSvgWrapper', () => ({ })) describe('IdDocsValidation.vue', () => { - type IdDocEntry = components['schemas']['File'] + type IdDocEntry = components['schemas']['IdDocFile'] const signedDoc: IdDocEntry = { account: { diff --git a/src/types/openapi/openapi-administration.ts b/src/types/openapi/openapi-administration.ts index 6a280db00c..29e2778155 100644 --- a/src/types/openapi/openapi-administration.ts +++ b/src/types/openapi/openapi-administration.ts @@ -984,10 +984,11 @@ export interface operations { /** @description Image returned */ 200: { headers: { + "Content-Disposition"?: "attachment; filename=\"background.png\""; [name: string]: unknown; }; content: { - "*/*": string; + "image/png": string; }; }; /** @description Current user is not logged in */ diff --git a/src/types/openapi/openapi-full.ts b/src/types/openapi/openapi-full.ts index a37db13462..1b7580b296 100644 --- a/src/types/openapi/openapi-full.ts +++ b/src/types/openapi/openapi-full.ts @@ -1571,7 +1571,7 @@ export type components = { /** Format: int64 */ id: number; /** Format: int64 */ - nodeId: number; + nodeId: number | null; uuid: string; name: string; /** Format: int64 */ @@ -1673,38 +1673,6 @@ export type components = { status: "failure"; message: string; }; - File: { - account: { - userId: string; - displayName: string; - }; - file_type: { - type: string; - name: string; - description: string | null; - }; - created_at: string; - file: { - name: string; - /** - * Format: int64 - * @enum {integer} - */ - status: 0 | 1 | 2 | 3 | 4 | 6; - statusText: string; - created_at: string; - file: { - type: string; - /** Format: int64 */ - nodeId: number; - /** Format: int64 */ - signedNodeId: number; - url: string; - }; - uuid: string; - signers: components["schemas"]["SignerDetail"][]; - }; - }; FileElementIdResponse: { /** Format: int64 */ fileElementId: number; @@ -1836,6 +1804,38 @@ export type components = { HasRootCertResponse: { hasRootCert: boolean; }; + IdDocFile: { + account: { + userId: string; + displayName: string; + }; + file_type: { + type: string; + name: string; + description: string | null; + }; + created_at: string; + file: { + name: string; + /** + * Format: int64 + * @enum {integer} + */ + status: 0 | 1 | 2 | 3 | 4 | 6; + statusText: string; + created_at: string; + file: { + type: string; + /** Format: int64 */ + nodeId: number; + /** Format: int64 */ + signedNodeId: number; + url: string; + }; + uuid: string; + signers: components["schemas"]["SignerDetail"][]; + }; + }; IdDocs: { file: components["schemas"]["NewFile"]; name?: string; @@ -1843,11 +1843,11 @@ export type components = { }; IdDocsApprovalListResponse: { pagination: components["schemas"]["Pagination"]; - data: components["schemas"]["File"][]; + data: components["schemas"]["IdDocFile"][]; }; IdDocsListResponse: { pagination: components["schemas"]["Pagination"]; - data: components["schemas"]["File"][]; + data: components["schemas"]["IdDocFile"][]; }; IdDocsUploadErrorResponse: { /** Format: int64 */ @@ -2565,7 +2565,7 @@ export interface operations { [name: string]: unknown; }; content: { - "*/*": string; + "application/pkix-crl": string; }; }; /** @description Failed to generate CRL */ @@ -3815,20 +3815,6 @@ export interface operations { }; }; }; - /** @description Failed */ - 422: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; - }; - }; - }; - }; }; }; "file_element-create-visible-element": { @@ -6029,7 +6015,7 @@ export interface operations { }; }; }; - /** @description Unauthorized */ + /** @description Request cannot be processed */ 422: { headers: { [name: string]: unknown; @@ -6038,7 +6024,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"]; }; }; }; @@ -6138,7 +6124,7 @@ export interface operations { }; }; }; - /** @description Unauthorized */ + /** @description Request cannot be processed */ 422: { headers: { [name: string]: unknown; @@ -6147,7 +6133,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"]; }; }; }; @@ -6214,7 +6200,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"]; }; }; }; @@ -6348,20 +6334,6 @@ export interface operations { }; }; }; - /** @description Failed */ - 422: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; - }; - }; - }; - }; }; }; "sign_file-sign-by-signer-uuid": { @@ -7606,10 +7578,11 @@ export interface operations { /** @description Image returned */ 200: { headers: { + "Content-Disposition"?: "attachment; filename=\"background.png\""; [name: string]: unknown; }; content: { - "*/*": string; + "image/png": string; }; }; /** @description Current user is not logged in */ diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 9fd7aa8f47..a6f4a0019d 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1171,7 +1171,7 @@ export type components = { /** Format: int64 */ id: number; /** Format: int64 */ - nodeId: number; + nodeId: number | null; uuid: string; name: string; /** Format: int64 */ @@ -1259,38 +1259,6 @@ export type components = { ErrorsResponse: { errors: components["schemas"]["ErrorItem"][]; }; - File: { - account: { - userId: string; - displayName: string; - }; - file_type: { - type: string; - name: string; - description: string | null; - }; - created_at: string; - file: { - name: string; - /** - * Format: int64 - * @enum {integer} - */ - status: 0 | 1 | 2 | 3 | 4 | 6; - statusText: string; - created_at: string; - file: { - type: string; - /** Format: int64 */ - nodeId: number; - /** Format: int64 */ - signedNodeId: number; - url: string; - }; - uuid: string; - signers: components["schemas"]["SignerDetail"][]; - }; - }; FileElementIdResponse: { /** Format: int64 */ fileElementId: number; @@ -1409,6 +1377,38 @@ export type components = { deletableByCurrentActor: boolean; }; GroupPolicyWriteResponse: components["schemas"]["MessageResponse"] & components["schemas"]["GroupPolicyResponse"]; + IdDocFile: { + account: { + userId: string; + displayName: string; + }; + file_type: { + type: string; + name: string; + description: string | null; + }; + created_at: string; + file: { + name: string; + /** + * Format: int64 + * @enum {integer} + */ + status: 0 | 1 | 2 | 3 | 4 | 6; + statusText: string; + created_at: string; + file: { + type: string; + /** Format: int64 */ + nodeId: number; + /** Format: int64 */ + signedNodeId: number; + url: string; + }; + uuid: string; + signers: components["schemas"]["SignerDetail"][]; + }; + }; IdDocs: { file: components["schemas"]["NewFile"]; name?: string; @@ -1416,11 +1416,11 @@ export type components = { }; IdDocsApprovalListResponse: { pagination: components["schemas"]["Pagination"]; - data: components["schemas"]["File"][]; + data: components["schemas"]["IdDocFile"][]; }; IdDocsListResponse: { pagination: components["schemas"]["Pagination"]; - data: components["schemas"]["File"][]; + data: components["schemas"]["IdDocFile"][]; }; IdDocsUploadErrorResponse: { /** Format: int64 */ @@ -2097,7 +2097,7 @@ export interface operations { [name: string]: unknown; }; content: { - "*/*": string; + "application/pkix-crl": string; }; }; /** @description Failed to generate CRL */ @@ -3347,20 +3347,6 @@ export interface operations { }; }; }; - /** @description Failed */ - 422: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; - }; - }; - }; - }; }; }; "file_element-create-visible-element": { @@ -5467,7 +5453,7 @@ export interface operations { }; }; }; - /** @description Unauthorized */ + /** @description Request cannot be processed */ 422: { headers: { [name: string]: unknown; @@ -5476,7 +5462,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"]; }; }; }; @@ -5576,7 +5562,7 @@ export interface operations { }; }; }; - /** @description Unauthorized */ + /** @description Request cannot be processed */ 422: { headers: { [name: string]: unknown; @@ -5585,7 +5571,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"]; }; }; }; @@ -5652,7 +5638,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"]; }; }; }; @@ -5786,20 +5772,6 @@ export interface operations { }; }; }; - /** @description Failed */ - 422: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; - }; - }; - }; - }; }; }; "sign_file-sign-by-signer-uuid": { diff --git a/src/views/Documents/IdDocsValidation.vue b/src/views/Documents/IdDocsValidation.vue index 9e561d64e1..7da52e2bbf 100644 --- a/src/views/Documents/IdDocsValidation.vue +++ b/src/views/Documents/IdDocsValidation.vue @@ -221,7 +221,7 @@ type StatusOption = { } type PersistedStatusFilter = StatusOption['value'] | null -type IdDocEntry = components['schemas']['File'] +type IdDocEntry = components['schemas']['IdDocFile'] type IdDocsListQuery = NonNullable type IdDocsListSuccess = operations['id_docs-list-to-approval']['responses'][200]['content']['application/json'] type IdDocsListError = operations['id_docs-list-to-approval']['responses'][404]['content']['application/json'] diff --git a/tests/php/openapi/OpenApiBinaryMediaTypesTest.php b/tests/php/openapi/OpenApiBinaryMediaTypesTest.php new file mode 100644 index 0000000000..82b5d29054 --- /dev/null +++ b/tests/php/openapi/OpenApiBinaryMediaTypesTest.php @@ -0,0 +1,46 @@ + ['openapi-full.json', 'crl-get-revocation-list', 'application/pkix-crl'], + 'CRL download in the default scope' => ['openapi.json', 'crl-get-revocation-list', 'application/pkix-crl'], + 'admin background image' => ['openapi-full.json', 'admin-signature-background-get', 'image/png'], + 'certificate policy PDF' => ['openapi-full.json', 'certificate_policy-get-certificate-policy', 'application/pdf'], + ]; + } + + #[DataProvider('mediaTypeProvider')] + public function testBinaryResponseDeclaresItsFixedMediaType(string $file, string $operationId, string $mediaType): void { + $source = file_get_contents(dirname(__DIR__, 3) . '/' . $file); + self::assertNotFalse($source); + $spec = json_decode($source, true, 512, JSON_THROW_ON_ERROR); + + $content = null; + foreach ($spec['paths'] as $methods) { + foreach ($methods as $operation) { + if (is_array($operation) && ($operation['operationId'] ?? null) === $operationId) { + $content = $operation['responses']['200']['content'] ?? null; + } + } + } + + // Thumbnails and signature element previews keep */* on purpose: their + // media type depends on the previewed file. + self::assertIsArray($content, $operationId); + self::assertSame([$mediaType], array_keys($content), $operationId); + self::assertSame(['type' => 'string', 'format' => 'binary'], $content[$mediaType]['schema'], $operationId); + } +} diff --git a/tests/php/openapi/OpenApiErrorBodyContractTest.php b/tests/php/openapi/OpenApiErrorBodyContractTest.php new file mode 100644 index 0000000000..7ffade06e7 --- /dev/null +++ b/tests/php/openapi/OpenApiErrorBodyContractTest.php @@ -0,0 +1,91 @@ + ['openapi.json'], + 'full scope' => ['openapi-full.json'], + ]; + } + + #[DataProvider('specificationProvider')] + public function testRequestSignatureOnlyReturnsAMessageWith422(string $file): void { + $paths = $this->load($file)['paths']; + + foreach (['post', 'patch'] as $method) { + self::assertSame( + '#/components/schemas/MessageResponse', + $this->errorData($paths[self::BASE . 'request-signature'][$method], '422')['$ref'] ?? null, + $method, + ); + } + } + + #[DataProvider('specificationProvider')] + public function testRemoveSignerDocumentsTheMessageItReturns(string $file): void { + $operation = $this->load($file)['paths'][self::BASE . 'sign/file_id/{fileId}/{signRequestId}']['delete']; + + self::assertSame('#/components/schemas/MessageResponse', $this->errorData($operation, '422')['$ref'] ?? null); + } + + #[DataProvider('specificationProvider')] + public function testDeleteOperationsDoNotDocumentAnUnreachable422(string $file): void { + $paths = $this->load($file)['paths']; + + foreach (['file/file_id/{fileId}', 'sign/file_id/{fileId}'] as $path) { + self::assertArrayNotHasKey('422', $paths[self::BASE . $path]['delete']['responses'], $path); + } + } + + #[DataProvider('specificationProvider')] + public function testNotifyKeepsBothRealBodiesAt422(string $file): void { + // canRequestSign() throws an action/errors body, other validations a message. + $paths = $this->load($file)['paths']; + + foreach (['notify/signers', 'notify/signer'] as $path) { + $data = $this->errorData($paths[self::BASE . $path]['post'], '422'); + self::assertEqualsCanonicalizing( + ['#/components/schemas/MessageResponse', '#/components/schemas/ActionErrorResponse'], + array_column($data['anyOf'] ?? [], '$ref'), + $path, + ); + } + } + + #[DataProvider('specificationProvider')] + public function testDetailedFileNodeIdIsNullable(string $file): void { + // libresign_file.node_id is nullable and the value is copied as is. + $nodeId = $this->load($file)['components']['schemas']['DetailedFile']['properties']['nodeId']; + + self::assertTrue($nodeId['nullable'] ?? false); + } + + private function errorData(array $operation, string $status): array { + return $operation['responses'][$status]['content']['application/json']['schema']['properties']['ocs']['properties']['data'] ?? []; + } + + private function load(string $file): array { + $source = file_get_contents(dirname(__DIR__, 3) . '/' . $file); + self::assertNotFalse($source); + + return json_decode($source, true, 512, JSON_THROW_ON_ERROR); + } +} diff --git a/tests/php/openapi/OpenApiIdDocSchemaTest.php b/tests/php/openapi/OpenApiIdDocSchemaTest.php new file mode 100644 index 0000000000..b6562e9ce1 --- /dev/null +++ b/tests/php/openapi/OpenApiIdDocSchemaTest.php @@ -0,0 +1,42 @@ + ['openapi.json'], + 'full scope' => ['openapi-full.json'], + ]; + } + + #[DataProvider('specificationProvider')] + public function testIdDocumentRecordHasADomainSpecificSchemaName(string $file): void { + $source = file_get_contents(dirname(__DIR__, 3) . '/' . $file); + self::assertNotFalse($source); + + $schemas = json_decode($source, true, 512, JSON_THROW_ON_ERROR)['components']['schemas']; + + // A schema named File collides with the global File type of TypeScript + // and is too generic: other schemas describe different file records. + self::assertArrayNotHasKey('File', $schemas); + self::assertArrayHasKey('IdDocFile', $schemas); + foreach (['IdDocsListResponse', 'IdDocsApprovalListResponse'] as $response) { + self::assertSame( + '#/components/schemas/IdDocFile', + $schemas[$response]['properties']['data']['items']['$ref'] ?? null, + $response, + ); + } + } +} diff --git a/tests/php/openapi/phpunit.xml b/tests/php/openapi/phpunit.xml index c9ec9062ea..bc3ff0aa7c 100644 --- a/tests/php/openapi/phpunit.xml +++ b/tests/php/openapi/phpunit.xml @@ -13,8 +13,11 @@ colors="true"> + OpenApiBinaryMediaTypesTest.php + OpenApiErrorBodyContractTest.php OpenApiFunctionalTagsTest.php OpenApiGenerationTest.php + OpenApiIdDocSchemaTest.php OpenApiPolicyNumberUnionTest.php OpenApiRequestHeadersTest.php OpenApiSigningRequestContractsTest.php From 9c08b92a363bb3d1ea0888c4effc9a6ce7efa2f1 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 10:08:40 -0300 Subject: [PATCH 02/14] test(sdk): re-evaluate typescript-axios against the current contract Re-run the #9089 evaluation on main with the LibreSign contract fixes: - inject the real `@nextcloud/axios` instance (jsdom) into a generated client and cover requesttoken, X-Requested-With, OCS-APIRequest and the CSRF retry; - turn the former `anyOf` reproduction into a regression guard and add `union-defects.ts`, which compiles only while the remaining object unions are still generated incorrectly; - replace the removed `callback` checks with `status`; - record the result in REPORT.md (still No-Go for unmodified input) and the extractor and generator follow-ups in UPSTREAM-NOTES.md, including what remains open in LibreSign. No generator, extractor or generated source is modified. Signed-off-by: Luis Amorim --- tests/sdk-generation/README.md | 44 +- tests/sdk-generation/REPORT.md | 279 ++++++---- tests/sdk-generation/UPSTREAM-NOTES.md | 248 +++++++++ tests/sdk-generation/anyof-defect.ts | 23 +- tests/sdk-generation/nextcloud-axios.test.ts | 60 +++ tests/sdk-generation/package-lock.json | 536 +++++++++++++++++++ tests/sdk-generation/package.json | 8 +- tests/sdk-generation/types.ts | 6 +- tests/sdk-generation/union-defects.ts | 24 + 9 files changed, 1103 insertions(+), 125 deletions(-) create mode 100644 tests/sdk-generation/UPSTREAM-NOTES.md create mode 100644 tests/sdk-generation/nextcloud-axios.test.ts create mode 100644 tests/sdk-generation/union-defects.ts diff --git a/tests/sdk-generation/README.md b/tests/sdk-generation/README.md index 98b66ff0ef..4d9bbe33f9 100644 --- a/tests/sdk-generation/README.md +++ b/tests/sdk-generation/README.md @@ -18,12 +18,14 @@ npm test --prefix tests/sdk-generation npm run test:anyof --prefix tests/sdk-generation ``` -The last command **passes while the known defect exists**: it assigns an invalid -array to the generated `EffectivePolicyValue` without suppressing diagnostics. -A missing client fails with TS2307; a corrected type that rejects arrays fails -with TS2322 and requires reevaluating the No-Go report. `npm test` checks -transport, generation cleanup and live-check error handling, and writes -the generated operation inventory to `build/sdk-generation/inventory.md`. +`test:anyof` has two parts. `anyof-defect.ts` is a regression guard: the generated +`EffectivePolicyValue` must keep rejecting arrays and `undefined`. `union-defects.ts` +**passes while known defects exist**: each `@ts-expect-error` marks a valid contract +value that the generated model rejects or over-accepts. When a defect is fixed, +compilation fails with TS2578 and the report must be reevaluated. `npm test` checks +transport, generation cleanup, live-check error handling and real `@nextcloud/axios` +injection under jsdom, and writes the generated operation inventory to +`build/sdk-generation/inventory.md`. Compare that inventory with the checked-in evaluation snapshot when changing the specification. This does not prove every operation's runtime serialization. @@ -38,7 +40,7 @@ See [REPORT.md](REPORT.md) and [inventory.md](inventory.md) for results. ## Normalized-input experiment -This separate experiment changes all 22 `anyOf` keywords to `oneOf` in a +This separate experiment changes all 12 `anyOf` keywords to `oneOf` in a **disposable generator input**, never in the committed specification: ```sh @@ -47,24 +49,28 @@ tests/sdk-generation/generate.sh build/sdk-generation/normalized/typescript buil npm run test:normalized --prefix tests/sdk-generation ``` -The positive/negative type checks pass, including rejection of the invalid -policy array and invalid scalar object unions. They also explicitly record that -schema-valid `null` is still rejected. This is partial mitigation, not a Go. -`oneOf` and `anyOf` are not equivalent validation contracts: `integer` and -`number` overlap. The transformed file must never replace the source contract. +The positive/negative type checks pass, including the object unions that the +unmodified output merges incorrectly. They also record that schema-valid `null` +is still rejected by the standalone union. This is partial mitigation, not a Go. +`oneOf` and `anyOf` are not equivalent validation contracts: overlapping object +branches would violate `oneOf`. The transformed file must never replace the +source contract. -## Real Nextcloud Axios import probe +## Real Nextcloud Axios ```sh +npm test --prefix tests/sdk-generation # includes nextcloud-axios.test.ts npm run test:nextcloud --prefix tests/sdk-generation ``` -With the locked `@nextcloud/axios` 2.6.0 on Node 24.22.2 this **fails** with -`ReferenceError: window is not defined` in `@nextcloud/browser-storage`, imported -by `@nextcloud/auth`. This invokes the real ESM package without browser shims. -Real Nextcloud instance injection therefore remains unverified; the deterministic -transport tests use ordinary Axios. Browser integration and CSRF retry behavior -need a separate browser environment. +`nextcloud-axios.test.ts` installs a jsdom window, injects the real locked +`@nextcloud/axios` instance into a generated API class and checks its default +`requesttoken`/`X-Requested-With` headers, the `OCS-APIRequest` header and the +package's own 412 CSRF retry. Only the network adapter and `fetch` are +replaced. `test:nextcloud` is the Node-only probe without browser globals; it +**fails** with `ReferenceError: window is not defined`, recording that the +package needs a browser-like environment. A real browser and Nextcloud server +remain unverified. ## Optional live Nextcloud check diff --git a/tests/sdk-generation/REPORT.md b/tests/sdk-generation/REPORT.md index 5afd01fba7..be2d82a196 100644 --- a/tests/sdk-generation/REPORT.md +++ b/tests/sdk-generation/REPORT.md @@ -5,134 +5,223 @@ # Compatibility evaluation -## Decision: No-Go for unmodified input - -OpenAPI Generator 7.27.0's `typescript-axios` output is not a sufficiently -faithful SDK foundation: `EffectivePolicyValue` is an empty interface and -accepts invalid arrays. Version 7.15.0 has the same defect. The separate -normalized-input experiment partially improves unions; it does not change -this decision or approve any source contract change. Multipart is tracked -separately in #9435. +## Decision: still No-Go for unmodified input, with a different blocker + +Re-run against `main` at `40ee2280737e54ebf798bbc1f77bf4272cbe9320`. The defect +that justified the earlier No-Go is fixed: `EffectivePolicyValue` is now +`boolean | number | string | { [key: string]: object }`, rejects arrays and +keeps `| null` at the properties that reference it (disjoint `oneOf` contract, +#9494). Generation, strict compilation, inventory, transport and real +`@nextcloud/axios` injection all pass. + +The decision remains No-Go for unmodified input because three generated models +(and the 9 error-body models) of the remaining 12 `anyOf` constructs are still +incorrect +(see [Remaining model defects](#remaining-model-defects)), and multipart +bodies are still absent from the contract. Every blocker left is on the +extractor/generator side or needs a maintainer decision about the contract +shape; see [UPSTREAM-NOTES.md](UPSTREAM-NOTES.md). This evaluation selects no +option and changes no PHP controller, extractor, committed OpenAPI, generated +frontend type, CI job or permanent SDK. ## Input and toolchain -- Application base: `9aebe13938369e70344a4fb1e16fc331387427ea` (upstream main). -- `openapi-full.json` SHA-256: - `2501bc11fcee0545dfb703a28d93018a80e62f6e14ba81bae549d1b130de9243`. +- Application base: `40ee2280737e54ebf798bbc1f77bf4272cbe9320` (`main`), plus + three LibreSign changes described below: the ID document schema `File` renamed + to `IdDocFile`, literal media types for the CRL and the admin background, and + error-body annotations aligned with what the controllers return (see + [Error bodies aligned with the code](#error-bodies-aligned-with-the-code)). +- `openapi-full.json` SHA-256 with those changes: `76b093d3325b9504ba7911ba487b9424d7e9821bd2f2f9905d01756371ba8bf9` + (`64c52fa2ba243af292eba30055982954bfd8c19136567e50e28c4abcffcc9405` on `main`). +- Extractor used to produce the contract: `nextcloud/openapi-extractor` 1.9.1. - Generator: `openapitools/openapi-generator-cli` 7.27.0 at `sha256:949efd0d5cf3c093ef169887b2ebe0879ee2e8074b6476264232ce4fd8ef46d0`; `typescript-axios`, `useSingleRequestParameter=true`. -- Previous comparison: 7.15.0 at - `sha256:509f01c3c7eee9d1ad286506a7b6aa4624a95b410be9a238a306d209e900621f`. -- TypeScript 5.8.3, Axios 1.20.0, `@nextcloud/axios` 2.6.0, tsx 4.19.4; - Node 24.22.2, npm 11.19.1. npm dependencies/transitives are locked. - Axios matches the application's locked version and satisfies Nextcloud Axios. -- All deterministic README commands ran with fresh generated directories. - Validation succeeded with unused `Capabilities` and `PublicCapabilities` - warnings. Two generations had an empty recursive diff including metadata. +- TypeScript 5.8.3, Axios 1.20.0, `@nextcloud/axios` 2.6.0, jsdom 26.1.0 + (test only), tsx 4.19.4; Node 24.22.3, npm 11.19.1 (an independent re-run on + Node 26.0.0 also passed). Dependencies and + transitives are locked. +- Validation succeeds with the unused `Capabilities`/`PublicCapabilities` + warnings. Two generations have an empty recursive diff including metadata. No generated source was edited. -- Warm timings: setup 1.05 s; validation/generation 4.91 s (repeat 5.79 s); - strict compilation 2.09 s; transport/inventory 1.06 s; normalized - validation/generation 4.71 s and type checks 1.36 s. These are single-machine - observations with cached images, not cold CI benchmarks. No CI job is added. +- Warm timings on one machine with cached images (not a cold CI benchmark): + setup about 1 s; validation + generation 4.6 s (repeat 4.1 s); strict + compilation 1.4 s; `npm test` 2.3 s; union checks 0.9 s. No CI job is added. -## Unmodified input results +## Results for the unmodified input The [inventory](inventory.md) covers 90 operations (69 default, 21 -administration), rather than the issue's original 88: 90 matched, zero inventory -errors, ten functional classes. The checked-in snapshot matches the new output. -The check matches method/path, generated documentation and public TypeScript +administration) across the ten functional tags: 90 matched, zero inventory +errors. Tag counts: appearance 17, certificates 12, documents 6, identity 14, +notifications 4, policies 17, requests 5, signing 8, system 3, verification 4. +This differs from the 88 operations and per-tag counts of the original issue +(appearance +1, notifications +1) because operations were added after it was +written. The check matches method/path, generated documentation and public class methods; it does not exhaustively validate signatures or serialization. -Generated Markdown examples still use positional arguments despite the chosen -single-request-parameter configuration; use actual class signatures. +Generated Markdown examples still use positional arguments despite +`useSingleRequestParameter=true`; use the actual class signatures. -Strict compilation with `skipLibCheck` passes. `types.ts` tests number/string -`NewFile.nodeId` (rejecting boolean), inherited/local `SignerDetail` fields, -nullable/optional fields and enums. `test:anyof` exits 0 because the generated -empty interface accepts an invalid policy array. This is a passing reproduction -of a failed SDK acceptance criterion, so the decision remains No-Go. The fixture -has no error suppression: missing generated output fails with TS2307; a type -that rejects arrays fails with TS2322, requiring the report to be reevaluated. +Strict compilation with `skipLibCheck` passes. `types.ts` checks number/string +`NewFile.nodeId` (rejecting boolean), inherited and local `SignerDetail` +fields, nullable/optional fields and enums. `RequestSignatureRequest` no longer +has `callback` (removed by #9505), so the nullable check uses `status`. +`anyof-defect.ts` is now a regression guard: arrays and `undefined` are +rejected by `EffectivePolicyValue`, and `effectiveValue: null` is accepted. The controlled Axios adapter tests generated calls for account GET and typed OCS envelope, encoded policy path and simulated HTTP 403, signature-request -JSON POST, and non-OCS PDF with explicit `responseType: arraybuffer`. Basic-only -and bearer-only configurations are independent, with assertions that the other -credential mechanism is absent. Both root and subdirectory paths pass. -An instance at `https://instance.test/installed` overrides configuration -`https://example.test/nextcloud` for both OCS and PDF URLs, proving precedence -with different values. - -The real locked `@nextcloud/axios` ESM import probe exits 1 in Node with -`ReferenceError: window is not defined`: `@nextcloud/auth` imports -`@nextcloud/browser-storage`, whose `StorageBuilder.build` accesses browser -storage during initialization. No browser globals are mocked. Real Nextcloud -Axios injection and its CSRF/session interceptors remain unverified; the -successful transport tests use ordinary Axios. +JSON POST, signing, appearance elements and non-OCS PDF with explicit +`responseType: arraybuffer`. Basic-only and bearer-only configurations are +independent. Root and subdirectory paths pass, and an instance base URL +overrides the configuration base path for OCS and PDF URLs. + +### Real `@nextcloud/axios` + +The Node-only import probe (`npm run test:nextcloud`) still fails with +`ReferenceError: window is not defined`: this is expected for a browser +package and is kept as the record of that requirement. A new test, +`nextcloud-axios.test.ts`, installs a jsdom window and injects the real locked +`@nextcloud/axios` instance into a generated `IdentityApi`. Only the network +adapter and `fetch` are replaced. It verifies the package defaults reach the +request (`requesttoken`, `X-Requested-With`), the generated `OCS-APIRequest` +header, the absolute subdirectory URL, and the package's own 412 "CSRF check +failed" retry: the retried request carries the refreshed token and +`/nextcloud/index.php/csrftoken` is the only token URL fetched. A real browser +and a real Nextcloud server remain unverified (real XHR adapter, cookies, +maintenance-mode and not-logged-in interceptors). + +### Remaining model defects + +`union-defects.ts` reproduces these defects with assertions that compile only +while the defect exists (`@ts-expect-error` for a valid value that is rejected, +a plain assignment for an invalid value that is accepted). Revisit the report as +soon as one of them fails (TS2578 or TS2322): + +| Schema | Contract | Generated | Effect | +| --- | --- | --- | --- | +| `FileListResponse.data[]` items | `anyOf` `FileSummary`, `DetailedFile` | one merged interface requiring `files`, `size` and `visibleElements`; `nodeId` narrowed to `number`; `signers` typed as `SignerDetail` | a valid `FileSummary` is not assignable | +| `FileRuntimeMetadata` | `anyOf` `ValidateMetadata`, `{ [key]: DynamicMetadataValue }` | only the `ValidateMetadata` fields, with `extension` and `p` required | a valid dynamic metadata object is rejected | +| `RequestPolicyOverrides` values | `anyOf` `EffectivePolicyValue`, array of it | empty interface `RequestPolicyOverridesValue` | accepts any non-null value | + +The other 9 `anyOf` occurrences are in 4xx bodies. Two (the 422 responses of +`notify-signers` and `notify-signer`) are real unions: `canRequestSign()` throws +an `{action, errors}` body (`ActionErrorResponse`), other validations a +`{message}` body (`MessageResponse`), both surfaced by the middleware. The +generator merges them into one interface (for example +`NotifySigners422ResponseOcsData` requires `action` and `errors`, which the +`MessageResponse` alternative does not have). The other seven (six 401 bodies +and the `footer-template` 403) are envelope-level `anyOf` whose second branch +has an untyped `data: {}`; they are generated as `...AnyOf1Ocs` models with +`data: any`. That reads the contract faithfully: the extractor's implicit 401/403 +has no typed body, so `X | {}` accepts anything. The typed branch is not lost by +the generator; the extractor adds the untyped one next to it. In +both cases the generator creates models for error bodies but method return +types only cover the success response, so callers receive errors as +`AxiosError` and must cast `error.response.data`. The `oneOf` constructs +(`NewFile.nodeId`, `RootCertificateName.value`, `UserConfigValue`, +`EffectivePolicyValue` and the inline `rootCert.names[].value` request +properties) generate correct unions. `UserConfigValue` includes `Array`; +`allowedValues` and the `values` maps are generated as `EffectivePolicyValue` +items without the contract's `null`. + +The schema formerly named `File` (an ID document record) was renamed to +`IdDocFile` in LibreSign. With the old name the generator renamed the model to +`ModelFile` but not its references, so `IdDocsListResponse.data` and +`IdDocsApprovalListResponse.data` were generated as `Array`, the only +unbounded `any` in the models. After the rename no `Array` remains and +`anyof-defect.ts` guards it. The underlying generator defect with reserved +model names is unchanged (see [UPSTREAM-NOTES.md](UPSTREAM-NOTES.md) G3). + +Other generator observations: binary responses are typed +as the DOM `File` although `responseType: arraybuffer` returns bytes; the +`OCS-APIRequest` header is a required boolean field named `oCSAPIRequest` of the +request object on all 87 OCS operations (positional only in the lower-level +generated functions and Markdown examples; the 3 non-OCS operations have none); +envelopes are not unwrapped. + +### Error bodies aligned with the code + +Two groups of documented error bodies did not match what the controllers send. +They were LibreSign annotations, not package defects, and were corrected: + +- `request-signature` (POST) and `update-signature-request` (PATCH) catch every + failure and return `{message}` with 422, but documented + `MessageResponse | ActionErrorResponse` and the description "Unauthorized". + They now document `MessageResponse` and "Request cannot be processed"; two + `anyOf` disappeared (14 became 12). +- `removeSigner` returns `{message}` with 401 or 422 and documented an + `ActionErrorResponse` 422; `deleteFile` and `deleteSignatureRequest` documented + a 422 they never return (the `RequireManager` middleware answers 401). +- `DetailedFile.nodeId` is now nullable: `libresign_file.node_id` is nullable + and the entity value is copied as is (`FileSummary` already allowed null). + +`tests/php/openapi/OpenApiErrorBodyContractTest.php` guards these shapes and +also records that the two `notify` 422 unions are real. + +Open decision for the maintainers, not changed here: six methods return HTTP +401 for any failure, including validation and business errors +(`AccountController::signatureGenerate`, the two certificate generators, +`deleteFile`, `deleteSignatureRequest`, `removeSigner`). A 401 means +"unauthenticated", so an SDK cannot tell an invalid session from a business +failure. Changing the status breaks compatibility and the Behat scenarios, so it +needs its own change. ## Normalized-input experiment `normalize-input.cjs` writes only -`build/sdk-generation/normalized/openapi-full.oneof.json`, renaming all 22 -`anyOf` keywords to `oneOf`. Generation is separate from the main evaluation. -It produces: - -- `EffectivePolicyValue = boolean | number | string | { [key: string]: object }`; -- `FileListResponseDataInner = DetailedFile | FileSummary`; -- `FileRuntimeMetadata = ValidateMetadata | { [key: string]: object }`. - -`test:normalized` passes strict compilation and positive/negative checks: -policy primitives/object values and object union members compile; policy arrays, -undefined and scalar file/metadata values are rejected. It also records a -remaining defect: schema-valid `null` is rejected by `EffectivePolicyValue`. -Passing this diagnostic suite does not establish full contract fidelity. - -This transformation is **generator-input normalization only**, not an equivalent -validation contract. In particular, integers match both `integer` and `number` -alternatives: `anyOf` allows that overlap, while `oneOf` requires exactly one -match. Never replace committed OpenAPI with this experiment's output. +`build/sdk-generation/normalized/openapi-full.oneof.json`, renaming the +remaining 12 `anyOf` keywords to `oneOf`. It generates +`FileListResponseDataInner = DetailedFile | FileSummary` and +`FileRuntimeMetadata = ValidateMetadata | { [key: string]: ... }`, and +`test:normalized` passes. It is generator-input normalization only: object +branches that overlap would also violate the `oneOf` "exactly one" rule, and +the transformed file must never replace the committed contract. The earlier +`integer`/`number` overlap argument no longer applies to policy values. ## Remaining limits -OCS envelopes are not automatically unwrapped, and callers must pass the OCS -header argument. Adapter status settlement is simulated; server authorization -and OCS-level errors inside HTTP 200 are not tested. Basic auth is inspected as -Axios config, not a real on-wire Authorization header. PDF types are generated -as `File` although explicit arraybuffer transport returns bytes; callers must -reconcile those types. No live Nextcloud checks were rerun for this version; -real account success, binary download, subdirectory deployment and state-changing -signature requests remain unverified. Tests sample models, not runtime JSON -validation or numerical limits. No production SDK or frontend migration is -included. +OCS envelopes are not automatically unwrapped. Adapter status settlement is +simulated; server authorization and OCS-level errors inside HTTP 200 are not +tested. Basic auth is inspected as Axios config, not as a real on-wire header. +PDF types are generated as `File` although arraybuffer transport returns bytes. +Live Nextcloud checks in `live.test.ts` use a local stub; no real server was +exercised in this run. Tests sample models and do not validate runtime JSON or +numerical limits. No production SDK or frontend migration is included. ## Multipart limitations -The harness checks the generated signatures and requests, and the controller -source supplies the expected upload names: +The contract still has no `multipart/form-data` request body for the six +operations tracked in #9435, which is closed on GitHub although no generated +request body exists yet; the merged work (#9452, #9490) added runtime +validation and endpoint descriptions, not request bodies. Upstream extractor support is open +(`nextcloud/openapi-extractor` #343 and PR #401). The harness checks +signatures and requests; controller source supplies the expected upload names: | operationId | Runtime upload | Generated behavior | | --- | --- | --- | -| `account-upload-pfx` | `file` in `AccountController::uploadPfx` | No typed file parameter or request body; generated call sends no body. | -| `file-save` | `file` or `files` in `FileController::prepareFilesForSaving` | Typed JSON body supports `NewFile` representations, but exposes no typed multipart upload. | -| `admin-signature-background-save` | `image` in `AdminController::signatureBackgroundSave` | No typed image parameter or request body; generated call sends no body. | +| `account-upload-pfx` | `file` in `AccountController::uploadPfx` | No typed file parameter or request body; sends no body. | +| `file-save` | `file`, `files[]` or legacy `file[]` | Typed JSON body only; no typed multipart upload. | +| `file-validate-binary` | `file` | No typed file parameter or request body. | +| `file-add-file-to-envelope` | `files[]` plus optional `expectedFilesCount` | No typed files or request body. | +| `admin-signature-background-save` | `image` | No typed image parameter or request body. | +| `admin-save-certificate-policy` | `pdf` | No typed file parameter or request body. | -Generic Axios options may allow a caller to handcraft a request, but that is not -verified typed multipart support. An official SDK or frontend migration would -need a reviewed contract/extractor correction and regenerated serialization, or -another explicitly designed solution. Changes to PHP or OpenAPI extraction are -outside this evaluation. +Generic Axios options can carry a handcrafted `FormData`, but that is not +verified typed multipart support. An official SDK or frontend migration needs +the extractor support above (or another reviewed design) and a regeneration. ## Handoff Maintainers must choose among these options; this evaluation selects none: -1. Conditional Go with reviewed generator-input normalization, addressing the - remaining nullable and transport limitations before SDK infrastructure. -2. Correct the source contract/extractor to emit `oneOf` where semantically - valid, explicitly resolving overlapping alternatives rather than blindly - renaming keywords. +1. Conditional Go with a reviewed generator-input normalization of the 12 + `anyOf` constructs, documented as non-contractual. +2. Fix the extractor (object unions, duplicated implicit 401/403) and the + generator upstream, and adjust LibreSign's own types or annotations where + their cause is confirmed to be in LibreSign, then regenerate. 3. Evaluate another generator against the same acceptance criteria. -Rerun the harness against the approved contract and toolchain. Multipart source -contract work belongs to #9435. No PHP controller, extractor, committed OpenAPI, -generated frontend type, CI job or permanent SDK is changed here. +Multipart needs the upstream extractor work in every option. Detailed +extractor/generator items and what remains unverified in this repository are +in [UPSTREAM-NOTES.md](UPSTREAM-NOTES.md). Rerun the harness against the +approved contract and toolchain before any decision. diff --git a/tests/sdk-generation/UPSTREAM-NOTES.md b/tests/sdk-generation/UPSTREAM-NOTES.md new file mode 100644 index 0000000000..ca6ce16acf --- /dev/null +++ b/tests/sdk-generation/UPSTREAM-NOTES.md @@ -0,0 +1,248 @@ + + +# Extractor and generator follow-ups + +Items found while re-running the #9089 evaluation against `main` at +`40ee2280737e54ebf798bbc1f77bf4272cbe9320` (`openapi-full.json` SHA-256 +`64c52fa2…c405`; the LibreSign-side fixes below change it). The items here cannot +be fixed in LibreSign without a local workaround, which the epic (#9087) forbids. Nothing here has been filed upstream yet; the +"Upstream status" lines say only what was checked. Reproduce evidence with +`tests/sdk-generation/README.md` and the checks named per item. + +Toolchain: `nextcloud/openapi-extractor` 1.9.1 (pinned in +`vendor-bin/openapi-extractor/composer.lock`), OpenAPI Generator 7.27.0 +`typescript-axios`, `useSingleRequestParameter=true`. + +## nextcloud/openapi-extractor + +### E1. Multipart request bodies for uploads (blocks the SDK) + +Six operations read `IRequest::getUploadedFile()` and have no multipart body +in the contract. Five have no `requestBody` at all: `account-upload-pfx` +(`file`), `file-validate-binary` (`file`), `file-add-file-to-envelope` +(`files[]`, optional `expectedFilesCount`), `admin-signature-background-save` +(`image`) and `admin-save-certificate-policy` (`pdf`). `file-save` has only an +`application/json` body; its multipart `file`, `files[]` and legacy `file[]` +are missing. + +Needed from the extractor: a `multipart/form-data` body with binary parts, +repeated array parts, optional/required semantics, and coexistence with a JSON +alternative on `file-save`. + +Upstream status: `nextcloud/openapi-extractor#343` (issue) and `#401` (PR) are +open; #401 is awaiting review. LibreSign keeps direct `getUploadedFile()` +calls in `FileController::save()` to stay compatible with that detection. +After it lands: regenerate, then verify that the generated client serializes +single and repeated files (not yet testable, see G5). + +### E2. Unions of objects and arrays are emitted as `anyOf` + +As #9494 showed, the extractor emitted `oneOf` for the policy value once its +scalar branches became disjoint. Unions that include objects or arrays (the policy-override one pairs a value with +an array of values) are still emitted as `anyOf`, +and OpenAPI Generator mishandles them (G1). Affected schemas, 12 in total: + +- `FileListResponse.data[]` items: `FileSummary | DetailedFile`; +- `FileRuntimeMetadata`: `ValidateMetadata | array`; +- `RequestPolicyOverrides` values: `EffectivePolicyValue | list`; +- 2 `422` bodies: `MessageResponse | ActionErrorResponse` (notify-signers and + notify-signer). This union is real: `canRequestSign()` throws an + `{action, errors}` body and other validations a `{message}` body. The same + union on `request-signature` and `update-signature-request` was a wrong + LibreSign annotation and was fixed (see "Left in LibreSign"); +- 7 error bodies (six 401 and the footer-template 403): an envelope `anyOf` + whose second branch has an untyped `data: {}`. Cause confirmed: for every + non-public OCS method the extractor adds an implicit 401 with an untyped + `data`, and a 403 for admin methods (`ControllerMethod.php`, about lines + 414-440 in 1.9.1). The `anyOf` appears exactly when the controller also + declares that same status in its `@return` for a method that is not + `#[PublicPage]` (401) or not `#[NoAdminRequired]` (403). A scan of + `lib/Controller` finds exactly seven such methods, the same seven operations: + `AccountController::signatureGenerate`, + `AdminController::generateCertificateCfssl` and `generateCertificateOpenSsl`, + `FileController::deleteFile`, `FooterTemplateController::saveFooterTemplate` + (403), `RequestSignatureController::removeSigner` and `deleteSignatureRequest`. + Public methods that declare a 401 (for example `IdDocsController::delete`) + generate a single typed response, and the 82 other 401/403 responses are + implicit-only. The explicit declarations describe what the code returns, so + removing them would only erase the typed body and leave `data: {}`. The + request to the extractor is therefore to give the implicit 401/403 a typed + body (or to let the controller refine it), not to let an explicit declaration + replace the implicit one: the framework still answers 401/403 without a + session, so both bodies are real and `anyOf` is correct. The generator then + produces `data: any`, a faithful reading of `X | {}`. Separately, six of these + methods use 401 for any failure, which is a LibreSign decision (see "Left in + LibreSign"). + +For the object unions, `anyOf` is semantically correct: without +`additionalProperties: false` an object carrying every key of two alternatives +matches both (a detailed file can match both `FileSummary` and `DetailedFile`), +so `oneOf` would be wrong. The defect is the generator's merge (G1), not the +extractor's choice. Evidence: `npm run test:anyof` (`union-defects.ts`) and +`npm run test:normalized`, which renames the 12 keywords in a disposable copy +and passes. + +### E3. `mixed` maps to `{ type: object }` + +`EffectivePolicyValue`'s object branch and `UserConfigValue` are emitted with +`additionalProperties: { type: object }`, `UserConfigValue`'s `list` +becomes `Array`, and `DynamicMetadataValue` (PHP `mixed`) is +`{ type: object }`. Generated types therefore reject scalar-valued entries that +the PHP type allows. This was already noted in #9494 as an open limitation. + +### E4. `nullable` on a composed schema + +`EffectivePolicyValue` is `nullable: true` plus `oneOf`, with no explicit +`null` alternative. The generator applies `| null` at properties that +reference it (`EffectivePolicyState.effectiveValue`) but not at array items +(`allowedValues: Array` and the `values` maps), and OpenAPI 3.0.3 defines +`nullable` only next to `type`. Decide whether the extractor should emit a +construct generators handle consistently. Not tested with another generator. + +### E5. Binary responses are typed `*/*` + +Thumbnails, signature element preview, the CRL and the admin background image +were all generated with the media type `*/*` and `format: binary`, while the PDF +operations use `application/pdf`. The CRL and the background have a fixed type +in the code and now declare it in LibreSign. Thumbnails and the element preview +depend on the previewed file; their `FileDisplayResponse` only states +`Content-Type: string`, so `*/*` remains. The extractor already accepts literal +`Content-Type` values (`ResponseType.php`, 1.9.1), so nothing is missing there: +the media type set of a previewed file is not closed, which is why LibreSign +keeps `string`. + +### E6. Every OCS operation repeats the header parameter + +`OCS-APIRequest` is a required header parameter with `default: true` on the +87 OCS operations (the 3 non-OCS ones have none). Generated clients make it +a required field of every request object (positional in the lower-level +functions). Consider whether the extractor can mark OCS operations through a +reusable component or security-like default so SDK generators can inject it +once. + +## OpenAPI Generator (`typescript-axios` 7.27.0) + +### G1. `anyOf` of objects becomes one merged interface + +The generated interface merges both alternatives and keeps required fields from +one of them: `FileListResponseDataInner` requires `files`, `size` and +`visibleElements` and narrows `nodeId` to `number`; `FileRuntimeMetadata` loses +its dynamic branch; the `RequestPolicyOverridesValue` union becomes an empty +interface; the two notify 422 bodies such as `NotifySigners422ResponseOcsData` require +`action` and `errors`, and the seven envelope `anyOf` bodies become `data: any`. Upstream status: `OpenAPITools/openapi-generator#8894` +("`anyOf` creates same interface as `allOf`", reported against 5.0.1) is open +and matches the merged-interface cases (`FileListResponseDataInner` and the two +notify 422 bodies). It does not describe the lost dynamic branch of +`FileRuntimeMetadata`, the empty `RequestPolicyOverridesValue` or the seven +envelope cases, where the generator keeps `data: any`; those may need their own +reports. The fix was not tracked here. The earlier evaluation recorded the former `EffectivePolicyValue` defect, a different `anyOf` case, in both 7.15.0 and 7.27.0; the object cases above were checked only with 7.27.0. +A union of two arrays (`list|list` as `anyOf`) becomes an empty interface +(tested on a disposable spec copy). `oneOf` produces correct unions, so the choice is: fix the generator, add a +reviewed normalization step to the future SDK Generator, or pick another +generator. + +### G2. Error responses are not part of method return types + +Models for 4xx/5xx bodies exist, but method return types only describe the +success response. The SDK layer must expose typed access to +`error.response.data` itself (for example through a wrapper or documented type +guards). Do not assume this is unwrapped or typed automatically. The success +types can also carry misleading names: `notifySigners` returns +`AxiosPromise`, a model deduplicated +from a 401 body that shares the 200 `MessageResponse` shape. If this matters for +the public SDK surface, it needs naming control (for example +`inlineSchemaNameMapping`), which was not tested. + +### G3. The schema named `File` is renamed but its references become `any` + +`File` is renamed to `ModelFile` because it matches a global TypeScript type +(generator warning, repeated per usage), but the references to it are not +updated: `IdDocsListResponse.data` and `IdDocsApprovalListResponse.data` are +generated as `Array`, the only unbounded `any` in the model section. On a +disposable copy of the spec with the schema renamed to `IdDocFile` both become +`Array` and no `Array` remains, so the defect is the +generator's handling of reserved model names. LibreSign renamed its schema to +`IdDocFile` (decided by the maintainer, because the name was also too generic), +which removes the `any` from its contract; `anyof-defect.ts` guards it. The +generator defect itself is not fixed. + +Binary responses are typed as the DOM `File`, while transport with +`responseType: arraybuffer` yields bytes, so callers must reconcile types. To +evaluate in the generator configuration: `typeMappings` (for example +`file=Blob` or `ArrayBuffer`) and `modelNameMappings`. Neither was tested. + +### G4. Ergonomics + +- Header parameter name is `oCSAPIRequest`; `parameterNameMappings` may allow a + readable name (untested). +- Generated Markdown examples use positional arguments although + `useSingleRequestParameter=true` is set; real signatures take one object. +- The OCS envelope is not unwrapped: callers read `response.data.ocs.data`. +- `BASE_PATH` defaults to `http://localhost` and LibreSign's paths mix + `/ocs/v2.php/...` and `/index.php/...`; subdirectory installs work only + because callers pass the full base URL (tested), not through `servers`. + +### G5. Multipart serialization is unverified + +Because the contract has no multipart bodies (E1), serialization of single and +repeated file parts by `typescript-axios` (FormData in browsers and Node, +`files[]` naming, `expectedFilesCount`) could not be tested. Add these checks +to the harness once E1 is available and record any generator limitation +separately. + +## Left in LibreSign + +Rule for this work: packages (`vendor/`, `vendor-bin/`, the generator) are not +patched locally and no local extractor workaround is added; defects above are +reported upstream. Anything whose cause is in LibreSign's own code is adjusted +in LibreSign. Candidates, each needing its cause confirmed first: + +- the 7 error bodies with an untyped `data: {}` (E2): investigated; the + controllers' explicit 401/403 declarations describe what the code returns, so + the untyped body is the extractor's and needs no LibreSign change; +- the error bodies that did not match the code (done): `request-signature` + POST/PATCH now document only `MessageResponse` for 422 (two `anyOf` fewer), + `removeSigner` documents `MessageResponse` for 422, `deleteFile` and + `deleteSignatureRequest` no longer document a 422 they never return, and + `DetailedFile.nodeId` is nullable like the database column. Guarded by + `tests/php/openapi/OpenApiErrorBodyContractTest.php`; +- **open maintainer decision**: six methods return HTTP 401 for any failure + (`AccountController::signatureGenerate`, the `AdminController` certificate + generators, `FileController::deleteFile`, + `RequestSignatureController::deleteSignatureRequest` and `removeSigner`). + Moving business failures to 422/400 is a compatibility-breaking change that + needs its own change and Behat updates; not done here; +- `DetailedFile.policySnapshotFrozen` is required but only set when a user is + present (`FileListService.php:273-275`); not changed because it was not shown + that the OCS responses typed `DetailedFile` can lack a user; +- the three `anyOf` schemas in `lib/ResponseDefinitions.php` (E2/G1): + investigated, no change recommended. `FileSummary|DetailedFile` is a + per-item approximation, because `FileListService.php:99-103` makes the + `details` flag switch the whole list; the more faithful + `list|list` is still an `anyOf`, and on a + disposable copy of the spec `typescript-axios` turned it into an empty + interface (`FileListResponseData`), which is worse. `FileRuntimeMetadata` + (`ValidateMetadata|array`) and `RequestPolicyOverrides` + (`value|list`) are deliberate unions that the runtime treats as + `array`; no evidence was found that they are wrong. So the + defects are the generator's (G1) and the extractor's `mixed` mapping (E3); +- the schema `File` name (G3): done. `LibresignFile` became `LibresignIdDocFile` + (`lib/ResponseDefinitions.php`, imports in `FileController`, + `IdDocsController` and `AccountController`), the frontend alias in + `src/views/Documents/IdDocsValidation.vue` and its spec follow, the three + contracts and the TypeScript types were regenerated, and + `tests/php/openapi/OpenApiIdDocSchemaTest.php` guards the name; +- the `*/*` media types (E5): done where the type is fixed in the code. The CRL + now declares `application/pkix-crl` (`CrlController.php`) and the admin + background `image/png` (`AdminController.php`), with + `tests/php/openapi/OpenApiBinaryMediaTypesTest.php`. Thumbnails and the + signature element preview keep `*/*` because their media type depends on the + previewed file (`Content-Type: string` is accurate). +- **Go/No-Go**: see the handoff in [REPORT.md](REPORT.md). It must be re-run + after the toolchain or contract changes. +- **Not verified**: a real browser with the real XHR adapter and a real + Nextcloud server; state-changing signature requests; runtime JSON + validation against the contract. diff --git a/tests/sdk-generation/anyof-defect.ts b/tests/sdk-generation/anyof-defect.ts index e23577beb6..50563a4d23 100644 --- a/tests/sdk-generation/anyof-defect.ts +++ b/tests/sdk-generation/anyof-defect.ts @@ -2,8 +2,21 @@ * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors * SPDX-License-Identifier: AGPL-3.0-or-later */ -import type { EffectivePolicyValue } from '../../build/sdk-generation/typescript/api' -// This defect-reproduction check passes only while invalid arrays are accepted. -// Missing generated output or a corrected union must fail compilation. -const accepted: EffectivePolicyValue = ['not a policy value'] -void accepted +import type { EffectivePolicyValue, EffectivePolicyState, IdDocFile, IdDocsListResponse } from '../../build/sdk-generation/typescript/api' +// Regression guard for the former EffectivePolicyValue defect (empty generated +// interface accepting arrays). Fixed by the disjoint oneOf contract; each +// ts-expect-error below fails compilation if the generated type widens again. +const accepted: EffectivePolicyValue[] = [true, 42, 1.5, 'value', { nested: {} }] +// @ts-expect-error arrays are not policy values +const invalidArray: EffectivePolicyValue = ['not a policy value'] +// @ts-expect-error undefined is not a policy value +const invalidUndefined: EffectivePolicyValue = undefined +// The nullable flag is applied where the schema is referenced as a property. +const nullableProperty: Pick = { effectiveValue: null } +// The ID document record schema was named File, which made the generator emit +// Array for both ID document lists. It is now IdDocFile and must stay typed. +declare const idDocs: IdDocsListResponse +const idDoc: IdDocFile = idDocs.data[0] +// @ts-expect-error a number is not an ID document record +const invalidIdDoc: IdDocsListResponse['data'][number] = 42 +void [accepted, invalidArray, invalidUndefined, nullableProperty, idDoc, invalidIdDoc] diff --git a/tests/sdk-generation/nextcloud-axios.test.ts b/tests/sdk-generation/nextcloud-axios.test.ts new file mode 100644 index 0000000000..974dac9b23 --- /dev/null +++ b/tests/sdk-generation/nextcloud-axios.test.ts @@ -0,0 +1,60 @@ +/* + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +// Injects the real, locked @nextcloud/axios instance into a generated client. +// The package needs browser globals, so a jsdom window is installed first. +// Only the network adapter is replaced; the package's own defaults and its CSRF +// interceptor run unmodified. No real Nextcloud server is contacted. +import * as assert from 'node:assert/strict' +import { test } from 'node:test' +import { AxiosError, type AxiosAdapter, type InternalAxiosRequestConfig } from 'axios' +import { JSDOM } from 'jsdom' +import { IdentityApi } from '../../build/sdk-generation/typescript/api' +import { Configuration } from '../../build/sdk-generation/typescript/configuration' + +const dom = new JSDOM('', { url: 'https://example.test/nextcloud/' }) +Object.assign(globalThis, { window: dom.window, document: dom.window.document, location: dom.window.location, localStorage: dom.window.localStorage, sessionStorage: dom.window.sessionStorage }) + +const okBody = { ocs: { meta: { status: 'ok', statuscode: 200 }, data: { account: { uid: 'test', emailAddress: 'test@example.test', displayName: 'Test' }, settings: { canRequestSign: true, hasSignatureFile: false, phoneNumber: '' } } } } + +test('generated client works with the real @nextcloud/axios instance and its CSRF retry', async () => { + const { default: nextcloudAxios } = await import('@nextcloud/axios') + const seen: InternalAxiosRequestConfig[] = [] + let calls = 0 + const adapter: AxiosAdapter = async config => { + seen.push(config) + calls++ + const reply = (status: number, data: unknown) => { + const response = { data, status, statusText: String(status), headers: {}, config } + if (config.validateStatus && !config.validateStatus(status)) { + throw new AxiosError('HTTP error', 'ERR_BAD_REQUEST', config, undefined, response) + } + return response + } + // First account request: simulate a stale token, as Nextcloud does. + return calls === 1 ? reply(412, { message: 'CSRF check failed' }) : reply(200, okBody) + } + // fetchRequestToken() uses the global fetch(), not Axios. + const fetched: string[] = [] + globalThis.fetch = (async (input: RequestInfo | URL) => { + fetched.push(String(input)) + return new Response(JSON.stringify({ token: 'refreshed-token' }), { status: 200, headers: { 'Content-Type': 'application/json' } }) + }) as typeof fetch + nextcloudAxios.defaults.adapter = adapter + + const api = new IdentityApi(new Configuration({ basePath: 'https://example.test/nextcloud' }), undefined, nextcloudAxios) + const account = await api.accountMe({ apiVersion: 'v1', oCSAPIRequest: true }) + + const first = seen[0] + assert.equal(first.url, 'https://example.test/nextcloud/ocs/v2.php/apps/libresign/api/v1/account/me') + assert.equal(first.headers.get('OCS-APIRequest'), 'true') + assert.equal(first.headers.get('requesttoken'), 'initial-token') + assert.equal(first.headers.get('X-Requested-With'), 'XMLHttpRequest') + const retry = seen[seen.length - 1] + assert.equal(retry.url, first.url) + assert.equal(retry.headers.get('requesttoken'), 'refreshed-token') + assert.equal(retry.headers.get('OCS-APIRequest'), 'true') + assert.deepEqual(fetched, ['/nextcloud/index.php/csrftoken']) + assert.equal(account.data.ocs.data.account.uid, 'test') +}) diff --git a/tests/sdk-generation/package-lock.json b/tests/sdk-generation/package-lock.json index b033d640d8..8845e2fba4 100644 --- a/tests/sdk-generation/package-lock.json +++ b/tests/sdk-generation/package-lock.json @@ -13,11 +13,142 @@ "axios": "1.20.0" }, "devDependencies": { + "@types/jsdom": "21.1.7", "@types/node": "22.15.21", + "jsdom": "26.1.0", "tsx": "4.19.4", "typescript": "5.8.3" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", @@ -542,6 +673,18 @@ "@types/sizzle": "*" } }, + "node_modules/@types/jsdom": { + "version": "21.1.7", + "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-21.1.7.tgz", + "integrity": "sha512-yOriVnggzrnQ3a9OKOCxaVuSug3w3/SbOj5i7VwXWZEyUNl3bLF9V3MfxGbZKuwqJOQyRfqXyROBB1CoZLFWzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/tough-cookie": "*", + "parse5": "^7.0.0" + } + }, "node_modules/@types/node": { "version": "22.15.21", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.21.tgz", @@ -564,6 +707,13 @@ "integrity": "sha512-TC0dmN0K8YcWEAEfiPi5gJP14eJe30TTGjkvek3iM/1NdHHsdCA/Td6GvNndMOo/iSnIsZ4HuuhrYPDAmbxzww==", "license": "MIT" }, + "node_modules/@types/tough-cookie": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz", + "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", + "dev": true, + "license": "MIT" + }, "node_modules/agent-base": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", @@ -619,6 +769,34 @@ "node": ">= 0.8" } }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -636,6 +814,13 @@ } } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -659,6 +844,19 @@ "node": ">= 0.4" } }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -907,6 +1105,43 @@ "node": ">= 0.4" } }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/http-proxy-agent/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "node_modules/https-proxy-agent": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", @@ -920,6 +1155,97 @@ "node": ">= 6" } }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/jsdom/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -956,6 +1282,26 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/nwsapi": { + "version": "2.2.28", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz", + "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", + "dev": true, + "license": "MIT" + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/proxy-from-env": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", @@ -965,6 +1311,16 @@ "node": ">=10" } }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/resolve-pkg-maps": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", @@ -975,6 +1331,33 @@ "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" } }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/semver": { "version": "7.8.6", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", @@ -987,6 +1370,59 @@ "node": ">=10" } }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/tsx": { "version": "4.19.4", "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.19.4.tgz", @@ -1027,6 +1463,106 @@ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "dev": true, "license": "MIT" + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" } } } diff --git a/tests/sdk-generation/package.json b/tests/sdk-generation/package.json index f28958bec6..b877d2cd2e 100644 --- a/tests/sdk-generation/package.json +++ b/tests/sdk-generation/package.json @@ -4,9 +4,9 @@ "private": true, "license": "AGPL-3.0-or-later", "scripts": { - "compile": "tsc --noEmit --strict --skipLibCheck --target ES2020 --module commonjs --moduleResolution node ../../build/sdk-generation/typescript/*.ts types.ts signing-contracts.ts transport.ts live.ts live.test.ts", - "test": "tsx transport.ts && node inventory.cjs && tsx --test live.test.ts && node --test generate.test.cjs", - "test:anyof": "tsc --noEmit --strict --skipLibCheck --target ES2020 --module commonjs --moduleResolution node anyof-defect.ts", + "compile": "tsc --noEmit --strict --skipLibCheck --target ES2020 --module commonjs --moduleResolution node ../../build/sdk-generation/typescript/*.ts types.ts signing-contracts.ts transport.ts live.ts live.test.ts nextcloud-axios.test.ts", + "test": "tsx transport.ts && node inventory.cjs && tsx --test live.test.ts && node --test generate.test.cjs && tsx --test nextcloud-axios.test.ts", + "test:anyof": "tsc --noEmit --strict --skipLibCheck --target ES2020 --module commonjs --moduleResolution node anyof-defect.ts union-defects.ts", "test:live": "tsx live.ts", "test:nextcloud": "node nextcloud-import.mjs", "test:normalized": "tsc --noEmit --strict --skipLibCheck --target ES2020 --module commonjs --moduleResolution node ../../build/sdk-generation/normalized/typescript/*.ts normalized-types.ts" @@ -16,7 +16,9 @@ "axios": "1.20.0" }, "devDependencies": { + "@types/jsdom": "21.1.7", "@types/node": "22.15.21", + "jsdom": "26.1.0", "tsx": "4.19.4", "typescript": "5.8.3" } diff --git a/tests/sdk-generation/types.ts b/tests/sdk-generation/types.ts index c6904e3ad8..024d3e6321 100644 --- a/tests/sdk-generation/types.ts +++ b/tests/sdk-generation/types.ts @@ -15,9 +15,9 @@ const signer: SignerDetail = { } // @ts-expect-error allOf requires inherited fields const badSigner: SignerDetail = { me: true, visibleElements: [] } -const request: RequestSignatureRequestSignatureRequest = { callback: null } -// @ts-expect-error callback must be a string or null -const badRequest: RequestSignatureRequestSignatureRequest = { callback: 2 } +const request: RequestSignatureRequestSignatureRequest = { status: null } +// @ts-expect-error status must be a number or null +const badRequest: RequestSignatureRequestSignatureRequest = { status: 'pending' } // @ts-expect-error status is a finite numeric enum const badStatus: SignerDetail['status'] = 99 function account(response: AccountMe200Response): string { return response.ocs.data.account.uid } diff --git a/tests/sdk-generation/union-defects.ts b/tests/sdk-generation/union-defects.ts new file mode 100644 index 0000000000..f510cfc98b --- /dev/null +++ b/tests/sdk-generation/union-defects.ts @@ -0,0 +1,24 @@ +/* + * SPDX-FileCopyrightText: 2026 LibreCode coop and contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +import type { FileListResponseDataInner, FileRuntimeMetadata, FileSummary, RequestPolicyOverridesValue } from '../../build/sdk-generation/typescript/api' +// Reproductions of defects that remain in the generated output for the +// object-valued anyOf constructs. The file compiles only while the defects +// exist: a @ts-expect-error marks a contract-valid value that the generated +// type rejects (it fails with TS2578 once fixed), and a plain assignment marks +// a contract-invalid value that the generated type accepts (it fails with +// TS2322 once fixed). When either happens, reevaluate the handoff in +// REPORT.md and UPSTREAM-NOTES.md and invert the assertion. +declare const summary: FileSummary +// anyOf of FileSummary|DetailedFile is merged into one interface whose +// required fields come from DetailedFile (files, size, visibleElements). +// @ts-expect-error a valid FileSummary is not assignable to the generated item type +const item: FileListResponseDataInner = summary +// anyOf of ValidateMetadata|{[k]: DynamicMetadataValue}: the dynamic branch is lost. +// @ts-expect-error a dynamic metadata object without extension/p is valid by contract +const metadata: FileRuntimeMetadata = { custom: {} } +// anyOf of EffectivePolicyValue|array becomes an empty interface. A triple-nested +// array is invalid by contract (only a flat array of policy values is allowed) but is accepted. +const overrideAcceptsAnything: RequestPolicyOverridesValue = [[[1]]] +void [item, metadata, overrideAcceptsAnything] From d7fec079089dc5529e9e0a48af4e215ac850b205 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 10:30:14 -0300 Subject: [PATCH 03/14] fix(openapi): keep the 422 bodies sent by the permission middleware A previous commit on this branch narrowed the 422 of request-signature (POST, PATCH), removeSigner, deleteFile and deleteSignatureRequest to a `{message}` body or removed it. That was wrong: #[RequireManager] runs canRequestSign() before the controller and its try block, so a user without permission still receives 422 with an `{action, errors}` body. Restore the original `ActionErrorResponse` documentation for those operations and document removeSigner as `MessageResponse|ActionErrorResponse`, because its catch block answers `{message}` with 422 when the exception code is 422. `DetailedFile.nodeId` stays nullable. Specs and TypeScript types are regenerated, not hand-edited. The contract test now asserts both bodies instead of the narrowed contract. Signed-off-by: Luis Amorim --- lib/Controller/FileController.php | 3 +- lib/Controller/RequestSignatureController.php | 14 +-- openapi-full.json | 91 ++++++++++++++++++- openapi.json | 91 ++++++++++++++++++- src/types/openapi/openapi-full.ts | 38 +++++++- src/types/openapi/openapi.ts | 38 +++++++- .../openapi/OpenApiErrorBodyContractTest.php | 58 +++++++----- 7 files changed, 285 insertions(+), 48 deletions(-) diff --git a/lib/Controller/FileController.php b/lib/Controller/FileController.php index 3dbc716e02..27a26695b4 100644 --- a/lib/Controller/FileController.php +++ b/lib/Controller/FileController.php @@ -887,10 +887,11 @@ private function extractFileName(array $fileData): string { * * @param integer $fileId LibreSign file ID * @param boolean $deleteFile Whether to delete the physical file from Nextcloud (default: true) - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse|DataResponse * * 200: OK * 401: Failed + * 422: Failed */ #[NoAdminRequired] #[NoCSRFRequired] diff --git a/lib/Controller/RequestSignatureController.php b/lib/Controller/RequestSignatureController.php index 320bb2a04b..f1316e1665 100644 --- a/lib/Controller/RequestSignatureController.php +++ b/lib/Controller/RequestSignatureController.php @@ -31,6 +31,7 @@ * @psalm-import-type LibresignNewSigner from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignDetailedFile from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignDetailedFileResponse from \OCA\Libresign\ResponseDefinitions + * @psalm-import-type LibresignActionErrorResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignMessageResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignFolderSettings from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignSettings from \OCA\Libresign\ResponseDefinitions @@ -66,10 +67,10 @@ public function __construct( * @param list $files Multiple files to create an envelope (optional, use either file or files). Each file supports nodeId, url, base64 or path. * @param integer|null $status Numeric code of status * 0 - no signers * 1 - signed * 2 - pending * @param LibresignRequestPolicy|null $policy Structured policy payload with request-level overrides and active context. - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: OK - * 422: Request cannot be processed + * 422: Unauthorized */ #[NoAdminRequired] #[NoCSRFRequired] @@ -137,10 +138,10 @@ public function requestSignature( * @param string|null $name The name of file to sign * @param LibresignFolderSettings $settings Settings to define how and where the file should be stored * @param list $files Multiple files to create an envelope (optional, use either file or files). Each file supports nodeId, url, base64 or path. - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: OK - * 422: Request cannot be processed + * 422: Unauthorized */ #[NoAdminRequired] #[NoCSRFRequired] @@ -211,7 +212,7 @@ public function updateSignatureRequest( * * @param integer $fileId LibreSign file ID * @param integer $signRequestId The sign request id - * @return DataResponse|DataResponse|DataResponse + * @return DataResponse|DataResponse|DataResponse * * 200: OK * 401: Failed @@ -257,10 +258,11 @@ public function removeSigner(int $fileId, int $signRequestId): DataResponse { * You can only request exclusion as any sign * * @param integer $fileId LibreSign file ID - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse|DataResponse * * 200: OK * 401: Failed + * 422: Failed */ #[NoAdminRequired] #[NoCSRFRequired] diff --git a/openapi-full.json b/openapi-full.json index eb2e759c59..3544b68f89 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -7267,6 +7267,36 @@ } } } + }, + "422": { + "description": "Failed", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/ActionErrorResponse" + } + } + } + } + } + } + } } } } @@ -12325,7 +12355,7 @@ } }, "422": { - "description": "Request cannot be processed", + "description": "Unauthorized", "content": { "application/json": { "schema": { @@ -12345,7 +12375,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -12537,7 +12574,7 @@ } }, "422": { - "description": "Request cannot be processed", + "description": "Unauthorized", "content": { "application/json": { "schema": { @@ -12557,7 +12594,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -12764,7 +12808,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -12911,6 +12962,36 @@ } } } + }, + "422": { + "description": "Failed", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/ActionErrorResponse" + } + } + } + } + } + } + } } } }, diff --git a/openapi.json b/openapi.json index 47c46370de..c07af04e03 100644 --- a/openapi.json +++ b/openapi.json @@ -6725,6 +6725,36 @@ } } } + }, + "422": { + "description": "Failed", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/ActionErrorResponse" + } + } + } + } + } + } + } } } } @@ -11588,7 +11618,7 @@ } }, "422": { - "description": "Request cannot be processed", + "description": "Unauthorized", "content": { "application/json": { "schema": { @@ -11608,7 +11638,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -11800,7 +11837,7 @@ } }, "422": { - "description": "Request cannot be processed", + "description": "Unauthorized", "content": { "application/json": { "schema": { @@ -11820,7 +11857,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -12027,7 +12071,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -12174,6 +12225,36 @@ } } } + }, + "422": { + "description": "Failed", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/ActionErrorResponse" + } + } + } + } + } + } + } } } }, diff --git a/src/types/openapi/openapi-full.ts b/src/types/openapi/openapi-full.ts index 1b7580b296..4b54580695 100644 --- a/src/types/openapi/openapi-full.ts +++ b/src/types/openapi/openapi-full.ts @@ -3815,6 +3815,20 @@ export interface operations { }; }; }; + /** @description Failed */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; }; }; "file_element-create-visible-element": { @@ -6015,7 +6029,7 @@ export interface operations { }; }; }; - /** @description Request cannot be processed */ + /** @description Unauthorized */ 422: { headers: { [name: string]: unknown; @@ -6024,7 +6038,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -6124,7 +6138,7 @@ export interface operations { }; }; }; - /** @description Request cannot be processed */ + /** @description Unauthorized */ 422: { headers: { [name: string]: unknown; @@ -6133,7 +6147,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -6200,7 +6214,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -6334,6 +6348,20 @@ export interface operations { }; }; }; + /** @description Failed */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; }; }; "sign_file-sign-by-signer-uuid": { diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index a6f4a0019d..cdde286544 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -3347,6 +3347,20 @@ export interface operations { }; }; }; + /** @description Failed */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; }; }; "file_element-create-visible-element": { @@ -5453,7 +5467,7 @@ export interface operations { }; }; }; - /** @description Request cannot be processed */ + /** @description Unauthorized */ 422: { headers: { [name: string]: unknown; @@ -5462,7 +5476,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -5562,7 +5576,7 @@ export interface operations { }; }; }; - /** @description Request cannot be processed */ + /** @description Unauthorized */ 422: { headers: { [name: string]: unknown; @@ -5571,7 +5585,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -5638,7 +5652,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -5772,6 +5786,20 @@ export interface operations { }; }; }; + /** @description Failed */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; }; }; "sign_file-sign-by-signer-uuid": { diff --git a/tests/php/openapi/OpenApiErrorBodyContractTest.php b/tests/php/openapi/OpenApiErrorBodyContractTest.php index 7ffade06e7..2c49a8d54e 100644 --- a/tests/php/openapi/OpenApiErrorBodyContractTest.php +++ b/tests/php/openapi/OpenApiErrorBodyContractTest.php @@ -13,11 +13,18 @@ use PHPUnit\Framework\TestCase; /** - * The documented error bodies must match what the controllers return, so that - * generated clients do not type a body that is never sent. + * The documented 422 bodies must match what the API really sends. + * + * Two sources exist. The #[RequireManager] middleware calls canRequestSign() + * before the controller runs and, for a user without permission, answers 422 + * with an {action, errors} body (ActionErrorResponse). The controller catch + * blocks answer {message} (MessageResponse). Documenting only one of them + * would type a body that is not the only one sent. */ final class OpenApiErrorBodyContractTest extends TestCase { private const BASE = '/ocs/v2.php/apps/libresign/api/{apiVersion}/'; + private const MESSAGE = '#/components/schemas/MessageResponse'; + private const ACTION_ERROR = '#/components/schemas/ActionErrorResponse'; public static function specificationProvider(): array { return [ @@ -27,46 +34,45 @@ public static function specificationProvider(): array { } #[DataProvider('specificationProvider')] - public function testRequestSignatureOnlyReturnsAMessageWith422(string $file): void { + public function testRequestSignatureDocumentsBothBodiesAt422(string $file): void { $paths = $this->load($file)['paths']; foreach (['post', 'patch'] as $method) { - self::assertSame( - '#/components/schemas/MessageResponse', - $this->errorData($paths[self::BASE . 'request-signature'][$method], '422')['$ref'] ?? null, - $method, - ); + $this->assertBothBodies($paths[self::BASE . 'request-signature'][$method], $method); } } #[DataProvider('specificationProvider')] - public function testRemoveSignerDocumentsTheMessageItReturns(string $file): void { - $operation = $this->load($file)['paths'][self::BASE . 'sign/file_id/{fileId}/{signRequestId}']['delete']; - - self::assertSame('#/components/schemas/MessageResponse', $this->errorData($operation, '422')['$ref'] ?? null); + public function testRemoveSignerDocumentsBothBodiesAt422(string $file): void { + // The catch block answers {message} with 422 when the exception code is 422. + $this->assertBothBodies( + $this->load($file)['paths'][self::BASE . 'sign/file_id/{fileId}/{signRequestId}']['delete'], + 'removeSigner', + ); } #[DataProvider('specificationProvider')] - public function testDeleteOperationsDoNotDocumentAnUnreachable422(string $file): void { + public function testDeleteOperationsDocumentTheMiddleware422(string $file): void { + // Their catch blocks answer 401, but the middleware rejects a user + // without permission with 422 before the method runs. $paths = $this->load($file)['paths']; foreach (['file/file_id/{fileId}', 'sign/file_id/{fileId}'] as $path) { - self::assertArrayNotHasKey('422', $paths[self::BASE . $path]['delete']['responses'], $path); + self::assertSame( + self::ACTION_ERROR, + $this->errorData($paths[self::BASE . $path]['delete'], '422')['$ref'] ?? null, + $path, + ); } } #[DataProvider('specificationProvider')] public function testNotifyKeepsBothRealBodiesAt422(string $file): void { - // canRequestSign() throws an action/errors body, other validations a message. + // canRequestSign() throws an action/errors body, other validations a message body. $paths = $this->load($file)['paths']; foreach (['notify/signers', 'notify/signer'] as $path) { - $data = $this->errorData($paths[self::BASE . $path]['post'], '422'); - self::assertEqualsCanonicalizing( - ['#/components/schemas/MessageResponse', '#/components/schemas/ActionErrorResponse'], - array_column($data['anyOf'] ?? [], '$ref'), - $path, - ); + $this->assertBothBodies($paths[self::BASE . $path]['post'], $path); } } @@ -78,6 +84,16 @@ public function testDetailedFileNodeIdIsNullable(string $file): void { self::assertTrue($nodeId['nullable'] ?? false); } + private function assertBothBodies(array $operation, string $label): void { + $data = $this->errorData($operation, '422'); + + self::assertEqualsCanonicalizing( + [self::MESSAGE, self::ACTION_ERROR], + array_column($data['anyOf'] ?? [], '$ref'), + $label, + ); + } + private function errorData(array $operation, string $status): array { return $operation['responses'][$status]['content']['application/json']['schema']['properties']['ocs']['properties']['data'] ?? []; } From 9f039fcff457e0cbe1db6aae98b9eb9bb777b387 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 10:30:14 -0300 Subject: [PATCH 04/14] docs(sdk): correct the 422 and 401 findings of the evaluation Rewrite the sections that claimed the 422 of the guarded operations was unreachable and that RequireManager answers 401: the middleware answers 422 with an `{action, errors}` body. Update the anyOf count (15), the SHA-256 of openapi-full.json, the methods that answer 401 for caught failures, the note on policySnapshotFrozen, and the TS2578/TS2322 description in the README. Signed-off-by: Luis Amorim --- tests/sdk-generation/README.md | 10 ++-- tests/sdk-generation/REPORT.md | 66 +++++++++++++------------ tests/sdk-generation/UPSTREAM-NOTES.md | 68 +++++++++++++++----------- 3 files changed, 80 insertions(+), 64 deletions(-) diff --git a/tests/sdk-generation/README.md b/tests/sdk-generation/README.md index 4d9bbe33f9..400865a195 100644 --- a/tests/sdk-generation/README.md +++ b/tests/sdk-generation/README.md @@ -20,9 +20,11 @@ npm run test:anyof --prefix tests/sdk-generation `test:anyof` has two parts. `anyof-defect.ts` is a regression guard: the generated `EffectivePolicyValue` must keep rejecting arrays and `undefined`. `union-defects.ts` -**passes while known defects exist**: each `@ts-expect-error` marks a valid contract -value that the generated model rejects or over-accepts. When a defect is fixed, -compilation fails with TS2578 and the report must be reevaluated. `npm test` checks +**passes while known defects exist**: a `@ts-expect-error` marks a valid contract +value that the generated model rejects, and a plain assignment marks an invalid +value that it accepts. When a defect is fixed, compilation fails: TS2578 for an +unused `@ts-expect-error`, TS2322 for an assignment that is now rejected. The +report must then be reevaluated. `npm test` checks transport, generation cleanup, live-check error handling and real `@nextcloud/axios` injection under jsdom, and writes the generated operation inventory to `build/sdk-generation/inventory.md`. @@ -40,7 +42,7 @@ See [REPORT.md](REPORT.md) and [inventory.md](inventory.md) for results. ## Normalized-input experiment -This separate experiment changes all 12 `anyOf` keywords to `oneOf` in a +This separate experiment changes all 15 `anyOf` keywords to `oneOf` in a **disposable generator input**, never in the committed specification: ```sh diff --git a/tests/sdk-generation/REPORT.md b/tests/sdk-generation/REPORT.md index be2d82a196..92d731ece1 100644 --- a/tests/sdk-generation/REPORT.md +++ b/tests/sdk-generation/REPORT.md @@ -15,7 +15,7 @@ keeps `| null` at the properties that reference it (disjoint `oneOf` contract, `@nextcloud/axios` injection all pass. The decision remains No-Go for unmodified input because three generated models -(and the 9 error-body models) of the remaining 12 `anyOf` constructs are still +(and the 12 error-body models) of the remaining 15 `anyOf` constructs are still incorrect (see [Remaining model defects](#remaining-model-defects)), and multipart bodies are still absent from the contract. Every blocker left is on the @@ -29,9 +29,9 @@ frontend type, CI job or permanent SDK. - Application base: `40ee2280737e54ebf798bbc1f77bf4272cbe9320` (`main`), plus three LibreSign changes described below: the ID document schema `File` renamed to `IdDocFile`, literal media types for the CRL and the admin background, and - error-body annotations aligned with what the controllers return (see - [Error bodies aligned with the code](#error-bodies-aligned-with-the-code)). -- `openapi-full.json` SHA-256 with those changes: `76b093d3325b9504ba7911ba487b9424d7e9821bd2f2f9905d01756371ba8bf9` + annotations aligned with what the code returns (see + [Annotations aligned with the code](#annotations-aligned-with-the-code)). +- `openapi-full.json` SHA-256 with those changes: `36635e033a52861d1bb5e0281bb759a7fdf4e05d097d9fd6610e2a29577ab6fa` (`64c52fa2ba243af292eba30055982954bfd8c19136567e50e28c4abcffcc9405` on `main`). - Extractor used to produce the contract: `nextcloud/openapi-extractor` 1.9.1. - Generator: `openapitools/openapi-generator-cli` 7.27.0 at @@ -103,10 +103,12 @@ soon as one of them fails (TS2578 or TS2322): | `FileRuntimeMetadata` | `anyOf` `ValidateMetadata`, `{ [key]: DynamicMetadataValue }` | only the `ValidateMetadata` fields, with `extension` and `p` required | a valid dynamic metadata object is rejected | | `RequestPolicyOverrides` values | `anyOf` `EffectivePolicyValue`, array of it | empty interface `RequestPolicyOverridesValue` | accepts any non-null value | -The other 9 `anyOf` occurrences are in 4xx bodies. Two (the 422 responses of -`notify-signers` and `notify-signer`) are real unions: `canRequestSign()` throws -an `{action, errors}` body (`ActionErrorResponse`), other validations a -`{message}` body (`MessageResponse`), both surfaced by the middleware. The +The other 12 `anyOf` occurrences are in 4xx bodies. Five (the 422 responses of +`notify-signers`, `notify-signer`, `request-signature`, +`update-signature-request` and `removeSigner`) are real unions. A user without +permission is rejected by the `RequireManager`/`canRequestSign()` middleware +with an `{action, errors}` body (`ActionErrorResponse`) before the controller +runs; failures inside the method answer `{message}` (`MessageResponse`). The generator merges them into one interface (for example `NotifySigners422ResponseOcsData` requires `action` and `errors`, which the `MessageResponse` alternative does not have). The other seven (six 401 bodies @@ -139,38 +141,40 @@ request object on all 87 OCS operations (positional only in the lower-level generated functions and Markdown examples; the 3 non-OCS operations have none); envelopes are not unwrapped. -### Error bodies aligned with the code +### Annotations aligned with the code -Two groups of documented error bodies did not match what the controllers send. -They were LibreSign annotations, not package defects, and were corrected: +Two LibreSign annotations did not match the data and were corrected: -- `request-signature` (POST) and `update-signature-request` (PATCH) catch every - failure and return `{message}` with 422, but documented - `MessageResponse | ActionErrorResponse` and the description "Unauthorized". - They now document `MessageResponse` and "Request cannot be processed"; two - `anyOf` disappeared (14 became 12). -- `removeSigner` returns `{message}` with 401 or 422 and documented an - `ActionErrorResponse` 422; `deleteFile` and `deleteSignatureRequest` documented - a 422 they never return (the `RequireManager` middleware answers 401). +- `removeSigner` documented only an `ActionErrorResponse` 422, but its `catch` + also answers `{message}` with 422 when the exception code is 422. It now + documents `MessageResponse | ActionErrorResponse`, which adds one `anyOf` + (14 became 15). - `DetailedFile.nodeId` is now nullable: `libresign_file.node_id` is nullable and the entity value is copied as is (`FileSummary` already allowed null). -`tests/php/openapi/OpenApiErrorBodyContractTest.php` guards these shapes and -also records that the two `notify` 422 unions are real. - -Open decision for the maintainers, not changed here: six methods return HTTP -401 for any failure, including validation and business errors -(`AccountController::signatureGenerate`, the two certificate generators, -`deleteFile`, `deleteSignatureRequest`, `removeSigner`). A 401 means -"unauthenticated", so an SDK cannot tell an invalid session from a business -failure. Changing the status breaks compatibility and the Behat scenarios, so it -needs its own change. +`tests/php/openapi/OpenApiErrorBodyContractTest.php` guards these and the other +422 unions. A review of this branch caught an earlier mistaken narrowing: the +422 of `request-signature` (POST, PATCH), `removeSigner`, `deleteFile` and +`deleteSignatureRequest` can also be an `{action, errors}` body, because +`#[RequireManager]` runs `canRequestSign()` before the method and its `try` +block (`InjectionMiddleware.php`, `SigningRequestValidator.php`), so the +original `ActionErrorResponse` documentation was kept. + +Open decision for the maintainers, not changed here: several methods answer +HTTP 401 for failures that are not authentication failures. +`signatureGenerate`, the two certificate generators (`catch \Exception`), +`deleteFile` and `deleteSignatureRequest` (`catch \Throwable`) return 401 for +every caught failure, including validation and business errors, and +`removeSigner` returns 401 for any `LibresignException` whose code is not 422. +A 401 means "unauthenticated", so an SDK cannot tell an invalid session from a +business failure. Changing the status breaks compatibility and the Behat +scenarios, so it needs its own change. ## Normalized-input experiment `normalize-input.cjs` writes only `build/sdk-generation/normalized/openapi-full.oneof.json`, renaming the -remaining 12 `anyOf` keywords to `oneOf`. It generates +remaining 15 `anyOf` keywords to `oneOf`. It generates `FileListResponseDataInner = DetailedFile | FileSummary` and `FileRuntimeMetadata = ValidateMetadata | { [key: string]: ... }`, and `test:normalized` passes. It is generator-input normalization only: object @@ -214,7 +218,7 @@ the extractor support above (or another reviewed design) and a regeneration. Maintainers must choose among these options; this evaluation selects none: -1. Conditional Go with a reviewed generator-input normalization of the 12 +1. Conditional Go with a reviewed generator-input normalization of the 15 `anyOf` constructs, documented as non-contractual. 2. Fix the extractor (object unions, duplicated implicit 401/403) and the generator upstream, and adjust LibreSign's own types or annotations where diff --git a/tests/sdk-generation/UPSTREAM-NOTES.md b/tests/sdk-generation/UPSTREAM-NOTES.md index ca6ce16acf..2bc2a07e24 100644 --- a/tests/sdk-generation/UPSTREAM-NOTES.md +++ b/tests/sdk-generation/UPSTREAM-NOTES.md @@ -43,16 +43,16 @@ single and repeated files (not yet testable, see G5). As #9494 showed, the extractor emitted `oneOf` for the policy value once its scalar branches became disjoint. Unions that include objects or arrays (the policy-override one pairs a value with an array of values) are still emitted as `anyOf`, -and OpenAPI Generator mishandles them (G1). Affected schemas, 12 in total: +and OpenAPI Generator mishandles them (G1). Affected schemas, 15 in total: - `FileListResponse.data[]` items: `FileSummary | DetailedFile`; - `FileRuntimeMetadata`: `ValidateMetadata | array`; - `RequestPolicyOverrides` values: `EffectivePolicyValue | list`; -- 2 `422` bodies: `MessageResponse | ActionErrorResponse` (notify-signers and - notify-signer). This union is real: `canRequestSign()` throws an - `{action, errors}` body and other validations a `{message}` body. The same - union on `request-signature` and `update-signature-request` was a wrong - LibreSign annotation and was fixed (see "Left in LibreSign"); +- 5 `422` bodies: `MessageResponse | ActionErrorResponse` (notify-signers, + notify-signer, request-signature, update-signature-request and + `removeSigner`). The union is real: the `RequireManager`/`canRequestSign()` + middleware answers `{action, errors}` before the controller runs, and the + methods answer `{message}` from their own `catch` blocks; - 7 error bodies (six 401 and the footer-template 403): an envelope `anyOf` whose second branch has an untyped `data: {}`. Cause confirmed: for every non-public OCS method the extractor adds an implicit 401 with an untyped @@ -71,18 +71,19 @@ and OpenAPI Generator mishandles them (G1). Affected schemas, 12 in total: removing them would only erase the typed body and leave `data: {}`. The request to the extractor is therefore to give the implicit 401/403 a typed body (or to let the controller refine it), not to let an explicit declaration - replace the implicit one: the framework still answers 401/403 without a - session, so both bodies are real and `anyOf` is correct. The generator then - produces `data: any`, a faithful reading of `X | {}`. Separately, six of these - methods use 401 for any failure, which is a LibreSign decision (see "Left in - LibreSign"). + replace the implicit one: the implicit response models what the framework + sends (not verified here, Nextcloud's security middleware was not read), so + both bodies are plausible and `anyOf` is correct. The generator then produces + `data: any`, a faithful reading of `X | {}`. Separately, several of these + methods use 401 for failures that are not authentication failures, which is a + LibreSign decision (see "Left in LibreSign"). For the object unions, `anyOf` is semantically correct: without `additionalProperties: false` an object carrying every key of two alternatives matches both (a detailed file can match both `FileSummary` and `DetailedFile`), so `oneOf` would be wrong. The defect is the generator's merge (G1), not the extractor's choice. Evidence: `npm run test:anyof` (`union-defects.ts`) and -`npm run test:normalized`, which renames the 12 keywords in a disposable copy +`npm run test:normalized`, which renames the 15 keywords in a disposable copy and passes. ### E3. `mixed` maps to `{ type: object }` @@ -131,11 +132,11 @@ The generated interface merges both alternatives and keeps required fields from one of them: `FileListResponseDataInner` requires `files`, `size` and `visibleElements` and narrows `nodeId` to `number`; `FileRuntimeMetadata` loses its dynamic branch; the `RequestPolicyOverridesValue` union becomes an empty -interface; the two notify 422 bodies such as `NotifySigners422ResponseOcsData` require +interface; the five 422 bodies such as `NotifySigners422ResponseOcsData` require `action` and `errors`, and the seven envelope `anyOf` bodies become `data: any`. Upstream status: `OpenAPITools/openapi-generator#8894` ("`anyOf` creates same interface as `allOf`", reported against 5.0.1) is open -and matches the merged-interface cases (`FileListResponseDataInner` and the two -notify 422 bodies). It does not describe the lost dynamic branch of +and matches the merged-interface cases (`FileListResponseDataInner` and the five +422 bodies). It does not describe the lost dynamic branch of `FileRuntimeMetadata`, the empty `RequestPolicyOverridesValue` or the seven envelope cases, where the generator keeps `data: any`; those may need their own reports. The fix was not tracked here. The earlier evaluation recorded the former `EffectivePolicyValue` defect, a different `anyOf` case, in both 7.15.0 and 7.27.0; the object cases above were checked only with 7.27.0. @@ -203,21 +204,30 @@ in LibreSign. Candidates, each needing its cause confirmed first: - the 7 error bodies with an untyped `data: {}` (E2): investigated; the controllers' explicit 401/403 declarations describe what the code returns, so the untyped body is the extractor's and needs no LibreSign change; -- the error bodies that did not match the code (done): `request-signature` - POST/PATCH now document only `MessageResponse` for 422 (two `anyOf` fewer), - `removeSigner` documents `MessageResponse` for 422, `deleteFile` and - `deleteSignatureRequest` no longer document a 422 they never return, and +- annotations that did not match the data (done): `removeSigner` now documents + `MessageResponse | ActionErrorResponse` for 422 (its `catch` answers + `{message}`, the middleware answers `{action, errors}`), and `DetailedFile.nodeId` is nullable like the database column. Guarded by - `tests/php/openapi/OpenApiErrorBodyContractTest.php`; -- **open maintainer decision**: six methods return HTTP 401 for any failure - (`AccountController::signatureGenerate`, the `AdminController` certificate - generators, `FileController::deleteFile`, - `RequestSignatureController::deleteSignatureRequest` and `removeSigner`). - Moving business failures to 422/400 is a compatibility-breaking change that - needs its own change and Behat updates; not done here; -- `DetailedFile.policySnapshotFrozen` is required but only set when a user is - present (`FileListService.php:273-275`); not changed because it was not shown - that the OCS responses typed `DetailedFile` can lack a user; + `tests/php/openapi/OpenApiErrorBodyContractTest.php`. The 422 documentation of + `request-signature`, `deleteFile` and `deleteSignatureRequest` was checked and + is correct: `#[RequireManager]` rejects a user without permission with an + `{action, errors}` 422 before the method runs; +- **open maintainer decision**: several methods answer HTTP 401 for failures + that are not authentication failures. `AccountController::signatureGenerate`, + the `AdminController` certificate generators (`catch \Exception`), + `FileController::deleteFile` and + `RequestSignatureController::deleteSignatureRequest` (`catch \Throwable`) + return 401 for every caught failure; `removeSigner` returns 401 for a + `LibresignException` whose code is not 422. Moving business failures to + 422/400 is a compatibility-breaking change that needs its own change and + Behat updates; not done here; +- `DetailedFile.policySnapshotFrozen` is declared required, but + `formatSingleFileData` omits it without a user (`FileListService.php:273-275`) + while `formatFileWithChildren` always sets it (`:881`); not changed because it + was not established which builder feeds each typed OCS response; +- `ValidatedFile.nodeId` and `ValidatedChildFile.nodeId` are declared as + integers although `BeforeNodeDeletedListener` clears `node_id` of an original + file whose signed copy remains; not changed here, worth a separate fix; - the three `anyOf` schemas in `lib/ResponseDefinitions.php` (E2/G1): investigated, no change recommended. `FileSummary|DetailedFile` is a per-item approximation, because `FileListService.php:99-103` makes the From 64821680b37de52de7c074eebf0c5e2baffc1909 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 10:42:31 -0300 Subject: [PATCH 05/14] docs(sdk): fix inaccurate statements found in the second review - say that the evaluation changes the LibreSign annotations, committed OpenAPI and generated types, instead of claiming no change; - separate the five merged 422 models from the seven envelope models that read the contract faithfully; - attribute the {action, errors} body of the notify endpoints to the call inside NotifyService, since they have no RequireManager; - describe the 82 untyped 401/403 responses as mostly implicit, not only implicit; - drop "object unions" from the extractor handoff option and the overstated "schema-valid null" claim in the README; - list the other RequireManager methods that do not document the permission 422. Signed-off-by: Luis Amorim --- tests/sdk-generation/README.md | 6 ++++-- tests/sdk-generation/REPORT.md | 29 +++++++++++++++----------- tests/sdk-generation/UPSTREAM-NOTES.md | 21 ++++++++++++++----- 3 files changed, 37 insertions(+), 19 deletions(-) diff --git a/tests/sdk-generation/README.md b/tests/sdk-generation/README.md index 400865a195..d182df443f 100644 --- a/tests/sdk-generation/README.md +++ b/tests/sdk-generation/README.md @@ -52,8 +52,10 @@ npm run test:normalized --prefix tests/sdk-generation ``` The positive/negative type checks pass, including the object unions that the -unmodified output merges incorrectly. They also record that schema-valid `null` -is still rejected by the standalone union. This is partial mitigation, not a Go. +unmodified output merges incorrectly. They also record that `null` is still +rejected by the standalone union; how `nullable` should work on a composed schema +is itself unresolved (see UPSTREAM-NOTES.md E4). This is partial mitigation, not +a Go. `oneOf` and `anyOf` are not equivalent validation contracts: overlapping object branches would violate `oneOf`. The transformed file must never replace the source contract. diff --git a/tests/sdk-generation/REPORT.md b/tests/sdk-generation/REPORT.md index 92d731ece1..84e4458f00 100644 --- a/tests/sdk-generation/REPORT.md +++ b/tests/sdk-generation/REPORT.md @@ -15,14 +15,15 @@ keeps `| null` at the properties that reference it (disjoint `oneOf` contract, `@nextcloud/axios` injection all pass. The decision remains No-Go for unmodified input because three generated models -(and the 12 error-body models) of the remaining 15 `anyOf` constructs are still -incorrect -(see [Remaining model defects](#remaining-model-defects)), and multipart +and five merged 422 error-body models of the remaining 15 `anyOf` constructs +are still incorrect (the other seven, envelope 401/403 bodies, read the contract +faithfully; see [Remaining model defects](#remaining-model-defects)), and multipart bodies are still absent from the contract. Every blocker left is on the extractor/generator side or needs a maintainer decision about the contract shape; see [UPSTREAM-NOTES.md](UPSTREAM-NOTES.md). This evaluation selects no -option and changes no PHP controller, extractor, committed OpenAPI, generated -frontend type, CI job or permanent SDK. +option and changes no extractor, generator, CI job or permanent SDK. Its only +LibreSign changes are the annotation, committed OpenAPI and generated type +changes listed under [Input and toolchain](#input-and-toolchain). ## Input and toolchain @@ -105,11 +106,15 @@ soon as one of them fails (TS2578 or TS2322): The other 12 `anyOf` occurrences are in 4xx bodies. Five (the 422 responses of `notify-signers`, `notify-signer`, `request-signature`, -`update-signature-request` and `removeSigner`) are real unions. A user without -permission is rejected by the `RequireManager`/`canRequestSign()` middleware -with an `{action, errors}` body (`ActionErrorResponse`) before the controller -runs; failures inside the method answer `{message}` (`MessageResponse`). The -generator merges them into one interface (for example +`update-signature-request` and `removeSigner`) are real unions of an +`{action, errors}` body (`ActionErrorResponse`, a `LibresignException` with a +JSON message) and a `{message}` body (`MessageResponse`), both serialized by the +middleware's `afterException`. For `request-signature` and `removeSigner` the +first comes from `#[RequireManager]`, which runs `canRequestSign()` before the +method, and the second from the method's own `catch`. The two notify endpoints +have no `RequireManager`: `NotifyService` calls `canRequestSign()` inside the +action and `sendNotification()` rethrows the exception. The generator merges +the alternatives into one interface (for example `NotifySigners422ResponseOcsData` requires `action` and `errors`, which the `MessageResponse` alternative does not have). The other seven (six 401 bodies and the `footer-template` 403) are envelope-level `anyOf` whose second branch @@ -220,8 +225,8 @@ Maintainers must choose among these options; this evaluation selects none: 1. Conditional Go with a reviewed generator-input normalization of the 15 `anyOf` constructs, documented as non-contractual. -2. Fix the extractor (object unions, duplicated implicit 401/403) and the - generator upstream, and adjust LibreSign's own types or annotations where +2. Fix the generator's `anyOf` merge and type the extractor's implicit 401/403 + body upstream, and adjust LibreSign's own types or annotations where their cause is confirmed to be in LibreSign, then regenerate. 3. Evaluate another generator against the same acceptance criteria. diff --git a/tests/sdk-generation/UPSTREAM-NOTES.md b/tests/sdk-generation/UPSTREAM-NOTES.md index 2bc2a07e24..d4f4f00a54 100644 --- a/tests/sdk-generation/UPSTREAM-NOTES.md +++ b/tests/sdk-generation/UPSTREAM-NOTES.md @@ -50,9 +50,13 @@ and OpenAPI Generator mishandles them (G1). Affected schemas, 15 in total: - `RequestPolicyOverrides` values: `EffectivePolicyValue | list`; - 5 `422` bodies: `MessageResponse | ActionErrorResponse` (notify-signers, notify-signer, request-signature, update-signature-request and - `removeSigner`). The union is real: the `RequireManager`/`canRequestSign()` - middleware answers `{action, errors}` before the controller runs, and the - methods answer `{message}` from their own `catch` blocks; + `removeSigner`). The union is real. `{action, errors}` is a + `LibresignException` with a JSON message and `{message}` a plain one, both + serialized by `afterException`. `request-signature` and `removeSigner` get the + first from `#[RequireManager]` (`canRequestSign()` runs before the method) and + the second from their `catch` blocks. The notify endpoints have no + `RequireManager`: `NotifyService` calls `canRequestSign()` inside the action + and `NotifyController::sendNotification()` rethrows; - 7 error bodies (six 401 and the footer-template 403): an envelope `anyOf` whose second branch has an untyped `data: {}`. Cause confirmed: for every non-public OCS method the extractor adds an implicit 401 with an untyped @@ -66,8 +70,9 @@ and OpenAPI Generator mishandles them (G1). Affected schemas, 15 in total: `FileController::deleteFile`, `FooterTemplateController::saveFooterTemplate` (403), `RequestSignatureController::removeSigner` and `deleteSignatureRequest`. Public methods that declare a 401 (for example `IdDocsController::delete`) - generate a single typed response, and the 82 other 401/403 responses are - implicit-only. The explicit declarations describe what the code returns, so + generate a single typed response, and the 82 other 401/403 responses have an + untyped `data: {}`, mostly the implicit ones (a few are explicit `list` + declarations, for example `FileController.php:138`). The explicit declarations describe what the code returns, so removing them would only erase the typed body and leave `data: {}`. The request to the extractor is therefore to give the implicit 401/403 a typed body (or to let the controller refine it), not to let an explicit declaration @@ -212,6 +217,12 @@ in LibreSign. Candidates, each needing its cause confirmed first: `request-signature`, `deleteFile` and `deleteSignatureRequest` was checked and is correct: `#[RequireManager]` rejects a user without permission with an `{action, errors}` 422 before the method runs; +- other `#[RequireManager]` methods do not document the 422 `{action, errors}` + body of the permission middleware: `FileController::save` and + `addFileToEnvelope` document only `MessageResponse` at 422, and + `IdentifyController::search` documents no 422. They are outside this change. + The same kind of fix applies, but each method's own `catch` blocks must be + checked first so the documented union stays exact; - **open maintainer decision**: several methods answer HTTP 401 for failures that are not authentication failures. `AccountController::signatureGenerate`, the `AdminController` certificate generators (`catch \Exception`), From 5b406f10a13252e0bb4167431472467827bec17b Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 10:50:25 -0300 Subject: [PATCH 06/14] fix(openapi): document the permission 422 and the nullable nodeId Complete the annotations that omitted what the API really returns: - file-save and file-add-file-to-envelope document the 422 as `MessageResponse|ActionErrorResponse`: #[RequireManager] runs canRequestSign() before the method, so a user without permission gets an `{action, errors}` body, while the catch blocks answer `{message}`; - identify-account/search documents the middleware 422 (`ActionErrorResponse`); the method has no try block; - ValidatedFile and ValidatedChildFile accept a null nodeId, like DetailedFile: BeforeNodeDeletedListener clears libresign_file.node_id when the original file is deleted and the validation code copies the entity value as is. The file filter in validationDocument.ts keeps rejecting a null nodeId; only its type predicate follows the normalized value, so behavior is unchanged. Specs and TypeScript types are regenerated, not hand-edited. The contract test covers the new shapes. Signed-off-by: Luis Amorim --- lib/Controller/FileController.php | 4 +- lib/Controller/IdentifyController.php | 4 +- lib/ResponseDefinitions.php | 4 +- openapi-full.json | 52 +++++++++++++++++-- openapi.json | 52 +++++++++++++++++-- src/services/validationDocument.ts | 2 +- src/types/openapi/openapi-full.ts | 22 ++++++-- src/types/openapi/openapi.ts | 22 ++++++-- .../openapi/OpenApiErrorBodyContractTest.php | 29 +++++++++-- 9 files changed, 167 insertions(+), 24 deletions(-) diff --git a/lib/Controller/FileController.php b/lib/Controller/FileController.php index 27a26695b4..87cfb02b62 100644 --- a/lib/Controller/FileController.php +++ b/lib/Controller/FileController.php @@ -585,7 +585,7 @@ private function getMimeFallbackResponse(string $mimeType): ?\OCP\AppFramework\H * @param string $name The name of file to sign * @param LibresignFolderSettings $settings Settings to define how and where the file should be stored * @param list $files Multiple files to create an envelope (optional, use either file or files) - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: OK * 422: Failed to save data @@ -630,7 +630,7 @@ public function save( * Multipart clients can send optional expectedFilesCount to reject incomplete batches. * * @param string $uuid The UUID of the envelope - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse|DataResponse * * 200: Files added successfully * 400: Invalid request diff --git a/lib/Controller/IdentifyController.php b/lib/Controller/IdentifyController.php index 5bf8f473ea..7b2509fcf1 100644 --- a/lib/Controller/IdentifyController.php +++ b/lib/Controller/IdentifyController.php @@ -32,6 +32,7 @@ use OCP\IRequest; /** + * @psalm-import-type LibresignActionErrorResponse from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignIdentifyAccount from \OCA\Libresign\ResponseDefinitions * @psalm-import-type LibresignIdentifyAccountsResponse from \OCA\Libresign\ResponseDefinitions */ @@ -59,9 +60,10 @@ public function __construct( * @param string $method filter by method (email, account, sms, signal, telegram, whatsapp, whatsappbusiness, xmpp) * @param int $page the number of page to return. Default: 1 * @param int $limit Total of elements to return. Default: 25 - * @return DataResponse + * @return DataResponse|DataResponse * * 200: Certificate saved with success + * 422: User is not allowed to request signatures */ #[NoAdminRequired] #[RequireManager] diff --git a/lib/ResponseDefinitions.php b/lib/ResponseDefinitions.php index f7cf4b5f00..d12fc7a37e 100644 --- a/lib/ResponseDefinitions.php +++ b/lib/ResponseDefinitions.php @@ -657,7 +657,7 @@ * name: string, * status: int, * statusText: string, - * nodeId: int, + * nodeId: ?int, * totalPages?: non-negative-int, * size: non-negative-int, * pdfVersion?: string, @@ -671,7 +671,7 @@ * name: string, * status: 0|1|2|3|4|6, * statusText: string, - * nodeId: non-negative-int, + * nodeId: non-negative-int|null, * nodeType: 'file'|'envelope', * signatureFlow: 'none'|'parallel'|'ordered_numeric', * policySnapshotFrozen?: bool, diff --git a/openapi-full.json b/openapi-full.json index 3544b68f89..b374e9aba7 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -3903,7 +3903,8 @@ }, "nodeId": { "type": "integer", - "format": "int64" + "format": "int64", + "nullable": true }, "totalPages": { "type": "integer", @@ -3999,6 +4000,7 @@ "nodeId": { "type": "integer", "format": "int64", + "nullable": true, "minimum": 0 }, "nodeType": { @@ -6882,7 +6884,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -7083,7 +7092,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -9179,6 +9195,36 @@ } } }, + "422": { + "description": "User is not allowed to request signatures", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/ActionErrorResponse" + } + } + } + } + } + } + } + }, "401": { "description": "Current user is not logged in", "content": { diff --git a/openapi.json b/openapi.json index c07af04e03..288494d135 100644 --- a/openapi.json +++ b/openapi.json @@ -3361,7 +3361,8 @@ }, "nodeId": { "type": "integer", - "format": "int64" + "format": "int64", + "nullable": true }, "totalPages": { "type": "integer", @@ -3457,6 +3458,7 @@ "nodeId": { "type": "integer", "format": "int64", + "nullable": true, "minimum": 0 }, "nodeType": { @@ -6340,7 +6342,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -6541,7 +6550,14 @@ "$ref": "#/components/schemas/OCSMeta" }, "data": { - "$ref": "#/components/schemas/MessageResponse" + "anyOf": [ + { + "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } @@ -8442,6 +8458,36 @@ } } }, + "422": { + "description": "User is not allowed to request signatures", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/ActionErrorResponse" + } + } + } + } + } + } + } + }, "401": { "description": "Current user is not logged in", "content": { diff --git a/src/services/validationDocument.ts b/src/services/validationDocument.ts index 7af705ae58..af2b19a1da 100644 --- a/src/services/validationDocument.ts +++ b/src/services/validationDocument.ts @@ -476,7 +476,7 @@ export function toValidationDocument(data: unknown): ValidationDocumentState | n if (files.some(file => file === null)) { return null } - const normalizedFiles = files.filter((file): file is ValidatedChildFileRecord => file !== null) + const normalizedFiles = files.filter((file): file is NonNullable => file !== null) const metadata = isValidationMetadata(data.metadata) ? data.metadata diff --git a/src/types/openapi/openapi-full.ts b/src/types/openapi/openapi-full.ts index 4b54580695..5308b2d464 100644 --- a/src/types/openapi/openapi-full.ts +++ b/src/types/openapi/openapi-full.ts @@ -2424,7 +2424,7 @@ export type components = { status: number; statusText: string; /** Format: int64 */ - nodeId: number; + nodeId: number | null; /** Format: int64 */ totalPages?: number; /** Format: int64 */ @@ -2449,7 +2449,7 @@ export type components = { status: 0 | 1 | 2 | 3 | 4 | 6; statusText: string; /** Format: int64 */ - nodeId: number; + nodeId: number | null; /** @enum {string} */ nodeType: "file" | "envelope"; /** @enum {string} */ @@ -3668,7 +3668,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -3756,7 +3756,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -4659,6 +4659,20 @@ export interface operations { }; }; }; + /** @description User is not allowed to request signatures */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; }; }; "notify-signers": { diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index cdde286544..3226ee12da 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -1956,7 +1956,7 @@ export type components = { status: number; statusText: string; /** Format: int64 */ - nodeId: number; + nodeId: number | null; /** Format: int64 */ totalPages?: number; /** Format: int64 */ @@ -1981,7 +1981,7 @@ export type components = { status: 0 | 1 | 2 | 3 | 4 | 6; statusText: string; /** Format: int64 */ - nodeId: number; + nodeId: number | null; /** @enum {string} */ nodeType: "file" | "envelope"; /** @enum {string} */ @@ -3200,7 +3200,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -3288,7 +3288,7 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; }; }; }; @@ -4097,6 +4097,20 @@ export interface operations { }; }; }; + /** @description User is not allowed to request signatures */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; }; }; "notify-signers": { diff --git a/tests/php/openapi/OpenApiErrorBodyContractTest.php b/tests/php/openapi/OpenApiErrorBodyContractTest.php index 2c49a8d54e..638a44dfaa 100644 --- a/tests/php/openapi/OpenApiErrorBodyContractTest.php +++ b/tests/php/openapi/OpenApiErrorBodyContractTest.php @@ -66,6 +66,24 @@ public function testDeleteOperationsDocumentTheMiddleware422(string $file): void } } + #[DataProvider('specificationProvider')] + public function testFileUploadsDocumentBothBodiesAt422(string $file): void { + // The middleware rejects a user without permission before the method; the + // catch block answers {message}. + $paths = $this->load($file)['paths']; + + $this->assertBothBodies($paths[self::BASE . 'file']['post'], 'file-save'); + $this->assertBothBodies($paths[self::BASE . 'file/{uuid}/add-file']['post'], 'file-add-file-to-envelope'); + } + + #[DataProvider('specificationProvider')] + public function testIdentifySearchDocumentsTheMiddleware422(string $file): void { + // The method has no try block: only the middleware can answer 422. + $operation = $this->load($file)['paths'][self::BASE . 'identify-account/search']['get']; + + self::assertSame(self::ACTION_ERROR, $this->errorData($operation, '422')['$ref'] ?? null); + } + #[DataProvider('specificationProvider')] public function testNotifyKeepsBothRealBodiesAt422(string $file): void { // canRequestSign() throws an action/errors body, other validations a message body. @@ -77,11 +95,14 @@ public function testNotifyKeepsBothRealBodiesAt422(string $file): void { } #[DataProvider('specificationProvider')] - public function testDetailedFileNodeIdIsNullable(string $file): void { - // libresign_file.node_id is nullable and the value is copied as is. - $nodeId = $this->load($file)['components']['schemas']['DetailedFile']['properties']['nodeId']; + public function testFileSchemasWithTheEntityNodeIdAreNullable(string $file): void { + // libresign_file.node_id is nullable (BeforeNodeDeletedListener clears it + // when the original file is deleted) and the value is copied as is. + $schemas = $this->load($file)['components']['schemas']; - self::assertTrue($nodeId['nullable'] ?? false); + foreach (['DetailedFile', 'ValidatedFile', 'ValidatedChildFile'] as $schema) { + self::assertTrue($schemas[$schema]['properties']['nodeId']['nullable'] ?? false, $schema); + } } private function assertBothBodies(array $operation, string $label): void { From 134dc66c5b72069e91a9608881bf093db9f298a6 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 10:50:25 -0300 Subject: [PATCH 07/14] docs(sdk): record the completed annotations and the validation nodeId Update the counts (17 anyOf, 14 of them in error bodies), the SHA-256, the list of corrected annotations, and note that the validation frontend treats a null nodeId as an invalid document. Signed-off-by: Luis Amorim --- tests/sdk-generation/README.md | 2 +- tests/sdk-generation/REPORT.md | 39 ++++++++++++++-------- tests/sdk-generation/UPSTREAM-NOTES.md | 45 +++++++++++++------------- 3 files changed, 50 insertions(+), 36 deletions(-) diff --git a/tests/sdk-generation/README.md b/tests/sdk-generation/README.md index d182df443f..350e536b42 100644 --- a/tests/sdk-generation/README.md +++ b/tests/sdk-generation/README.md @@ -42,7 +42,7 @@ See [REPORT.md](REPORT.md) and [inventory.md](inventory.md) for results. ## Normalized-input experiment -This separate experiment changes all 15 `anyOf` keywords to `oneOf` in a +This separate experiment changes all 17 `anyOf` keywords to `oneOf` in a **disposable generator input**, never in the committed specification: ```sh diff --git a/tests/sdk-generation/REPORT.md b/tests/sdk-generation/REPORT.md index 84e4458f00..cf43d1be8e 100644 --- a/tests/sdk-generation/REPORT.md +++ b/tests/sdk-generation/REPORT.md @@ -15,7 +15,7 @@ keeps `| null` at the properties that reference it (disjoint `oneOf` contract, `@nextcloud/axios` injection all pass. The decision remains No-Go for unmodified input because three generated models -and five merged 422 error-body models of the remaining 15 `anyOf` constructs +and seven merged 422 error-body models of the remaining 17 `anyOf` constructs are still incorrect (the other seven, envelope 401/403 bodies, read the contract faithfully; see [Remaining model defects](#remaining-model-defects)), and multipart bodies are still absent from the contract. Every blocker left is on the @@ -32,7 +32,7 @@ changes listed under [Input and toolchain](#input-and-toolchain). to `IdDocFile`, literal media types for the CRL and the admin background, and annotations aligned with what the code returns (see [Annotations aligned with the code](#annotations-aligned-with-the-code)). -- `openapi-full.json` SHA-256 with those changes: `36635e033a52861d1bb5e0281bb759a7fdf4e05d097d9fd6610e2a29577ab6fa` +- `openapi-full.json` SHA-256 with those changes: `b586418da879f0650b4e9ee4f9b0553c8cb3b72472c80cd998cf395491855387` (`64c52fa2ba243af292eba30055982954bfd8c19136567e50e28c4abcffcc9405` on `main`). - Extractor used to produce the contract: `nextcloud/openapi-extractor` 1.9.1. - Generator: `openapitools/openapi-generator-cli` 7.27.0 at @@ -104,12 +104,14 @@ soon as one of them fails (TS2578 or TS2322): | `FileRuntimeMetadata` | `anyOf` `ValidateMetadata`, `{ [key]: DynamicMetadataValue }` | only the `ValidateMetadata` fields, with `extension` and `p` required | a valid dynamic metadata object is rejected | | `RequestPolicyOverrides` values | `anyOf` `EffectivePolicyValue`, array of it | empty interface `RequestPolicyOverridesValue` | accepts any non-null value | -The other 12 `anyOf` occurrences are in 4xx bodies. Five (the 422 responses of +The other 14 `anyOf` occurrences are in 4xx bodies. Seven (the 422 responses of `notify-signers`, `notify-signer`, `request-signature`, -`update-signature-request` and `removeSigner`) are real unions of an +`update-signature-request`, `removeSigner`, `file-save` and +`file-add-file-to-envelope`) are real unions of an `{action, errors}` body (`ActionErrorResponse`, a `LibresignException` with a JSON message) and a `{message}` body (`MessageResponse`), both serialized by the -middleware's `afterException`. For `request-signature` and `removeSigner` the +middleware's `afterException`. For `request-signature`, `removeSigner`, `file-save` and +`file-add-file-to-envelope` the first comes from `#[RequireManager]`, which runs `canRequestSign()` before the method, and the second from the method's own `catch`. The two notify endpoints have no `RequireManager`: `NotifyService` calls `canRequestSign()` inside the @@ -148,14 +150,25 @@ envelopes are not unwrapped. ### Annotations aligned with the code -Two LibreSign annotations did not match the data and were corrected: +LibreSign annotations that did not match the data were corrected: - `removeSigner` documented only an `ActionErrorResponse` 422, but its `catch` - also answers `{message}` with 422 when the exception code is 422. It now - documents `MessageResponse | ActionErrorResponse`, which adds one `anyOf` - (14 became 15). -- `DetailedFile.nodeId` is now nullable: `libresign_file.node_id` is nullable - and the entity value is copied as is (`FileSummary` already allowed null). + also answers `{message}` with 422 when the exception code is 422. + `file-save` and `file-add-file-to-envelope` documented only a + `MessageResponse` 422, but `#[RequireManager]` rejects a user without + permission with an `{action, errors}` 422 before the method runs. The three + now document `MessageResponse | ActionErrorResponse`, which adds three `anyOf` + (14 became 17). +- `identify-account/search` documented no 422 although it has + `#[RequireManager]` and no `try` block: it now documents the middleware's + `ActionErrorResponse`. +- `nodeId` is nullable in `DetailedFile`, `ValidatedFile` and + `ValidatedChildFile`: `libresign_file.node_id` is nullable (the + `BeforeNodeDeletedListener` clears it when the original file is deleted) and + the entity value is copied as is (`FileSummary` already allowed null). + `src/services/validationDocument.ts` already rejects a validation payload with + a null `nodeId`; only the type predicate of its file filter changed, not its + behavior. `tests/php/openapi/OpenApiErrorBodyContractTest.php` guards these and the other 422 unions. A review of this branch caught an earlier mistaken narrowing: the @@ -179,7 +192,7 @@ scenarios, so it needs its own change. `normalize-input.cjs` writes only `build/sdk-generation/normalized/openapi-full.oneof.json`, renaming the -remaining 15 `anyOf` keywords to `oneOf`. It generates +remaining 17 `anyOf` keywords to `oneOf`. It generates `FileListResponseDataInner = DetailedFile | FileSummary` and `FileRuntimeMetadata = ValidateMetadata | { [key: string]: ... }`, and `test:normalized` passes. It is generator-input normalization only: object @@ -223,7 +236,7 @@ the extractor support above (or another reviewed design) and a regeneration. Maintainers must choose among these options; this evaluation selects none: -1. Conditional Go with a reviewed generator-input normalization of the 15 +1. Conditional Go with a reviewed generator-input normalization of the 17 `anyOf` constructs, documented as non-contractual. 2. Fix the generator's `anyOf` merge and type the extractor's implicit 401/403 body upstream, and adjust LibreSign's own types or annotations where diff --git a/tests/sdk-generation/UPSTREAM-NOTES.md b/tests/sdk-generation/UPSTREAM-NOTES.md index d4f4f00a54..719c4da3c0 100644 --- a/tests/sdk-generation/UPSTREAM-NOTES.md +++ b/tests/sdk-generation/UPSTREAM-NOTES.md @@ -43,16 +43,16 @@ single and repeated files (not yet testable, see G5). As #9494 showed, the extractor emitted `oneOf` for the policy value once its scalar branches became disjoint. Unions that include objects or arrays (the policy-override one pairs a value with an array of values) are still emitted as `anyOf`, -and OpenAPI Generator mishandles them (G1). Affected schemas, 15 in total: +and OpenAPI Generator mishandles them (G1). Affected schemas, 17 in total: - `FileListResponse.data[]` items: `FileSummary | DetailedFile`; - `FileRuntimeMetadata`: `ValidateMetadata | array`; - `RequestPolicyOverrides` values: `EffectivePolicyValue | list`; -- 5 `422` bodies: `MessageResponse | ActionErrorResponse` (notify-signers, - notify-signer, request-signature, update-signature-request and - `removeSigner`). The union is real. `{action, errors}` is a +- 7 `422` bodies: `MessageResponse | ActionErrorResponse` (notify-signers, + notify-signer, request-signature, update-signature-request, `removeSigner`, + `file-save` and `file-add-file-to-envelope`). The union is real. `{action, errors}` is a `LibresignException` with a JSON message and `{message}` a plain one, both - serialized by `afterException`. `request-signature` and `removeSigner` get the + serialized by `afterException`. The other five get the first from `#[RequireManager]` (`canRequestSign()` runs before the method) and the second from their `catch` blocks. The notify endpoints have no `RequireManager`: `NotifyService` calls `canRequestSign()` inside the action @@ -88,7 +88,7 @@ For the object unions, `anyOf` is semantically correct: without matches both (a detailed file can match both `FileSummary` and `DetailedFile`), so `oneOf` would be wrong. The defect is the generator's merge (G1), not the extractor's choice. Evidence: `npm run test:anyof` (`union-defects.ts`) and -`npm run test:normalized`, which renames the 15 keywords in a disposable copy +`npm run test:normalized`, which renames the 17 keywords in a disposable copy and passes. ### E3. `mixed` maps to `{ type: object }` @@ -137,10 +137,10 @@ The generated interface merges both alternatives and keeps required fields from one of them: `FileListResponseDataInner` requires `files`, `size` and `visibleElements` and narrows `nodeId` to `number`; `FileRuntimeMetadata` loses its dynamic branch; the `RequestPolicyOverridesValue` union becomes an empty -interface; the five 422 bodies such as `NotifySigners422ResponseOcsData` require +interface; the seven 422 bodies such as `NotifySigners422ResponseOcsData` require `action` and `errors`, and the seven envelope `anyOf` bodies become `data: any`. Upstream status: `OpenAPITools/openapi-generator#8894` ("`anyOf` creates same interface as `allOf`", reported against 5.0.1) is open -and matches the merged-interface cases (`FileListResponseDataInner` and the five +and matches the merged-interface cases (`FileListResponseDataInner` and the seven 422 bodies). It does not describe the lost dynamic branch of `FileRuntimeMetadata`, the empty `RequestPolicyOverridesValue` or the seven envelope cases, where the generator keeps `data: any`; those may need their own @@ -209,20 +209,19 @@ in LibreSign. Candidates, each needing its cause confirmed first: - the 7 error bodies with an untyped `data: {}` (E2): investigated; the controllers' explicit 401/403 declarations describe what the code returns, so the untyped body is the extractor's and needs no LibreSign change; -- annotations that did not match the data (done): `removeSigner` now documents - `MessageResponse | ActionErrorResponse` for 422 (its `catch` answers - `{message}`, the middleware answers `{action, errors}`), and - `DetailedFile.nodeId` is nullable like the database column. Guarded by +- annotations that did not match the data (done): `removeSigner`, `file-save` + and `file-add-file-to-envelope` now document `MessageResponse | + ActionErrorResponse` for 422 (their `catch` answers `{message}`, the + middleware answers `{action, errors}`); `identify-account/search` documents the + middleware 422 (`ActionErrorResponse`), it has no `try` block; and `nodeId` is + nullable in `DetailedFile`, `ValidatedFile` and `ValidatedChildFile` like the + database column. Guarded by `tests/php/openapi/OpenApiErrorBodyContractTest.php`. The 422 documentation of `request-signature`, `deleteFile` and `deleteSignatureRequest` was checked and is correct: `#[RequireManager]` rejects a user without permission with an - `{action, errors}` 422 before the method runs; -- other `#[RequireManager]` methods do not document the 422 `{action, errors}` - body of the permission middleware: `FileController::save` and - `addFileToEnvelope` document only `MessageResponse` at 422, and - `IdentifyController::search` documents no 422. They are outside this change. - The same kind of fix applies, but each method's own `catch` blocks must be - checked first so the documented union stays exact; + `{action, errors}` 422 before the method runs. `SignFileController::signByFileId` + is public and documents `SignActionErrorResponse`, which accommodates that + payload; unchanged; - **open maintainer decision**: several methods answer HTTP 401 for failures that are not authentication failures. `AccountController::signatureGenerate`, the `AdminController` certificate generators (`catch \Exception`), @@ -236,9 +235,11 @@ in LibreSign. Candidates, each needing its cause confirmed first: `formatSingleFileData` omits it without a user (`FileListService.php:273-275`) while `formatFileWithChildren` always sets it (`:881`); not changed because it was not established which builder feeds each typed OCS response; -- `ValidatedFile.nodeId` and `ValidatedChildFile.nodeId` are declared as - integers although `BeforeNodeDeletedListener` clears `node_id` of an original - file whose signed copy remains; not changed here, worth a separate fix; +- `src/services/validationDocument.ts` (`isValidatedChildFileRecord` and + `isValidationDocumentRecord`) treats a validation payload with a null + `nodeId` as invalid, although the backend can send it once the original file + was deleted (`FileService.php`, `EnvelopeAssembler.php`). Not changed here: it + is a frontend behavior decision, not an annotation; - the three `anyOf` schemas in `lib/ResponseDefinitions.php` (E2/G1): investigated, no change recommended. `FileSummary|DetailedFile` is a per-item approximation, because `FileListService.php:99-103` makes the From 6c8d6cb127f6b97e5a826537a97df1a20c4cc4d4 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 11:00:23 -0300 Subject: [PATCH 08/14] docs(sdk): fix the description of how the 422 bodies are produced Only the notify endpoints rely on the middleware to serialize both 422 bodies. For the five operations guarded by #[RequireManager] the `{message}` body is a DataResponse built in the method's catch block, and the middleware only serializes the permission body. Also list the frontend type adjustments among the LibreSign changes of the evaluation. Signed-off-by: Luis Amorim --- tests/sdk-generation/REPORT.md | 20 ++++++++++++-------- tests/sdk-generation/UPSTREAM-NOTES.md | 15 ++++++++------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/tests/sdk-generation/REPORT.md b/tests/sdk-generation/REPORT.md index cf43d1be8e..1494ec8d0f 100644 --- a/tests/sdk-generation/REPORT.md +++ b/tests/sdk-generation/REPORT.md @@ -23,7 +23,9 @@ extractor/generator side or needs a maintainer decision about the contract shape; see [UPSTREAM-NOTES.md](UPSTREAM-NOTES.md). This evaluation selects no option and changes no extractor, generator, CI job or permanent SDK. Its only LibreSign changes are the annotation, committed OpenAPI and generated type -changes listed under [Input and toolchain](#input-and-toolchain). +changes listed under [Input and toolchain](#input-and-toolchain), the frontend +type alias for the renamed schema and a type predicate in +`src/services/validationDocument.ts`; none changes runtime behavior. ## Input and toolchain @@ -109,13 +111,15 @@ The other 14 `anyOf` occurrences are in 4xx bodies. Seven (the 422 responses of `update-signature-request`, `removeSigner`, `file-save` and `file-add-file-to-envelope`) are real unions of an `{action, errors}` body (`ActionErrorResponse`, a `LibresignException` with a -JSON message) and a `{message}` body (`MessageResponse`), both serialized by the -middleware's `afterException`. For `request-signature`, `removeSigner`, `file-save` and -`file-add-file-to-envelope` the -first comes from `#[RequireManager]`, which runs `canRequestSign()` before the -method, and the second from the method's own `catch`. The two notify endpoints -have no `RequireManager`: `NotifyService` calls `canRequestSign()` inside the -action and `sendNotification()` rethrows the exception. The generator merges +JSON message) and a `{message}` body (`MessageResponse`). For +`request-signature` (POST and PATCH), `removeSigner`, `file-save` and +`file-add-file-to-envelope` the first comes from `#[RequireManager]`, which runs +`canRequestSign()` before the method and is serialized by the middleware's +`afterException`; the second is a `DataResponse` built by the method's own +`catch`. The two notify endpoints have no `RequireManager`: `NotifyService` +calls `canRequestSign()` inside the action, `sendNotification()` rethrows the +exception and `afterException` serializes both bodies (JSON message as +`{action, errors}`, plain message as `{message}`). The generator merges the alternatives into one interface (for example `NotifySigners422ResponseOcsData` requires `action` and `errors`, which the `MessageResponse` alternative does not have). The other seven (six 401 bodies diff --git a/tests/sdk-generation/UPSTREAM-NOTES.md b/tests/sdk-generation/UPSTREAM-NOTES.md index 719c4da3c0..5183548c41 100644 --- a/tests/sdk-generation/UPSTREAM-NOTES.md +++ b/tests/sdk-generation/UPSTREAM-NOTES.md @@ -50,13 +50,14 @@ and OpenAPI Generator mishandles them (G1). Affected schemas, 17 in total: - `RequestPolicyOverrides` values: `EffectivePolicyValue | list`; - 7 `422` bodies: `MessageResponse | ActionErrorResponse` (notify-signers, notify-signer, request-signature, update-signature-request, `removeSigner`, - `file-save` and `file-add-file-to-envelope`). The union is real. `{action, errors}` is a - `LibresignException` with a JSON message and `{message}` a plain one, both - serialized by `afterException`. The other five get the - first from `#[RequireManager]` (`canRequestSign()` runs before the method) and - the second from their `catch` blocks. The notify endpoints have no - `RequireManager`: `NotifyService` calls `canRequestSign()` inside the action - and `NotifyController::sendNotification()` rethrows; + `file-save` and `file-add-file-to-envelope`). The union is real. The other + five get `{action, errors}` from `#[RequireManager]` (`canRequestSign()` runs + before the method; `afterException` serializes the `LibresignException`) and + `{message}` from a `DataResponse` built in their own `catch` blocks. The + notify endpoints have no `RequireManager`: `NotifyService` calls + `canRequestSign()` inside the action, `NotifyController::sendNotification()` + rethrows, and `afterException` serializes both bodies (a JSON message becomes + `{action, errors}`, a plain one `{message}`); - 7 error bodies (six 401 and the footer-template 403): an envelope `anyOf` whose second branch has an untyped `data: {}`. Cause confirmed: for every non-public OCS method the extractor adds an implicit 401 with an untyped From f555833fd1924ffcab1db0c2095a9a26c0f07942 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 12:16:31 -0300 Subject: [PATCH 09/14] fix(openapi): build the admin background response with its documented headers Psalm rejects the `@return` added for the literal `image/png` media type because `new FileDisplayResponse($file)` is inferred with empty headers. Pass the headers to the constructor, as CertificatePolicyController already does, and drop the redundant addHeader calls (the same keys are sent at the end). Cover the headers with a unit test. Signed-off-by: Luis Amorim --- lib/Controller/AdminController.php | 8 ++++---- .../Unit/Controller/AdminControllerTest.php | 20 +++++++++++++++++-- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/lib/Controller/AdminController.php b/lib/Controller/AdminController.php index 242dd8e6da..e2ef9fd065 100644 --- a/lib/Controller/AdminController.php +++ b/lib/Controller/AdminController.php @@ -346,14 +346,14 @@ public function signatureBackgroundSave(): DataResponse { public function signatureBackgroundGet(): FileDisplayResponse { $file = $this->signatureBackgroundService->getImage(); - $response = new FileDisplayResponse($file); + $response = new FileDisplayResponse($file, Http::STATUS_OK, [ + 'Content-Disposition' => 'attachment; filename="background.png"', + 'Content-Type' => 'image/png', + ]); $csp = new ContentSecurityPolicy(); $csp->allowInlineStyle(); $response->setContentSecurityPolicy($csp); $response->cacheFor(3600); - $response->addHeader('Content-Type', 'image/png'); - $response->addHeader('Content-Disposition', 'attachment; filename="background.png"'); - $response->addHeader('Content-Type', 'image/png'); return $response; } diff --git a/tests/php/Unit/Controller/AdminControllerTest.php b/tests/php/Unit/Controller/AdminControllerTest.php index 765a547bbe..c807026598 100644 --- a/tests/php/Unit/Controller/AdminControllerTest.php +++ b/tests/php/Unit/Controller/AdminControllerTest.php @@ -20,6 +20,7 @@ use OCA\Libresign\Service\SetupCheckResultService; use OCA\Libresign\Service\SignatureBackgroundService; use OCP\AppFramework\Http; +use OCP\Files\SimpleFS\ISimpleFile; use OCP\IAppConfig; use OCP\IEventSource; use OCP\IEventSourceFactory; @@ -32,6 +33,7 @@ class AdminControllerTest extends TestCase { private AdminController $controller; private ActiveSigningsService&MockObject $activeSigningsService; + private SignatureBackgroundService&MockObject $signatureBackgroundService; private IRequest&MockObject $request; protected function setUp(): void { @@ -42,7 +44,7 @@ protected function setUp(): void { $eventSourceFactory = $this->createMock(IEventSourceFactory::class); $l10n = $this->createMock(IL10N::class); $session = $this->createMock(ISession::class); - $signatureBackgroundService = $this->createMock(SignatureBackgroundService::class); + $this->signatureBackgroundService = $this->createMock(SignatureBackgroundService::class); $certificatePolicyService = $this->createMock(CertificatePolicyService::class); $validateService = $this->createMock(ValidateService::class); $identifyMethodService = $this->createMock(IdentifyMethodService::class); @@ -64,7 +66,7 @@ protected function setUp(): void { $eventSourceFactory, $l10n, $session, - $signatureBackgroundService, + $this->signatureBackgroundService, $certificatePolicyService, $validateService, $identifyMethodService, @@ -114,4 +116,18 @@ public function testGetActiveSigningsReturnsErrorResponseWhenServiceFails(): voi $this->assertSame(Http::STATUS_INTERNAL_SERVER_ERROR, $response->getStatus()); $this->assertSame(['error' => 'boom'], $response->getData()); } + + public function testSignatureBackgroundGetSendsTheDocumentedHeaders(): void { + $this->signatureBackgroundService + ->expects($this->once()) + ->method('getImage') + ->willReturn($this->createMock(ISimpleFile::class)); + + $response = $this->controller->signatureBackgroundGet(); + + $this->assertSame(Http::STATUS_OK, $response->getStatus()); + $headers = $response->getHeaders(); + $this->assertSame('image/png', $headers['Content-Type']); + $this->assertSame('attachment; filename="background.png"', $headers['Content-Disposition']); + } } From 2df4f5a4e7771c0b45ee2294a0419144e07fa8b5 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 12:29:56 -0300 Subject: [PATCH 10/14] fix(openapi): keep the attachment disposition of the admin background The previous commit moved the headers to the FileDisplayResponse constructor and dropped the addHeader calls, but the constructor always sets Content-Disposition to "inline" with the file name, so the response lost its `attachment; filename="background.png"` disposition. The unit test added there caught it. Keep the headers in the constructor, which lets Psalm infer the documented shape, and set the disposition again after construction. Signed-off-by: Luis Amorim --- lib/Controller/AdminController.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/Controller/AdminController.php b/lib/Controller/AdminController.php index e2ef9fd065..b6463cb242 100644 --- a/lib/Controller/AdminController.php +++ b/lib/Controller/AdminController.php @@ -350,6 +350,9 @@ public function signatureBackgroundGet(): FileDisplayResponse { 'Content-Disposition' => 'attachment; filename="background.png"', 'Content-Type' => 'image/png', ]); + // The constructor always sets Content-Disposition to "inline" using the + // file name, so the attachment disposition must be set again afterwards. + $response->addHeader('Content-Disposition', 'attachment; filename="background.png"'); $csp = new ContentSecurityPolicy(); $csp->allowInlineStyle(); $response->setContentSecurityPolicy($csp); From 106c6f9a17df22b9b6733bcb929e4be2078628e5 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 15:56:57 -0300 Subject: [PATCH 11/14] fix(api)!: answer failures with 422 or 500 instead of 401 Six operations answered HTTP 401 for failures that are not authentication failures: POST account/signature, POST admin/certificate/openssl and cfssl, DELETE file/file_id/{fileId}, DELETE sign/file_id/{fileId} and DELETE sign/file_id/{fileId}/{signRequestId}. A 401 means "not authenticated", so a client could not tell an invalid session from "Parameter 'CN' is required!" or from a closed signing workflow, which the neighbouring notify and sign endpoints already answer with 422. - a LibresignException (and an InvalidArgumentException in the PFX and certificate generators) is now 422 with the same `{message}` body; - any other failure these methods already caught is now 500 with the same `{message}` body; - removeSigner answers 422 for every LibresignException, not only for code 422; - the real authentication failure stays the framework's 401. The OpenAPI contract is regenerated: the explicit 401 bodies are gone (six `anyOf` fewer), and deleteFile and deleteSignatureRequest document the 422 `MessageResponse|ActionErrorResponse` union plus the 500. Behat scenarios, the API test and the frontend type of removeSigner follow, and unit tests cover each status. BREAKING CHANGE: the operations above no longer answer 401 for validation or business failures; clients that treated 401 as "the operation failed" must handle 422 and 500. Signed-off-by: Luis Amorim --- lib/Controller/AccountController.php | 9 +- lib/Controller/AdminController.php | 20 +- lib/Controller/FileController.php | 8 +- lib/Controller/RequestSignatureController.php | 15 +- openapi-administration.json | 206 +++--- openapi-full.json | 592 ++++++++++-------- openapi.json | 344 +++++----- .../RightSidebar/RequestSignatureTab.vue | 4 +- src/types/openapi/openapi-administration.ts | 70 ++- src/types/openapi/openapi-full.ts | 152 +++-- src/types/openapi/openapi.ts | 82 ++- .../admin/certificate_openssl.feature | 8 +- .../integration/features/sign/reject.feature | 2 +- .../Api/Controller/AdminControllerTest.php | 2 +- ...AccountControllerSignatureGenerateTest.php | 71 +++ .../Unit/Controller/AdminControllerTest.php | 54 +- .../Controller/FileControllerDeleteTest.php | 74 +++ .../RequestSignatureControllerTest.php | 39 ++ .../openapi/OpenApiErrorBodyContractTest.php | 56 +- 19 files changed, 1218 insertions(+), 590 deletions(-) create mode 100644 tests/php/Unit/Controller/AccountControllerSignatureGenerateTest.php create mode 100644 tests/php/Unit/Controller/FileControllerDeleteTest.php diff --git a/lib/Controller/AccountController.php b/lib/Controller/AccountController.php index 17f330f145..9c90ade9a6 100644 --- a/lib/Controller/AccountController.php +++ b/lib/Controller/AccountController.php @@ -142,10 +142,11 @@ public function createToSign(string $uuid, string $email, string $password, ?str * * @param string $signPassword The password that will be used to encrypt the certificate file * - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: Settings saved - * 401: Failure to create PFX file + * 422: Invalid data to create the PFX file + * 500: Failure to create PFX file */ #[NoAdminRequired] #[NoCSRFRequired] @@ -185,7 +186,9 @@ public function signatureGenerate( [ 'message' => $exception->getMessage() ], - Http::STATUS_UNAUTHORIZED + $exception instanceof LibresignException || $exception instanceof InvalidArgumentException + ? Http::STATUS_UNPROCESSABLE_ENTITY + : Http::STATUS_INTERNAL_SERVER_ERROR, ); } } diff --git a/lib/Controller/AdminController.php b/lib/Controller/AdminController.php index b6463cb242..5573acea4c 100644 --- a/lib/Controller/AdminController.php +++ b/lib/Controller/AdminController.php @@ -8,8 +8,10 @@ namespace OCA\Libresign\Controller; +use InvalidArgumentException; use OCA\Libresign\AppInfo\Application; use OCA\Libresign\Controller\Traits\UploadValidator; +use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory; use OCA\Libresign\Handler\CertificateEngine\IEngineHandler; use OCA\Libresign\Service\ActiveSigningsService; @@ -83,10 +85,11 @@ public function __construct( * @param array{commonName: string, names: array}>} $rootCert fields of root certificate * @param string $cfsslUri URI of CFSSL API * @param string $configPath Path of config files of CFSSL - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: OK - * 401: Account not found + * 422: Invalid certificate data + * 500: Failure to generate the certificate */ #[NoCSRFRequired] #[OpenAPI(tags: ['certificates'])] @@ -110,7 +113,9 @@ public function generateCertificateCfssl( [ 'message' => $exception->getMessage() ], - Http::STATUS_UNAUTHORIZED + $exception instanceof LibresignException || $exception instanceof InvalidArgumentException + ? Http::STATUS_UNPROCESSABLE_ENTITY + : Http::STATUS_INTERNAL_SERVER_ERROR, ); } } @@ -120,10 +125,11 @@ public function generateCertificateCfssl( * * @param array{commonName: string, names: array}>} $rootCert fields of root certificate * @param string $configPath Path of config files of CFSSL - * @return DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: OK - * 401: Account not found + * 422: Invalid certificate data + * 500: Failure to generate the certificate */ #[NoCSRFRequired] #[OpenAPI(tags: ['certificates'])] @@ -145,7 +151,9 @@ public function generateCertificateOpenSsl( [ 'message' => $exception->getMessage() ], - Http::STATUS_UNAUTHORIZED + $exception instanceof LibresignException || $exception instanceof InvalidArgumentException + ? Http::STATUS_UNPROCESSABLE_ENTITY + : Http::STATUS_INTERNAL_SERVER_ERROR, ); } } diff --git a/lib/Controller/FileController.php b/lib/Controller/FileController.php index 87cfb02b62..4871d6d8ba 100644 --- a/lib/Controller/FileController.php +++ b/lib/Controller/FileController.php @@ -887,11 +887,11 @@ private function extractFileName(array $fileData): string { * * @param integer $fileId LibreSign file ID * @param boolean $deleteFile Whether to delete the physical file from Nextcloud (default: true) - * @return DataResponse|DataResponse|DataResponse + * @return DataResponse|DataResponse|DataResponse * * 200: OK - * 401: Failed * 422: Failed + * 500: Unexpected failure */ #[NoAdminRequired] #[NoCSRFRequired] @@ -913,7 +913,9 @@ public function deleteFile(int $fileId, bool $deleteFile = true): DataResponse { [ 'message' => $th->getMessage(), ], - Http::STATUS_UNAUTHORIZED + $th instanceof LibresignException + ? Http::STATUS_UNPROCESSABLE_ENTITY + : Http::STATUS_INTERNAL_SERVER_ERROR, ); } return new DataResponse( diff --git a/lib/Controller/RequestSignatureController.php b/lib/Controller/RequestSignatureController.php index f1316e1665..c15d361e15 100644 --- a/lib/Controller/RequestSignatureController.php +++ b/lib/Controller/RequestSignatureController.php @@ -212,10 +212,9 @@ public function updateSignatureRequest( * * @param integer $fileId LibreSign file ID * @param integer $signRequestId The sign request id - * @return DataResponse|DataResponse|DataResponse + * @return DataResponse|DataResponse * * 200: OK - * 401: Failed * 422: Failed */ #[NoAdminRequired] @@ -238,9 +237,7 @@ public function removeSigner(int $fileId, int $signRequestId): DataResponse { } catch (LibresignException $e) { return new DataResponse( ['message' => $e->getMessage()], - $e->getCode() === Http::STATUS_UNPROCESSABLE_ENTITY - ? Http::STATUS_UNPROCESSABLE_ENTITY - : Http::STATUS_UNAUTHORIZED, + Http::STATUS_UNPROCESSABLE_ENTITY, ); } return new DataResponse( @@ -258,11 +255,11 @@ public function removeSigner(int $fileId, int $signRequestId): DataResponse { * You can only request exclusion as any sign * * @param integer $fileId LibreSign file ID - * @return DataResponse|DataResponse|DataResponse + * @return DataResponse|DataResponse|DataResponse * * 200: OK - * 401: Failed * 422: Failed + * 500: Unexpected failure */ #[NoAdminRequired] #[NoCSRFRequired] @@ -284,7 +281,9 @@ public function deleteSignatureRequest(int $fileId): DataResponse { [ 'message' => $th->getMessage(), ], - Http::STATUS_UNAUTHORIZED + $th instanceof LibresignException + ? Http::STATUS_UNPROCESSABLE_ENTITY + : Http::STATUS_INTERNAL_SERVER_ERROR, ); } return new DataResponse( diff --git a/openapi-administration.json b/openapi-administration.json index f699fd9c72..06464c5649 100644 --- a/openapi-administration.json +++ b/openapi-administration.json @@ -1073,57 +1073,90 @@ } } }, - "401": { - "description": "Account not found", + "422": { + "description": "Invalid certificate data", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/MessageResponse" - } - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } - }, - { + } + } + } + } + } + }, + "500": { + "description": "Failure to generate the certificate", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": {} - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } } - ] + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } } } } @@ -1287,57 +1320,90 @@ } } }, - "401": { - "description": "Account not found", + "422": { + "description": "Invalid certificate data", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/MessageResponse" - } - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } - }, - { + } + } + } + } + } + }, + "500": { + "description": "Failure to generate the certificate", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": {} - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } } - ] + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } } } } diff --git a/openapi-full.json b/openapi-full.json index b374e9aba7..e55ffa503e 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -4586,57 +4586,90 @@ } } }, - "401": { - "description": "Failure to create PFX file", + "422": { + "description": "Invalid data to create the PFX file", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/MessageResponse" - } - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } - }, - { + } + } + } + } + } + }, + "500": { + "description": "Failure to create PFX file", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": {} - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } } - ] + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } } } } @@ -7229,63 +7262,75 @@ } } }, - "401": { + "422": { "description": "Failed", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "anyOf": [ + { "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" } - } + ] } } - }, - { + } + } + } + } + } + }, + "500": { + "description": "Unexpected failure", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": {} - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } } - ] + } } } } }, - "422": { - "description": "Failed", + "401": { + "description": "Current user is not logged in", "content": { "application/json": { "schema": { @@ -7304,9 +7349,7 @@ "meta": { "$ref": "#/components/schemas/OCSMeta" }, - "data": { - "$ref": "#/components/schemas/ActionErrorResponse" - } + "data": {} } } } @@ -12778,61 +12821,6 @@ } } }, - "401": { - "description": "Failed", - "content": { - "application/json": { - "schema": { - "anyOf": [ - { - "type": "object", - "required": [ - "ocs" - ], - "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/MessageResponse" - } - } - } - } - }, - { - "type": "object", - "required": [ - "ocs" - ], - "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": {} - } - } - } - } - ] - } - } - } - }, "422": { "description": "Failed", "content": { @@ -12869,23 +12857,51 @@ } } } - } - } - } - }, - "/ocs/v2.php/apps/libresign/api/{apiVersion}/sign/file_id/{fileId}": { - "delete": { - "operationId": "request_signature-delete-signature-request", - "summary": "Delete sign request", - "description": "You can only request exclusion as any sign", - "tags": [ - "requests" - ], - "security": [ - { - "bearer_auth": [] }, - { + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } + } + } + } + } + } + } + }, + "/ocs/v2.php/apps/libresign/api/{apiVersion}/sign/file_id/{fileId}": { + "delete": { + "operationId": "request_signature-delete-signature-request", + "summary": "Delete sign request", + "description": "You can only request exclusion as any sign", + "tags": [ + "requests" + ], + "security": [ + { + "bearer_auth": [] + }, + { "basic_auth": [] } ], @@ -12954,63 +12970,75 @@ } } }, - "401": { + "422": { "description": "Failed", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "anyOf": [ + { "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" } - } + ] } } - }, - { + } + } + } + } + } + }, + "500": { + "description": "Unexpected failure", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": {} - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } } - ] + } } } } }, - "422": { - "description": "Failed", + "401": { + "description": "Current user is not logged in", "content": { "application/json": { "schema": { @@ -13029,9 +13057,7 @@ "meta": { "$ref": "#/components/schemas/OCSMeta" }, - "data": { - "$ref": "#/components/schemas/ActionErrorResponse" - } + "data": {} } } } @@ -15262,57 +15288,90 @@ } } }, - "401": { - "description": "Account not found", + "422": { + "description": "Invalid certificate data", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/MessageResponse" - } - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } - }, - { + } + } + } + } + } + }, + "500": { + "description": "Failure to generate the certificate", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": {} - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } } - ] + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } } } } @@ -15476,57 +15535,90 @@ } } }, - "401": { - "description": "Account not found", + "422": { + "description": "Invalid certificate data", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/MessageResponse" - } - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } - }, - { + } + } + } + } + } + }, + "500": { + "description": "Failure to generate the certificate", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": {} - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } } - ] + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } } } } diff --git a/openapi.json b/openapi.json index 288494d135..241926ff8d 100644 --- a/openapi.json +++ b/openapi.json @@ -4044,57 +4044,90 @@ } } }, - "401": { - "description": "Failure to create PFX file", + "422": { + "description": "Invalid data to create the PFX file", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { - "$ref": "#/components/schemas/MessageResponse" - } - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } - }, - { + } + } + } + } + } + }, + "500": { + "description": "Failure to create PFX file", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": {} - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } } - ] + } + } + } + } + }, + "401": { + "description": "Current user is not logged in", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { + "type": "object", + "required": [ + "meta", + "data" + ], + "properties": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": {} + } + } + } } } } @@ -6687,63 +6720,75 @@ } } }, - "401": { + "422": { "description": "Failed", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "anyOf": [ + { "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" } - } + ] } } - }, - { + } + } + } + } + } + }, + "500": { + "description": "Unexpected failure", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": {} - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } } - ] + } } } } }, - "422": { - "description": "Failed", + "401": { + "description": "Current user is not logged in", "content": { "application/json": { "schema": { @@ -6762,9 +6807,7 @@ "meta": { "$ref": "#/components/schemas/OCSMeta" }, - "data": { - "$ref": "#/components/schemas/ActionErrorResponse" - } + "data": {} } } } @@ -12041,63 +12084,45 @@ } } }, - "401": { + "422": { "description": "Failed", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "anyOf": [ + { "$ref": "#/components/schemas/MessageResponse" - } - } - } - } - }, - { - "type": "object", - "required": [ - "ocs" - ], - "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" }, - "data": {} - } + { + "$ref": "#/components/schemas/ActionErrorResponse" + } + ] } } } - ] + } } } } }, - "422": { - "description": "Failed", + "401": { + "description": "Current user is not logged in", "content": { "application/json": { "schema": { @@ -12116,16 +12141,7 @@ "meta": { "$ref": "#/components/schemas/OCSMeta" }, - "data": { - "anyOf": [ - { - "$ref": "#/components/schemas/MessageResponse" - }, - { - "$ref": "#/components/schemas/ActionErrorResponse" - } - ] - } + "data": {} } } } @@ -12217,63 +12233,75 @@ } } }, - "401": { + "422": { "description": "Failed", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": { + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "anyOf": [ + { "$ref": "#/components/schemas/MessageResponse" + }, + { + "$ref": "#/components/schemas/ActionErrorResponse" } - } + ] } } - }, - { + } + } + } + } + } + }, + "500": { + "description": "Unexpected failure", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "ocs" + ], + "properties": { + "ocs": { "type": "object", "required": [ - "ocs" + "meta", + "data" ], "properties": { - "ocs": { - "type": "object", - "required": [ - "meta", - "data" - ], - "properties": { - "meta": { - "$ref": "#/components/schemas/OCSMeta" - }, - "data": {} - } + "meta": { + "$ref": "#/components/schemas/OCSMeta" + }, + "data": { + "$ref": "#/components/schemas/MessageResponse" } } } - ] + } } } } }, - "422": { - "description": "Failed", + "401": { + "description": "Current user is not logged in", "content": { "application/json": { "schema": { @@ -12292,9 +12320,7 @@ "meta": { "$ref": "#/components/schemas/OCSMeta" }, - "data": { - "$ref": "#/components/schemas/ActionErrorResponse" - } + "data": {} } } } diff --git a/src/components/RightSidebar/RequestSignatureTab.vue b/src/components/RightSidebar/RequestSignatureTab.vue index 645211128b..8b33b456a2 100644 --- a/src/components/RightSidebar/RequestSignatureTab.vue +++ b/src/components/RightSidebar/RequestSignatureTab.vue @@ -595,9 +595,7 @@ type PollingStatusData = { } type RequestSignatureErrorData = operations['request_signature-request-signature']['responses'][422]['content']['application/json']['ocs']['data'] type UpdateSignatureErrorData = operations['request_signature-update-signature-request']['responses'][422]['content']['application/json']['ocs']['data'] -type DeleteRequestSignatureErrorData - = | operations['request_signature-remove-signer']['responses'][401]['content']['application/json']['ocs']['data'] - | operations['request_signature-remove-signer']['responses'][422]['content']['application/json']['ocs']['data'] +type DeleteRequestSignatureErrorData = operations['request_signature-remove-signer']['responses'][422]['content']['application/json']['ocs']['data'] type NotifySignerErrorData = operations['notify-signer']['responses'][422 | 502 | 500]['content']['application/json']['ocs']['data'] type NotifySignerSuccess = operations['notify-signer']['responses'][200]['content']['application/json'] type OcsErrorData = RequestSignatureErrorData | UpdateSignatureErrorData | DeleteRequestSignatureErrorData | NotifySignerErrorData diff --git a/src/types/openapi/openapi-administration.ts b/src/types/openapi/openapi-administration.ts index 29e2778155..035a97f3e2 100644 --- a/src/types/openapi/openapi-administration.ts +++ b/src/types/openapi/openapi-administration.ts @@ -655,18 +655,13 @@ export interface operations { }; }; }; - /** @description Account not found */ + /** @description Current user is not logged in */ 401: { headers: { [name: string]: unknown; }; content: { "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; - }; - } | { ocs: { meta: components["schemas"]["OCSMeta"]; data: unknown; @@ -688,6 +683,34 @@ export interface operations { }; }; }; + /** @description Invalid certificate data */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; + }; + }; + }; + }; + /** @description Failure to generate the certificate */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; + }; + }; + }; + }; }; }; "admin-generate-certificate-open-ssl": { @@ -737,18 +760,13 @@ export interface operations { }; }; }; - /** @description Account not found */ + /** @description Current user is not logged in */ 401: { headers: { [name: string]: unknown; }; content: { "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; - }; - } | { ocs: { meta: components["schemas"]["OCSMeta"]; data: unknown; @@ -770,6 +788,34 @@ export interface operations { }; }; }; + /** @description Invalid certificate data */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; + }; + }; + }; + }; + /** @description Failure to generate the certificate */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; + }; + }; + }; + }; }; }; "admin-set-certificate-engine": { diff --git a/src/types/openapi/openapi-full.ts b/src/types/openapi/openapi-full.ts index 5308b2d464..044222108c 100644 --- a/src/types/openapi/openapi-full.ts +++ b/src/types/openapi/openapi-full.ts @@ -2703,8 +2703,22 @@ export interface operations { }; }; }; - /** @description Failure to create PFX file */ + /** @description Current user is not logged in */ 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: unknown; + }; + }; + }; + }; + /** @description Invalid data to create the PFX file */ + 422: { headers: { [name: string]: unknown; }; @@ -2714,10 +2728,19 @@ export interface operations { meta: components["schemas"]["OCSMeta"]; data: components["schemas"]["MessageResponse"]; }; - } | { + }; + }; + }; + /** @description Failure to create PFX file */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: unknown; + data: components["schemas"]["MessageResponse"]; }; }; }; @@ -3796,18 +3819,13 @@ export interface operations { }; }; }; - /** @description Failed */ + /** @description Current user is not logged in */ 401: { headers: { [name: string]: unknown; }; content: { "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; - }; - } | { ocs: { meta: components["schemas"]["OCSMeta"]; data: unknown; @@ -3824,7 +3842,21 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; + /** @description Unexpected failure */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; }; }; }; @@ -6200,18 +6232,13 @@ export interface operations { }; }; }; - /** @description Failed */ + /** @description Current user is not logged in */ 401: { headers: { [name: string]: unknown; }; content: { "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; - }; - } | { ocs: { meta: components["schemas"]["OCSMeta"]; data: unknown; @@ -6343,18 +6370,13 @@ export interface operations { }; }; }; - /** @description Failed */ + /** @description Current user is not logged in */ 401: { headers: { [name: string]: unknown; }; content: { "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; - }; - } | { ocs: { meta: components["schemas"]["OCSMeta"]; data: unknown; @@ -6371,7 +6393,21 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; + /** @description Unexpected failure */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; }; }; }; @@ -7291,18 +7327,13 @@ export interface operations { }; }; }; - /** @description Account not found */ + /** @description Current user is not logged in */ 401: { headers: { [name: string]: unknown; }; content: { "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; - }; - } | { ocs: { meta: components["schemas"]["OCSMeta"]; data: unknown; @@ -7324,6 +7355,34 @@ export interface operations { }; }; }; + /** @description Invalid certificate data */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; + }; + }; + }; + }; + /** @description Failure to generate the certificate */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; + }; + }; + }; + }; }; }; "admin-generate-certificate-open-ssl": { @@ -7373,18 +7432,13 @@ export interface operations { }; }; }; - /** @description Account not found */ + /** @description Current user is not logged in */ 401: { headers: { [name: string]: unknown; }; content: { "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; - }; - } | { ocs: { meta: components["schemas"]["OCSMeta"]; data: unknown; @@ -7406,6 +7460,34 @@ export interface operations { }; }; }; + /** @description Invalid certificate data */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; + }; + }; + }; + }; + /** @description Failure to generate the certificate */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; + }; + }; + }; + }; }; }; "admin-set-certificate-engine": { diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 3226ee12da..90aba62aa8 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -2235,8 +2235,22 @@ export interface operations { }; }; }; - /** @description Failure to create PFX file */ + /** @description Current user is not logged in */ 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: unknown; + }; + }; + }; + }; + /** @description Invalid data to create the PFX file */ + 422: { headers: { [name: string]: unknown; }; @@ -2246,10 +2260,19 @@ export interface operations { meta: components["schemas"]["OCSMeta"]; data: components["schemas"]["MessageResponse"]; }; - } | { + }; + }; + }; + /** @description Failure to create PFX file */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: unknown; + data: components["schemas"]["MessageResponse"]; }; }; }; @@ -3328,18 +3351,13 @@ export interface operations { }; }; }; - /** @description Failed */ + /** @description Current user is not logged in */ 401: { headers: { [name: string]: unknown; }; content: { "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; - }; - } | { ocs: { meta: components["schemas"]["OCSMeta"]; data: unknown; @@ -3356,7 +3374,21 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; + /** @description Unexpected failure */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; }; }; }; @@ -5638,18 +5670,13 @@ export interface operations { }; }; }; - /** @description Failed */ + /** @description Current user is not logged in */ 401: { headers: { [name: string]: unknown; }; content: { "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; - }; - } | { ocs: { meta: components["schemas"]["OCSMeta"]; data: unknown; @@ -5781,18 +5808,13 @@ export interface operations { }; }; }; - /** @description Failed */ + /** @description Current user is not logged in */ 401: { headers: { [name: string]: unknown; }; content: { "application/json": { - ocs: { - meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["MessageResponse"]; - }; - } | { ocs: { meta: components["schemas"]["OCSMeta"]; data: unknown; @@ -5809,7 +5831,21 @@ export interface operations { "application/json": { ocs: { meta: components["schemas"]["OCSMeta"]; - data: components["schemas"]["ActionErrorResponse"]; + data: components["schemas"]["MessageResponse"] | components["schemas"]["ActionErrorResponse"]; + }; + }; + }; + }; + /** @description Unexpected failure */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ocs: { + meta: components["schemas"]["OCSMeta"]; + data: components["schemas"]["MessageResponse"]; }; }; }; diff --git a/tests/integration/features/admin/certificate_openssl.feature b/tests/integration/features/admin/certificate_openssl.feature index 400e56ab3e..5b136adc11 100644 --- a/tests/integration/features/admin/certificate_openssl.feature +++ b/tests/integration/features/admin/certificate_openssl.feature @@ -18,7 +18,7 @@ Feature: admin/certificate_openssl Given as user "admin" When sending "post" to ocs "/apps/libresign/api/v1/admin/certificate/openssl" | rootCert | {"commonName":""} | - Then the response should have a status code 401 + Then the response should have a status code 422 And the response should be a JSON array with the following mandatory values | key | value | | (jq).ocs.data.message | Parameter 'CN' is required! | @@ -27,7 +27,7 @@ Feature: admin/certificate_openssl Given as user "admin" When sending "post" to ocs "/apps/libresign/api/v1/admin/certificate/openssl" | rootCert | {"commonName":"0123456789012345678901234567890123456789012345678901234567890123456789"} | - Then the response should have a status code 401 + Then the response should have a status code 422 And the response should be a JSON array with the following mandatory values | key | value | | (jq).ocs.data.message | Parameter 'CN' should be betweeen 1 and 64. | @@ -53,7 +53,7 @@ Feature: admin/certificate_openssl Given as user "admin" When sending "post" to ocs "/apps/libresign/api/v1/admin/certificate/openssl" | rootCert | {"commonName":"Common Name","names":[{"id": "C","value":"B"}]} | - Then the response should have a status code 401 + Then the response should have a status code 422 And the response should be a JSON array with the following mandatory values | key | value | | (jq).ocs.data.message | Parameter 'C' should be betweeen 2 and 2. | @@ -62,7 +62,7 @@ Feature: admin/certificate_openssl Given as user "admin" When sending "post" to ocs "/apps/libresign/api/v1/admin/certificate/openssl" | rootCert | {"commonName":"Common Name","names":[{"id": "C","value":"BRA"}]} | - Then the response should have a status code 401 + Then the response should have a status code 422 And the response should be a JSON array with the following mandatory values | key | value | | (jq).ocs.data.message | Parameter 'C' should be betweeen 2 and 2. | diff --git a/tests/integration/features/sign/reject.feature b/tests/integration/features/sign/reject.feature index 7b01172f1f..b4ef7fb3d3 100644 --- a/tests/integration/features/sign/reject.feature +++ b/tests/integration/features/sign/reject.feature @@ -884,7 +884,7 @@ Feature: sign-signature-rejection | key | value | | (jq).ocs.data.message | The signing workflow of this document is already closed. | When sending "delete" to ocs "/apps/libresign/api/v1/sign/file_id//" - Then the response should have a status code 401 + Then the response should have a status code 422 And the response should be a JSON array with the following mandatory values | key | value | | (jq).ocs.data.message | The signing workflow of this document is already closed. | diff --git a/tests/php/Api/Controller/AdminControllerTest.php b/tests/php/Api/Controller/AdminControllerTest.php index f85b20fa56..d052fdf1ec 100644 --- a/tests/php/Api/Controller/AdminControllerTest.php +++ b/tests/php/Api/Controller/AdminControllerTest.php @@ -50,7 +50,7 @@ public function testGenerateCertificateWithFailure():void { ], 'configPath' => '' ]) - ->expectStatus(401); + ->expectStatus(422); // Make and test request mach with schema $this->assertRequest(); diff --git a/tests/php/Unit/Controller/AccountControllerSignatureGenerateTest.php b/tests/php/Unit/Controller/AccountControllerSignatureGenerateTest.php new file mode 100644 index 0000000000..55f3ca787c --- /dev/null +++ b/tests/php/Unit/Controller/AccountControllerSignatureGenerateTest.php @@ -0,0 +1,71 @@ +accountService = $this->createMock(AccountService::class); + $this->pkcs12Handler = $this->createMock(Pkcs12Handler::class); + $user = $this->createMock(IUser::class); + $user->method('getEMailAddress')->willReturn('user@example.test'); + $user->method('getUID')->willReturn('user'); + $user->method('getDisplayName')->willReturn('User'); + $userSession = $this->createMock(IUserSession::class); + $userSession->method('getUser')->willReturn($user); + + $reflection = new ReflectionClass(AccountController::class); + $this->controller = $reflection->newInstanceWithoutConstructor(); + foreach ([ + 'accountService' => $this->accountService, + 'pkcs12Handler' => $this->pkcs12Handler, + 'userSession' => $userSession, + 'logger' => $this->createMock(LoggerInterface::class), + 'request' => $this->createMock(IRequest::class), + ] as $property => $value) { + $reflection->getProperty($property)->setValue($this->controller, $value); + } + } + + public static function failures(): array { + return [ + 'business failure' => [new LibresignException('Invalid password'), Http::STATUS_UNPROCESSABLE_ENTITY], + 'invalid argument' => [new \InvalidArgumentException('Invalid password'), Http::STATUS_UNPROCESSABLE_ENTITY], + 'unexpected failure' => [new \RuntimeException('openssl is unavailable'), Http::STATUS_INTERNAL_SERVER_ERROR], + ]; + } + + #[DataProvider('failures')] + public function testSignatureGenerateMapsTheFailureToItsStatus(\Throwable $failure, int $status): void { + $this->accountService->method('validateCertificateData')->willThrowException($failure); + + $response = $this->controller->signatureGenerate('secret'); + + $this->assertSame($status, $response->getStatus()); + $this->assertSame(['message' => $failure->getMessage()], $response->getData()); + } +} diff --git a/tests/php/Unit/Controller/AdminControllerTest.php b/tests/php/Unit/Controller/AdminControllerTest.php index c807026598..90f78315d8 100644 --- a/tests/php/Unit/Controller/AdminControllerTest.php +++ b/tests/php/Unit/Controller/AdminControllerTest.php @@ -9,6 +9,7 @@ namespace OCA\Libresign\Tests\Unit\Controller; use OCA\Libresign\Controller\AdminController; +use OCA\Libresign\Exception\LibresignException; use OCA\Libresign\Handler\CertificateEngine\CertificateEngineFactory; use OCA\Libresign\Service\ActiveSigningsService; use OCA\Libresign\Service\Certificate\ValidateService; @@ -27,6 +28,7 @@ use OCP\IL10N; use OCP\IRequest; use OCP\ISession; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -34,19 +36,21 @@ class AdminControllerTest extends TestCase { private AdminController $controller; private ActiveSigningsService&MockObject $activeSigningsService; private SignatureBackgroundService&MockObject $signatureBackgroundService; + private InstallService&MockObject $installService; + private ValidateService&MockObject $validateService; private IRequest&MockObject $request; protected function setUp(): void { $this->request = $this->createMock(IRequest::class); $appConfig = $this->createMock(IAppConfig::class); - $installService = $this->createMock(InstallService::class); + $this->installService = $this->createMock(InstallService::class); $certificateEngineFactory = $this->createMock(CertificateEngineFactory::class); $eventSourceFactory = $this->createMock(IEventSourceFactory::class); $l10n = $this->createMock(IL10N::class); $session = $this->createMock(ISession::class); $this->signatureBackgroundService = $this->createMock(SignatureBackgroundService::class); $certificatePolicyService = $this->createMock(CertificatePolicyService::class); - $validateService = $this->createMock(ValidateService::class); + $this->validateService = $this->createMock(ValidateService::class); $identifyMethodService = $this->createMock(IdentifyMethodService::class); $this->activeSigningsService = $this->createMock(ActiveSigningsService::class); $setupCheckResultService = $this->createMock(SetupCheckResultService::class); @@ -61,14 +65,14 @@ protected function setUp(): void { $this->controller = new AdminController( $this->request, $appConfig, - $installService, + $this->installService, $certificateEngineFactory, $eventSourceFactory, $l10n, $session, $this->signatureBackgroundService, $certificatePolicyService, - $validateService, + $this->validateService, $identifyMethodService, $this->activeSigningsService, $setupCheckResultService, @@ -117,6 +121,48 @@ public function testGetActiveSigningsReturnsErrorResponseWhenServiceFails(): voi $this->assertSame(['error' => 'boom'], $response->getData()); } + public static function certificateGenerators(): array { + return [ + 'openssl' => ['generateCertificateOpenSsl'], + 'cfssl' => ['generateCertificateCfssl'], + ]; + } + + #[DataProvider('certificateGenerators')] + public function testCertificateGenerationReportsInvalidInputAsUnprocessable(string $method): void { + $this->validateService + ->method('validate') + ->willThrowException(new \InvalidArgumentException("Parameter 'CN' is required!")); + + $response = $this->controller->$method(['commonName' => '']); + + $this->assertSame(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); + $this->assertSame(['message' => "Parameter 'CN' is required!"], $response->getData()); + } + + #[DataProvider('certificateGenerators')] + public function testCertificateGenerationReportsLibresignExceptionAsUnprocessable(string $method): void { + $this->installService + ->method('generate') + ->willThrowException(new LibresignException('Invalid configuration')); + + $response = $this->controller->$method(['commonName' => 'Common Name']); + + $this->assertSame(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); + } + + #[DataProvider('certificateGenerators')] + public function testCertificateGenerationReportsUnexpectedFailureAsServerError(string $method): void { + $this->installService + ->method('generate') + ->willThrowException(new \RuntimeException('openssl is unavailable')); + + $response = $this->controller->$method(['commonName' => 'Common Name']); + + $this->assertSame(Http::STATUS_INTERNAL_SERVER_ERROR, $response->getStatus()); + $this->assertSame(['message' => 'openssl is unavailable'], $response->getData()); + } + public function testSignatureBackgroundGetSendsTheDocumentedHeaders(): void { $this->signatureBackgroundService ->expects($this->once()) diff --git a/tests/php/Unit/Controller/FileControllerDeleteTest.php b/tests/php/Unit/Controller/FileControllerDeleteTest.php new file mode 100644 index 0000000000..f2a2100990 --- /dev/null +++ b/tests/php/Unit/Controller/FileControllerDeleteTest.php @@ -0,0 +1,74 @@ +validator = $this->createMock(SigningRequestValidator::class); + $this->fileService = $this->createMock(FileService::class); + $userSession = $this->createMock(IUserSession::class); + $userSession->method('getUser')->willReturn($this->createMock(IUser::class)); + $l10n = $this->createMock(IL10N::class); + $l10n->method('t')->willReturnCallback(static fn (string $message): string => $message); + + $reflection = new ReflectionClass(FileController::class); + $this->controller = $reflection->newInstanceWithoutConstructor(); + foreach ([ + 'signingRequestValidator' => $this->validator, + 'fileService' => $this->fileService, + 'userSession' => $userSession, + 'l10n' => $l10n, + ] as $property => $value) { + $reflection->getProperty($property)->setValue($this->controller, $value); + } + } + + public static function failures(): array { + return [ + 'business failure' => [new LibresignException('Invalid fileID'), Http::STATUS_UNPROCESSABLE_ENTITY], + 'unexpected failure' => [new \RuntimeException('database is gone'), Http::STATUS_INTERNAL_SERVER_ERROR], + ]; + } + + #[DataProvider('failures')] + public function testDeleteFileMapsTheFailureToItsStatus(\Throwable $failure, int $status): void { + $this->validator->method('validateExistingFile')->willThrowException($failure); + + $response = $this->controller->deleteFile(10); + + $this->assertSame($status, $response->getStatus()); + $this->assertSame(['message' => $failure->getMessage()], $response->getData()); + } + + public function testDeleteFileDoesNotReportTheFailureOfTheServiceAsUnauthorized(): void { + $this->fileService->method('delete')->willThrowException(new \RuntimeException('database is gone')); + + $response = $this->controller->deleteFile(10); + + $this->assertSame(Http::STATUS_INTERNAL_SERVER_ERROR, $response->getStatus()); + } +} diff --git a/tests/php/Unit/Controller/RequestSignatureControllerTest.php b/tests/php/Unit/Controller/RequestSignatureControllerTest.php index 237a05183a..dfcac03b9b 100644 --- a/tests/php/Unit/Controller/RequestSignatureControllerTest.php +++ b/tests/php/Unit/Controller/RequestSignatureControllerTest.php @@ -354,6 +354,45 @@ public function testUpdateSignStatusPropagation(?int $status, bool $expectStatus $this->assertSame(Http::STATUS_OK, $response->getStatus()); } + public static function libresignExceptionCodes(): array { + return [ + 'default code' => [0], + 'former unauthorized code' => [401], + 'unprocessable code' => [422], + ]; + } + + #[DataProvider('libresignExceptionCodes')] + public function testRemoveSignerReportsAnyLibresignExceptionAsUnprocessable(int $code): void { + $this->signingRequestValidator + ->method('validateExistingFile') + ->willThrowException(new LibresignException('The signing workflow of this document is already closed.', $code)); + + $response = $this->controller->removeSigner(10, 20); + + $this->assertSame(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); + $this->assertSame(['message' => 'The signing workflow of this document is already closed.'], $response->getData()); + } + + public static function deleteFailureScenarios(): array { + return [ + 'business failure' => [new LibresignException('Invalid fileID'), Http::STATUS_UNPROCESSABLE_ENTITY], + 'unexpected failure' => [new \RuntimeException('database is gone'), Http::STATUS_INTERNAL_SERVER_ERROR], + ]; + } + + #[DataProvider('deleteFailureScenarios')] + public function testDeleteSignatureRequestMapsTheFailureToItsStatus(\Throwable $failure, int $status): void { + $this->signingRequestValidator + ->method('validateExistingFile') + ->willThrowException($failure); + + $response = $this->controller->deleteSignatureRequest(10); + + $this->assertSame($status, $response->getStatus()); + $this->assertSame(['message' => $failure->getMessage()], $response->getData()); + } + public static function statusPayloadScenarios(): array { return [ 'null status is omitted' => [ diff --git a/tests/php/openapi/OpenApiErrorBodyContractTest.php b/tests/php/openapi/OpenApiErrorBodyContractTest.php index 638a44dfaa..dee5a309f1 100644 --- a/tests/php/openapi/OpenApiErrorBodyContractTest.php +++ b/tests/php/openapi/OpenApiErrorBodyContractTest.php @@ -52,17 +52,57 @@ public function testRemoveSignerDocumentsBothBodiesAt422(string $file): void { } #[DataProvider('specificationProvider')] - public function testDeleteOperationsDocumentTheMiddleware422(string $file): void { - // Their catch blocks answer 401, but the middleware rejects a user - // without permission with 422 before the method runs. + public function testDeleteOperationsDocumentBothBodiesAt422AndTheUnexpectedFailureAt500(string $file): void { + // The middleware rejects a user without permission with 422 before the + // method runs; the catch block answers {message} with 422 for a business + // failure and 500 for an unexpected one. $paths = $this->load($file)['paths']; foreach (['file/file_id/{fileId}', 'sign/file_id/{fileId}'] as $path) { - self::assertSame( - self::ACTION_ERROR, - $this->errorData($paths[self::BASE . $path]['delete'], '422')['$ref'] ?? null, - $path, - ); + $operation = $paths[self::BASE . $path]['delete']; + $this->assertBothBodies($operation, $path); + self::assertSame(self::MESSAGE, $this->errorData($operation, '500')['$ref'] ?? null, $path); + } + } + + #[DataProvider('specificationProvider')] + public function testFailuresAreNotDocumentedAsUnauthorized(string $file): void { + // 401 means "not authenticated". The operations below used to answer 401 + // for validation and business failures; only the untyped framework 401 + // (data: {}) may remain. + $paths = $this->load($file)['paths']; + $operations = [ + 'account/signature' => 'post', + 'file/file_id/{fileId}' => 'delete', + 'sign/file_id/{fileId}' => 'delete', + 'sign/file_id/{fileId}/{signRequestId}' => 'delete', + ]; + if ($file === 'openapi-full.json') { + $operations += ['admin/certificate/openssl' => 'post', 'admin/certificate/cfssl' => 'post']; + } + + foreach ($operations as $path => $method) { + $data = $this->errorData($paths[self::BASE . $path][$method], '401'); + self::assertArrayNotHasKey('$ref', $data, $path); + self::assertArrayNotHasKey('anyOf', $data, $path); + } + } + + #[DataProvider('specificationProvider')] + public function testPfxGenerationDocumentsItsFailures(string $file): void { + $operation = $this->load($file)['paths'][self::BASE . 'account/signature']['post']; + + self::assertSame(self::MESSAGE, $this->errorData($operation, '422')['$ref'] ?? null); + self::assertSame(self::MESSAGE, $this->errorData($operation, '500')['$ref'] ?? null); + } + + public function testCertificateGenerationDocumentsItsFailures(): void { + $paths = $this->load('openapi-full.json')['paths']; + + foreach (['admin/certificate/openssl', 'admin/certificate/cfssl'] as $path) { + $operation = $paths[self::BASE . $path]['post']; + self::assertSame(self::MESSAGE, $this->errorData($operation, '422')['$ref'] ?? null, $path); + self::assertSame(self::MESSAGE, $this->errorData($operation, '500')['$ref'] ?? null, $path); } } From ac896f252e33d2a0302febb677aede23dd97e15b Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 15:56:58 -0300 Subject: [PATCH 12/14] docs(sdk): record that failures are no longer reported as 401 Update the evaluation notes: the six envelope anyOf that came from the 401 of those operations are gone (17 became 13), the SHA-256 of the contract, and the decision about the 401 is now implemented instead of left open. Signed-off-by: Luis Amorim --- tests/sdk-generation/README.md | 2 +- tests/sdk-generation/REPORT.md | 57 ++++++++----- tests/sdk-generation/UPSTREAM-NOTES.md | 110 ++++++++++++------------- 3 files changed, 91 insertions(+), 78 deletions(-) diff --git a/tests/sdk-generation/README.md b/tests/sdk-generation/README.md index 350e536b42..240e9f6e84 100644 --- a/tests/sdk-generation/README.md +++ b/tests/sdk-generation/README.md @@ -42,7 +42,7 @@ See [REPORT.md](REPORT.md) and [inventory.md](inventory.md) for results. ## Normalized-input experiment -This separate experiment changes all 17 `anyOf` keywords to `oneOf` in a +This separate experiment changes all 13 `anyOf` keywords to `oneOf` in a **disposable generator input**, never in the committed specification: ```sh diff --git a/tests/sdk-generation/REPORT.md b/tests/sdk-generation/REPORT.md index 1494ec8d0f..384fb9d02f 100644 --- a/tests/sdk-generation/REPORT.md +++ b/tests/sdk-generation/REPORT.md @@ -15,9 +15,9 @@ keeps `| null` at the properties that reference it (disjoint `oneOf` contract, `@nextcloud/axios` injection all pass. The decision remains No-Go for unmodified input because three generated models -and seven merged 422 error-body models of the remaining 17 `anyOf` constructs -are still incorrect (the other seven, envelope 401/403 bodies, read the contract -faithfully; see [Remaining model defects](#remaining-model-defects)), and multipart +and nine merged 422 error-body models of the remaining 13 `anyOf` constructs +are still incorrect (the other one, the `footer-template` 403 envelope body, +reads the contract faithfully; see [Remaining model defects](#remaining-model-defects)), and multipart bodies are still absent from the contract. Every blocker left is on the extractor/generator side or needs a maintainer decision about the contract shape; see [UPSTREAM-NOTES.md](UPSTREAM-NOTES.md). This evaluation selects no @@ -34,7 +34,7 @@ type alias for the renamed schema and a type predicate in to `IdDocFile`, literal media types for the CRL and the admin background, and annotations aligned with what the code returns (see [Annotations aligned with the code](#annotations-aligned-with-the-code)). -- `openapi-full.json` SHA-256 with those changes: `b586418da879f0650b4e9ee4f9b0553c8cb3b72472c80cd998cf395491855387` +- `openapi-full.json` SHA-256 with those changes: `49410bb42e286791713e9ce3d36728875c2d36cf28f19998c8dfa4f3b0fcd343` (`64c52fa2ba243af292eba30055982954bfd8c19136567e50e28c4abcffcc9405` on `main`). - Extractor used to produce the contract: `nextcloud/openapi-extractor` 1.9.1. - Generator: `openapitools/openapi-generator-cli` 7.27.0 at @@ -106,10 +106,11 @@ soon as one of them fails (TS2578 or TS2322): | `FileRuntimeMetadata` | `anyOf` `ValidateMetadata`, `{ [key]: DynamicMetadataValue }` | only the `ValidateMetadata` fields, with `extension` and `p` required | a valid dynamic metadata object is rejected | | `RequestPolicyOverrides` values | `anyOf` `EffectivePolicyValue`, array of it | empty interface `RequestPolicyOverridesValue` | accepts any non-null value | -The other 14 `anyOf` occurrences are in 4xx bodies. Seven (the 422 responses of +The other 10 `anyOf` occurrences are in 4xx bodies. Nine (the 422 responses of `notify-signers`, `notify-signer`, `request-signature`, -`update-signature-request`, `removeSigner`, `file-save` and -`file-add-file-to-envelope`) are real unions of an +`update-signature-request`, `removeSigner`, `file-save`, +`file-add-file-to-envelope`, `deleteFile` and `deleteSignatureRequest`) are real +unions of an `{action, errors}` body (`ActionErrorResponse`, a `LibresignException` with a JSON message) and a `{message}` body (`MessageResponse`). For `request-signature` (POST and PATCH), `removeSigner`, `file-save` and @@ -122,10 +123,9 @@ exception and `afterException` serializes both bodies (JSON message as `{action, errors}`, plain message as `{message}`). The generator merges the alternatives into one interface (for example `NotifySigners422ResponseOcsData` requires `action` and `errors`, which the -`MessageResponse` alternative does not have). The other seven (six 401 bodies -and the `footer-template` 403) are envelope-level `anyOf` whose second branch -has an untyped `data: {}`; they are generated as `...AnyOf1Ocs` models with -`data: any`. That reads the contract faithfully: the extractor's implicit 401/403 +`MessageResponse` alternative does not have). The tenth, the `footer-template` +403, is an envelope-level `anyOf` whose second branch has an untyped +`data: {}`; it is generated as an `...AnyOf1Ocs` model with `data: any`. That reads the contract faithfully: the extractor's implicit 401/403 has no typed body, so `X | {}` accepts anything. The typed branch is not lost by the generator; the extractor adds the untyped one next to it. In both cases the generator creates models for error bodies but method return @@ -182,21 +182,34 @@ LibreSign annotations that did not match the data were corrected: block (`InjectionMiddleware.php`, `SigningRequestValidator.php`), so the original `ActionErrorResponse` documentation was kept. -Open decision for the maintainers, not changed here: several methods answer -HTTP 401 for failures that are not authentication failures. -`signatureGenerate`, the two certificate generators (`catch \Exception`), -`deleteFile` and `deleteSignatureRequest` (`catch \Throwable`) return 401 for -every caught failure, including validation and business errors, and -`removeSigner` returns 401 for any `LibresignException` whose code is not 422. -A 401 means "unauthenticated", so an SDK cannot tell an invalid session from a -business failure. Changing the status breaks compatibility and the Behat -scenarios, so it needs its own change. +### Failures no longer reported as 401 + +Six operations answered HTTP 401 for failures that are not authentication +failures: `account/signature` (POST), the two certificate generators +(`catch \Exception`), `deleteFile` and `deleteSignatureRequest` +(`catch \Throwable`), and `removeSigner` (any `LibresignException` whose code was +not 422). A 401 means "unauthenticated", so an SDK could not tell an invalid +session from "CN is required" or from a closed signing workflow, which the +neighbouring `notify` and `sign` endpoints already answered with 422. This is a +breaking change of the API: + +- a `LibresignException` (and an `InvalidArgumentException` in the PFX and + certificate generators) is now HTTP 422 with the same `{message}` body; +- any other failure that these methods already caught is now HTTP 500 with the + same `{message}` body (before, it was 401); +- the real authentication failure is still the framework's 401, now the only + one in those operations, and it is untyped (`data: {}`). + +Six of the former envelope `anyOf` disappeared with the explicit 401 +(17 became 13); `deleteFile` and `deleteSignatureRequest` gained the +`MessageResponse | ActionErrorResponse` 422 union, because the catch block and +the permission middleware answer different bodies. ## Normalized-input experiment `normalize-input.cjs` writes only `build/sdk-generation/normalized/openapi-full.oneof.json`, renaming the -remaining 17 `anyOf` keywords to `oneOf`. It generates +remaining 13 `anyOf` keywords to `oneOf`. It generates `FileListResponseDataInner = DetailedFile | FileSummary` and `FileRuntimeMetadata = ValidateMetadata | { [key: string]: ... }`, and `test:normalized` passes. It is generator-input normalization only: object @@ -240,7 +253,7 @@ the extractor support above (or another reviewed design) and a regeneration. Maintainers must choose among these options; this evaluation selects none: -1. Conditional Go with a reviewed generator-input normalization of the 17 +1. Conditional Go with a reviewed generator-input normalization of the 13 `anyOf` constructs, documented as non-contractual. 2. Fix the generator's `anyOf` merge and type the extractor's implicit 401/403 body upstream, and adjust LibreSign's own types or annotations where diff --git a/tests/sdk-generation/UPSTREAM-NOTES.md b/tests/sdk-generation/UPSTREAM-NOTES.md index 5183548c41..84aa1b6088 100644 --- a/tests/sdk-generation/UPSTREAM-NOTES.md +++ b/tests/sdk-generation/UPSTREAM-NOTES.md @@ -43,53 +43,53 @@ single and repeated files (not yet testable, see G5). As #9494 showed, the extractor emitted `oneOf` for the policy value once its scalar branches became disjoint. Unions that include objects or arrays (the policy-override one pairs a value with an array of values) are still emitted as `anyOf`, -and OpenAPI Generator mishandles them (G1). Affected schemas, 17 in total: +and OpenAPI Generator mishandles them (G1). Affected schemas, 13 in total: - `FileListResponse.data[]` items: `FileSummary | DetailedFile`; - `FileRuntimeMetadata`: `ValidateMetadata | array`; - `RequestPolicyOverrides` values: `EffectivePolicyValue | list`; -- 7 `422` bodies: `MessageResponse | ActionErrorResponse` (notify-signers, +- 9 `422` bodies: `MessageResponse | ActionErrorResponse` (notify-signers, notify-signer, request-signature, update-signature-request, `removeSigner`, - `file-save` and `file-add-file-to-envelope`). The union is real. The other - five get `{action, errors}` from `#[RequireManager]` (`canRequestSign()` runs - before the method; `afterException` serializes the `LibresignException`) and - `{message}` from a `DataResponse` built in their own `catch` blocks. The - notify endpoints have no `RequireManager`: `NotifyService` calls - `canRequestSign()` inside the action, `NotifyController::sendNotification()` - rethrows, and `afterException` serializes both bodies (a JSON message becomes - `{action, errors}`, a plain one `{message}`); -- 7 error bodies (six 401 and the footer-template 403): an envelope `anyOf` - whose second branch has an untyped `data: {}`. Cause confirmed: for every - non-public OCS method the extractor adds an implicit 401 with an untyped - `data`, and a 403 for admin methods (`ControllerMethod.php`, about lines - 414-440 in 1.9.1). The `anyOf` appears exactly when the controller also - declares that same status in its `@return` for a method that is not - `#[PublicPage]` (401) or not `#[NoAdminRequired]` (403). A scan of - `lib/Controller` finds exactly seven such methods, the same seven operations: - `AccountController::signatureGenerate`, - `AdminController::generateCertificateCfssl` and `generateCertificateOpenSsl`, - `FileController::deleteFile`, `FooterTemplateController::saveFooterTemplate` - (403), `RequestSignatureController::removeSigner` and `deleteSignatureRequest`. - Public methods that declare a 401 (for example `IdDocsController::delete`) - generate a single typed response, and the 82 other 401/403 responses have an - untyped `data: {}`, mostly the implicit ones (a few are explicit `list` - declarations, for example `FileController.php:138`). The explicit declarations describe what the code returns, so - removing them would only erase the typed body and leave `data: {}`. The - request to the extractor is therefore to give the implicit 401/403 a typed - body (or to let the controller refine it), not to let an explicit declaration - replace the implicit one: the implicit response models what the framework - sends (not verified here, Nextcloud's security middleware was not read), so - both bodies are plausible and `anyOf` is correct. The generator then produces - `data: any`, a faithful reading of `X | {}`. Separately, several of these - methods use 401 for failures that are not authentication failures, which is a - LibreSign decision (see "Left in LibreSign"). + `file-save`, `file-add-file-to-envelope`, `deleteFile` and + `deleteSignatureRequest`). The union is real. The notify endpoints have no + `RequireManager`: `NotifyService` calls `canRequestSign()` inside the action, + `NotifyController::sendNotification()` rethrows, and `afterException` + serializes both bodies (a JSON message becomes `{action, errors}`, a plain one + `{message}`). The other seven get `{action, errors}` from `#[RequireManager]` + (`canRequestSign()` runs before the method; `afterException` serializes the + `LibresignException`) and `{message}` from a `DataResponse` built in their own + `catch` blocks; +- 1 error body (the footer-template 403): an envelope `anyOf` whose second + branch has an untyped `data: {}`. Cause confirmed: for every non-public OCS + method the extractor adds an implicit 401 with an untyped `data`, and a 403 for + admin methods (`ControllerMethod.php`, about lines 414-440 in 1.9.1). The + `anyOf` appears exactly when the controller also declares that same status in + its `@return` for a method that is not `#[PublicPage]` (401) or not + `#[NoAdminRequired]` (403). Six more cases existed (the 401 of + `AccountController::signatureGenerate`, the two certificate generators, + `FileController::deleteFile`, `RequestSignatureController::removeSigner` and + `deleteSignatureRequest`), but there the LibreSign annotation was wrong: those + methods used 401 for failures that are not authentication failures. They now + answer 422 or 500, the explicit 401 is gone and so are those six `anyOf`. + `saveFooterTemplate` really answers 403 (`NoAdminRequired` is absent on + purpose: it writes the global template), so its two bodies coexist. Public + methods that declare a 401 (for example `IdDocsController::delete`) generate a + single typed response, and the other 401/403 responses have an untyped + `data: {}`, mostly the implicit ones (a few are explicit `list` + declarations, for example `FileController.php:138`). The request to the + extractor is to give the implicit 401/403 a typed body (or to let the + controller refine it), not to let an explicit declaration replace the implicit + one: the implicit response models what the framework sends (not verified here, + Nextcloud's security middleware was not read), so both bodies are plausible and + `anyOf` is correct. The generator then produces `data: any`, a faithful + reading of `X | {}`. For the object unions, `anyOf` is semantically correct: without `additionalProperties: false` an object carrying every key of two alternatives matches both (a detailed file can match both `FileSummary` and `DetailedFile`), so `oneOf` would be wrong. The defect is the generator's merge (G1), not the extractor's choice. Evidence: `npm run test:anyof` (`union-defects.ts`) and -`npm run test:normalized`, which renames the 17 keywords in a disposable copy +`npm run test:normalized`, which renames the 13 keywords in a disposable copy and passes. ### E3. `mixed` maps to `{ type: object }` @@ -138,13 +138,13 @@ The generated interface merges both alternatives and keeps required fields from one of them: `FileListResponseDataInner` requires `files`, `size` and `visibleElements` and narrows `nodeId` to `number`; `FileRuntimeMetadata` loses its dynamic branch; the `RequestPolicyOverridesValue` union becomes an empty -interface; the seven 422 bodies such as `NotifySigners422ResponseOcsData` require -`action` and `errors`, and the seven envelope `anyOf` bodies become `data: any`. Upstream status: `OpenAPITools/openapi-generator#8894` +interface; the nine 422 bodies such as `NotifySigners422ResponseOcsData` require +`action` and `errors`, and the footer-template 403 envelope body becomes `data: any`. Upstream status: `OpenAPITools/openapi-generator#8894` ("`anyOf` creates same interface as `allOf`", reported against 5.0.1) is open -and matches the merged-interface cases (`FileListResponseDataInner` and the seven +and matches the merged-interface cases (`FileListResponseDataInner` and the nine 422 bodies). It does not describe the lost dynamic branch of -`FileRuntimeMetadata`, the empty `RequestPolicyOverridesValue` or the seven -envelope cases, where the generator keeps `data: any`; those may need their own +`FileRuntimeMetadata`, the empty `RequestPolicyOverridesValue` or the +envelope case, where the generator keeps `data: any`; those may need their own reports. The fix was not tracked here. The earlier evaluation recorded the former `EffectivePolicyValue` defect, a different `anyOf` case, in both 7.15.0 and 7.27.0; the object cases above were checked only with 7.27.0. A union of two arrays (`list|list` as `anyOf`) becomes an empty interface (tested on a disposable spec copy). `oneOf` produces correct unions, so the choice is: fix the generator, add a @@ -158,8 +158,8 @@ success response. The SDK layer must expose typed access to `error.response.data` itself (for example through a wrapper or documented type guards). Do not assume this is unwrapped or typed automatically. The success types can also carry misleading names: `notifySigners` returns -`AxiosPromise`, a model deduplicated -from a 401 body that shares the 200 `MessageResponse` shape. If this matters for +`AxiosPromise`, a model named after the 422 +body of another operation, deduplicated against the 200 `MessageResponse` shape. If this matters for the public SDK surface, it needs naming control (for example `inlineSchemaNameMapping`), which was not tested. @@ -207,9 +207,18 @@ patched locally and no local extractor workaround is added; defects above are reported upstream. Anything whose cause is in LibreSign's own code is adjusted in LibreSign. Candidates, each needing its cause confirmed first: -- the 7 error bodies with an untyped `data: {}` (E2): investigated; the - controllers' explicit 401/403 declarations describe what the code returns, so - the untyped body is the extractor's and needs no LibreSign change; +- the six 401 error bodies of E2 (done, breaking change): they came from LibreSign + methods that answered 401 for failures that are not authentication failures. + `AccountController::signatureGenerate`, the `AdminController` certificate + generators, `FileController::deleteFile`, + `RequestSignatureController::deleteSignatureRequest` and `removeSigner` now + answer 422 for a `LibresignException` (and an `InvalidArgumentException` in the + PFX and certificate generators) and 500 for any other failure they already + caught, with the same `{message}` body. The framework's own 401 is the only one + left in those operations. Behat scenarios, the API test and the frontend type + of `removeSigner` were updated; +- the footer-template 403 (E2): the explicit 403 describes what the code returns, + so the untyped implicit body is the extractor's and needs no LibreSign change; - annotations that did not match the data (done): `removeSigner`, `file-save` and `file-add-file-to-envelope` now document `MessageResponse | ActionErrorResponse` for 422 (their `catch` answers `{message}`, the @@ -223,15 +232,6 @@ in LibreSign. Candidates, each needing its cause confirmed first: `{action, errors}` 422 before the method runs. `SignFileController::signByFileId` is public and documents `SignActionErrorResponse`, which accommodates that payload; unchanged; -- **open maintainer decision**: several methods answer HTTP 401 for failures - that are not authentication failures. `AccountController::signatureGenerate`, - the `AdminController` certificate generators (`catch \Exception`), - `FileController::deleteFile` and - `RequestSignatureController::deleteSignatureRequest` (`catch \Throwable`) - return 401 for every caught failure; `removeSigner` returns 401 for a - `LibresignException` whose code is not 422. Moving business failures to - 422/400 is a compatibility-breaking change that needs its own change and - Behat updates; not done here; - `DetailedFile.policySnapshotFrozen` is declared required, but `formatSingleFileData` omits it without a user (`FileListService.php:273-275`) while `formatFileWithChildren` always sets it (`:881`); not changed because it From c24b78feca25d4cf39c4a216ec22bd760e026ea6 Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 17:49:15 -0300 Subject: [PATCH 13/14] test(account): import Pkcs12Handler from SignEngine namespace The signature generate test imported OCA\Libresign\Handler\Pkcs12Handler, which does not exist, so createMock() threw UnknownTypeException for every data set. The class lives in OCA\Libresign\Handler\SignEngine. Signed-off-by: Luis Amorim --- .../Unit/Controller/AccountControllerSignatureGenerateTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/php/Unit/Controller/AccountControllerSignatureGenerateTest.php b/tests/php/Unit/Controller/AccountControllerSignatureGenerateTest.php index 55f3ca787c..11bb9c1f60 100644 --- a/tests/php/Unit/Controller/AccountControllerSignatureGenerateTest.php +++ b/tests/php/Unit/Controller/AccountControllerSignatureGenerateTest.php @@ -11,7 +11,7 @@ use OCA\Libresign\Controller\AccountController; use OCA\Libresign\Exception\LibresignException; -use OCA\Libresign\Handler\Pkcs12Handler; +use OCA\Libresign\Handler\SignEngine\Pkcs12Handler; use OCA\Libresign\Service\AccountService; use OCP\AppFramework\Http; use OCP\IRequest; From 54423748ee1dee1ba3ddc2ea0871a4de37ccbe4b Mon Sep 17 00:00:00 2001 From: Luis Amorim Date: Tue, 17 Nov 2026 17:55:44 -0300 Subject: [PATCH 14/14] test(api): expect 422 for sign failure responses POST /account/signature and DELETE /sign/file_id/{fileId} now return 422 for business failures, and the OpenAPI contract declares it. Update the two API tests that still expected 401. Signed-off-by: Luis Amorim --- tests/php/Api/Controller/SignFileControllerTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/php/Api/Controller/SignFileControllerTest.php b/tests/php/Api/Controller/SignFileControllerTest.php index 0cb84e3101..6c8ddde26b 100644 --- a/tests/php/Api/Controller/SignFileControllerTest.php +++ b/tests/php/Api/Controller/SignFileControllerTest.php @@ -256,7 +256,7 @@ public function testAccountSignatureEndpointWithFailure():void { 'signPassword' => '' ]) ->withPath('/api/v1/account/signature') - ->expectStatus(401); + ->expectStatus(422); $this->assertRequest(); } @@ -373,7 +373,7 @@ public function testDeleteUsingSignFileIdWithInvalidFile():void { 'Authorization' => 'Basic ' . base64_encode('username:password') ]) ->withPath('/api/v1/sign/file_id/171') - ->expectStatus(401); + ->expectStatus(422); $this->assertRequest(); }