Skip to content

Fix/api failure status codes - #9532

Draft
lfals wants to merge 15 commits into
LibreSign:mainfrom
lfals:fix/api-failure-status-codes
Draft

lfals wants to merge 15 commits into
LibreSign:mainfrom
lfals:fix/api-failure-status-codes

Conversation

@lfals

@lfals lfals commented Nov 17, 2026

Copy link
Copy Markdown

Related: #9087

📝 Summary

Aligns the OpenAPI contract with what the controllers actually return, so a generated SDK (#9087, typescript-axios) gets truthful types. Nothing in vendor/, vendor-bin/ or the generator is patched; defects whose cause is in the extractor or the generator are only recorded in tests/sdk-generation/UPSTREAM-NOTES.md.

Contract fixes (LibreSign side)

  • 422 bodies are documented as MessageResponse | ActionErrorResponse where both are really sent: #[RequireManager] / canRequestSign() answers {action, errors} before the method runs, and the method's own catch answers {message}. Affected: request-signature, update-signature-request, removeSigner, deleteFile, deleteSignatureRequest, file-save, file-add-file-to-envelope, notify endpoints; identify-account/search documents the middleware 422.
  • nodeId is nullable in DetailedFile, ValidatedFile and ValidatedChildFile, like the database column.
  • The schema File is renamed to IdDocFile, because the generator renames File but leaves its references as any.
  • The CRL declares application/pkix-crl and the admin background image/png instead of */*. The background response is built with its documented headers, and Content-Disposition: attachment is kept because the FileDisplayResponse constructor would otherwise force inline.
  • Adds an SDK evaluation harness (tests/sdk-generation/) with REPORT.md and UPSTREAM-NOTES.md.

Breaking change: failures are no longer reported as 401

AccountController::signatureGenerate, the two AdminController certificate generators, FileController::deleteFile, RequestSignatureController::removeSigner and deleteSignatureRequest answered 401 for failures that are not authentication failures. They now answer:

  • 422 for a LibresignException (and an InvalidArgumentException in the PFX and certificate generators);
  • 500 for any other failure they already caught.

The body stays {message}. The only 401 left on these operations is the framework's own. This also removes six anyOf from the contract, which the generator mishandles.

Clients that matched on 401 for these failures must switch to 422 / 500. The frontend type of removeSigner and the Behat/API tests were updated.

🧪 How to test

composer openapi
npm run typescript:generate
vendor/bin/phpunit -c tests/php/openapi/phpunit.xml
composer test:unit -- --filter 'AdminControllerTest|RequestSignatureControllerTest|FileControllerDeleteTest|AccountControllerSignatureGenerateTest'
vendor-bin/behat/vendor/bin/behat tests/integration/features/admin/certificate_openssl.feature
vendor-bin/behat/vendor/bin/behat tests/integration/features/sign/reject.feature
npm run ts:check && npx vitest run

The SDK harness is described in tests/sdk-generation/README.md.

Validation evidence

  • Focused regression/acceptance test
    • New: OpenApiErrorBodyContractTest, OpenApiIdDocSchemaTest, OpenApiBinaryMediaTypesTest, FileControllerDeleteTest, AccountControllerSignatureGenerateTest.
    • Updated: AdminControllerTest, RequestSignatureControllerTest, the API AdminControllerTest, and the Behat features certificate_openssl.feature and sign/reject.feature.
  • Relevant lint/type/static-analysis checks: psalm, php-cs, eslint, ts:check and REUSE ran locally.
  • Broader suite required by the changed surface
    • A CI-like run with act (openapi, psalm, PHPUnit, vitest, 4 Behat shards) was green for the contract commits (up to 2df4f5a4e), merged with upstream main.
    • It was not completed for the last two commits (106c6f9a1, ac896f252: 401→422/500). Only the local checks above were run for them.
  • CI reviewed

Not verified: Playwright, Infection, devcontainer, test:live against a real Nextcloud.

⚙️ API / Back-end changes

  • Contract changes described in the Summary. Failure statuses of 6 operations move from 401 to 422/500, and the 422 bodies, nodeId nullability, the IdDocFile name and the CRL/background media types are corrected.
  • Unit and/or integration tests added or updated
  • Authorization and negative paths checked when applicable: OpenApiErrorBodyContractTest asserts both 422 bodies, 500 on the deletes and no typed 401 on the six operations.
  • Capabilities updated when applicable (not applicable)
  • Documentation updated when applicable: tests/sdk-generation/REPORT.md, UPSTREAM-NOTES.md, README.md
  • API documentation regenerated with composer openapi when necessary: openapi*.json and src/types/openapi/*.ts

🚧 Tasks

  • Review the 401 → 422/500 breaking change with API consumers in mind
  • Leave out of this PR, as pre-existing: DetailedFile.policySnapshotFrozen being required but omitted without a user, and the frontend rejecting a null nodeId in validationDocument.ts
  • Extractor and generator defects (multipart bodies, anyOf merge, mixed, reserved File) go upstream, see UPSTREAM-NOTES.md

✅ Checklist

  • I have read and followed the contribution guide.
  • The diff does not contain unrelated refactors or generated changes. (It contains generated openapi*.json and src/types/openapi/*.ts, as required by the contract change.)
  • Commits follow Conventional Commits where applicable.
  • All commits include the required DCO sign-off.

🤖 AI (if applicable)

  • The content of this PR was partially or fully generated using AI

lfals added 15 commits November 17, 2026 10:08
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<any>`;
- 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 <principal@felps.zip>
Re-run the LibreSign#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 <principal@felps.zip>
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 <principal@felps.zip>
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 <principal@felps.zip>
- 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 <principal@felps.zip>
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 <principal@felps.zip>
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 <principal@felps.zip>
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 <principal@felps.zip>
… 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 <principal@felps.zip>
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 <principal@felps.zip>
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 <principal@felps.zip>
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 <principal@felps.zip>
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 <principal@felps.zip>
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 <principal@felps.zip>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant