Knowledge Migration API Developer Guide - edmozley/freeitsm GitHub Wiki
๐ ๏ธ Knowledge migration API - Developer Guide
(PR #378 by @Dr4inder, #377, 5.7.0, #3013-#3015.) For someone changing the Knowledge REST endpoints, the folder or permissions screens, or the protected picture route.
User side: REST API: Knowledge - Migrating a knowledge base in. The review and its fixes: PR #378 write-up.
๐ช Front door
Four ideas carry the whole thing:
- One write path. The REST endpoints and the folder and permissions screens go through
KnowledgeServiceandKnowledgeTransferService, so a rule fixed in one place is fixed for both. - Content and access commit together. An article created with an
accesslist is never visible without it, even for a moment. - A create can be replayed.
client_reference+knowledge_api_referencesmake "send it again after a timeout" safe. - A picture is part of its article. Every read re-runs
knowledgeCanRead()for that article and that reader; there is no other permission on a picture, and nobody without a session gets one.
๐ Files
| File | What it does |
|---|---|
๐ฃ includes/services/knowledge_transfer.php |
Actor checks, folders, setAccess(), revision(), createOnce(), transactions |
๐ฃ includes/services/knowledge_images.php |
Upload, load() (the permission check), serve(), delete and purge |
๐ฃ includes/services/knowledge.php |
saveArticle() learns folder_id, is_published on update, access, expected_revision, required_image_ids, processing; finishSave() runs search / AI / workflows after commit |
โช includes/knowledge/processing.php |
KnowledgeProcessing::suppresses() - reads processing |
๐ฃ api/v1/resources/knowledge_transfer.php |
Folder, access and image endpoints |
๐ก api/v1/resources/knowledge.php |
Article create/update use createOnce(), report processing, return revision |
โช api/v1/lib/routes.php, permissions.php, modules.php |
Nine routes, four permission groups, mapped to the Knowledge module |
๐ฃ api/knowledge/image.php |
The picture URL that goes in article HTML, for analyst and portal sessions |
๐ก api/knowledge/folders.php, permissions.php |
The screens, now thin adapters over the services |
๐ก api/knowledge/knowledge_save.php |
The editor's save - an allow-list of the keys the screen sends |
โช uploads/knowledge/.htaccess, web.config |
Deny direct access (nginx: the shipped /uploads/ deny) |
โช includes/db_verify_schema.php, database/freeitsm.sql, includes/db_verify_indexes.php |
The two tables |
๐ข tests/knowledge-migration-api.php |
52 checks over HTTP, concurrent workers included |
๐ข tests/knowledge-pr378-review-fixes.php |
15 checks for the review fixes and Publish |
๐งฑ The tables
CREATE TABLE knowledge_api_references (
id INT NOT NULL AUTO_INCREMENT,
analyst_id INT NOT NULL, -- the API key's analyst
operation VARCHAR(16) NOT NULL, -- 'folder', 'article', 'image'
parent_id INT NOT NULL DEFAULT 0, -- e.g. the article an image belongs to
client_reference VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
request_hash CHAR(64) NOT NULL, -- sha256 of the canonical request
object_id INT NOT NULL,
created_datetime DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_knowledge_reference (analyst_id, operation, parent_id, client_reference)
);
CREATE TABLE knowledge_images (
id INT NOT NULL AUTO_INCREMENT,
article_id INT NOT NULL,
stored_name VARCHAR(64) NOT NULL, -- 32 random hex + extension, nothing from the client
original_name VARCHAR(255) NOT NULL,
mime_type VARCHAR(100) NOT NULL,
size_bytes INT UNSIGNED NOT NULL,
sha256 CHAR(64) NOT NULL,
created_by_id INT NULL,
created_datetime DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_knowledge_images_article (article_id)
);
client_reference is binary-collated, so ABC and abc are different references. Both analyst_id and created_by_id are in analystReferenceRegistry().
๐ createOnce() - a create you can send twice
$lock = 'kb:' . substr(hash('sha256', "$db:$ctx->actorId:$operation:$parent:$ref"), 0, 60);
// SELECT GET_LOCK(?, 10) - else 409 reference_busy
...
$st = $conn->prepare('SELECT object_id, request_hash FROM knowledge_api_references
WHERE analyst_id = ? AND operation = ? AND parent_id = ? AND client_reference = ? FOR UPDATE');
if ($prior = $st->fetch(PDO::FETCH_ASSOC)) {
if (!hash_equals($prior['request_hash'], $hash)) throw new ServiceError('conflict', 'reference_conflict', ...);
return ['id' => (int)$prior['object_id'], 'replayed' => true];
}
$result = $write();
// INSERT INTO knowledge_api_references ...
GET_LOCKserializes two workers sending the same reference at once; the row lock covers the rest.- A reference outlives its object. Delete the article and the reference stays, pointing at an id that no longer exists, so a stale retry resolves to a 404 instead of creating it again.
- The caller re-authorizes the replayed id (
apiLoadArticle(),object(),load()), so a replay never hands back something the key can no longer read. - A replay does not re-run search, AI or workflows: the response says
not_repeated.
๐ setAccess() - the whole list, atomically
The REST PATCH .../access replaces the list; the screen's add, remove and mode actions read the current list, change it, and send the whole thing to the same function. Inside one transaction it updates is_restricted / inherit_permissions, keeps unchanged rows (their ids and authors - an open dialog removes by row id), deletes what is gone and inserts what is new.
TRAP: only a new entry has to name someone who exists. An entry already stored may point at a person, team or group deleted since; checking those too locked the list, because the screen sends every entry back on each change. Found in review, fixed before merge - see the write-up.
Gate: the key's knowledge_access.manage and the analyst's Cap::KNOWLEDGE_MANAGE (requireActor($conn, $ctx, true, true)).
โ revision() - optimistic locking
The row (minus view_count and the embedding columns, which change without an edit), its access list, its tag ids and its pictures' ids and hashes, JSON-encoded and HMAC'd with a key derived from the encryption key:
$key = hash_hmac('sha256', 'freeitsm/knowledge-revision/v1', getEncryptionKey(), true);
return hash_hmac('sha256', json_encode($row, JSON_THROW_ON_ERROR), $key);
Keyed because the input includes the admin-only access list. checkRevision() compares with hash_equals() and throws 409 revision_conflict. Every write locks the row (FOR UPDATE) before reading it, so the check and the write see the same row - even two saves in the same second.
๐ผ๏ธ Pictures
Upload goes through uploadStoreBytes() with UPLOAD_TYPES_IMAGE (magic bytes checked, SVG excluded, policy DROP) and the install's cap, KnowledgeImageService::maxBytes(); the file gets a random name, and if the database insert fails the file is removed.
๐ The size limit (5.9.0, #417)
| Piece | Where |
|---|---|
| The choices | KnowledgeImageService::SIZE_CHOICES_MB = [5, 10, 20, 25, 50] - a dropdown, never a typed number. Capped at 50 because the upload sits in memory several times over |
| The setting | system_settings.knowledge_image_max_mb; no row, or a value that is not a choice, = MAX_BYTES (10 MiB) - so an upgrade changes nothing |
| Reading it | maxBytes($conn), used for both the base64 length check and uploadStoreBytes() |
| Too big | ServiceError('validation', 'image_too_large', tooLargeMessage($max)); apiKnowledgeImagesCreate() turns that one code into 413 with details.max_bytes and max_base64_length. Malformed base64 stays 422 invalid_image |
| Discovery | constraints($conn) โ GET /knowledge/images/constraints (knowledge_images.read) |
| Will PHP take it? | serverFit($maxBytes): request = maxBase64Length() + 64 KB; memory = 5 ร image + 32 MB (measured 4.3ร on 10 and 20 MiB: JSON body, decoded copy, stored copy). The settings tab renders it for every choice; the API returns within_server_limits |
| The setting's screen | knowledge/settings/ tab Images (Cap::KNOWLEDGE_MANAGE), saved by api/knowledge/save_email_settings.php key image_max_mb, which refuses anything not in the list |
[!WARNING] TRAP:
post_max_sizedoes not refuse a JSON body. PHP 8.4 still hands the whole body tophp://inputand only raises a startup warning - proved on mod_php, 21 Nov 2026. Arequest_too_largeerror was written and then removed: it could never fire. Wheredisplay_errorsis on, though, that warning is printed before FreeITSM runs, so the reply arrives as HTTP 200 with HTML in front of the JSON. Hence "raise it", never "uploads are refused".
Not affected: pictures added in the article editor. They are embedded in the HTML, scaled by the browser to KB_IMAGE_MAX_SIDE and capped by KB_IMAGE_MAX_BYTES (3 MB) in assets/js/knowledge.js.
Pictures embedded in body_html meet the same limit (GH #423, 5.9.1). Before, a client could put any size of picture in the article HTML as a data: URL and skip the limit entirely - only PHP's request size stopped it. KnowledgeService::saveArticle() now calls KnowledgeImageService::assertEmbeddedWithinLimit($conn, $body, $previousBody) whenever body_html is sent, on create and update, from the API and the screens alike:
| What is checked | Every <img src="data:...">, its decoded size worked out from the base64 length (embeddedPictures() - a large picture is never decoded) |
| What is not | A picture already in the article's current body (matched by a hash of its data), so an article holding one from before can still be edited |
| Too big | ServiceError('validation', 'embedded_image_too_large', ...) with httpStatus = 413 and details: picture (its position, 1 = first embedded picture), type, bytes, max_bytes, max_base64_length. Nothing is saved |
| The editor | Never refused: it caps a picture at 3 MB, under the smallest choice (5 MB) - a TRAP: comment on the check says to keep it so |
ServiceError gained two optional fields for this, details and httpStatus, which apiFailFromService() passes through - so any service can now return a precise status and machine-readable details without an adapter-specific catch.
Tested in tests/knowledge-migration-api.php (the #423 block): exactly the limit accepted, one byte over refused naming picture 2, an existing larger picture kept through an edit while a new one is refused, the 413 body over HTTP with nothing created, and a small embedded picture still accepted. The three refusals fail against the old service.
Tested by tests/knowledge-migration-api.php (the #417 block): the 10 MiB default with no row and with a stray value, formats without SVG, exact limit accepted and one byte over refused (through the service, so PHP's request limits do not decide it), 413 with the limit over HTTP, malformed still 422, and - when within_server_limits - a 10 MiB + 1 image uploaded, replayed, downloaded byte for byte and refused to a reader without access. On a dev install with an 8 MB post_max_size the round trip SKIPs; it was run with the API folder's limits raised.
Read - the only permission check is the article's:
public static function load(PDO $conn, KnowledgeViewer $viewer, int $id, string $lifecycle = 'live'): array
{
...
if (!$row || !knowledgeCanRead($conn, $viewer, (int)$row['article_id'], ['lifecycle' => $lifecycle])) {
throw new ServiceError('not_found', 'not_found', 'Image not found.');
}
image.php picks the viewer from the session - an analyst (lifecycle 'any', so a draft's pictures show in the editor), a portal user ('live' only) - and anybody else gets 404. Ed, 19 November 2026: no content of any sort without authentication.
Serve sends Content-Type from the allow-list (never the stored mime), nosniff, Content-Disposition: inline, Cache-Control: private, no-store and Content-Security-Policy: default-src 'none'; sandbox. No caching on purpose: revoking someone's access to an article must revoke its pictures on their next view, not when a cache expires.
stored_name is re-checked against ^[0-9a-f]{32}\.(png|jpe?g|gif|webp|bmp|heic|heif)$ before it is joined to a path.
๐ Drafts, processing and the editor
is_published: falseon a create makes a draft;is_publishedon an update is new in 5.7.0 and is what the screen's Publish button sends. Flipping it to true raisesknowledge.publishedrather thanknowledge.updated.processing: "suppress"skips the AI embedding and workflows; the search index still runs after commit. REST requiresknowledge_imports.manage.saveArticle()only runsfinishSave()when it owns the transaction. A caller already inside a transaction gets no post-commit processing and must callfinishSave()itself after its own commit.
TRAP:
api/knowledge/knowledge_save.phppasses on an allow-list of the keys the screen sends. Passing the whole body would hand every analyst the REST-only keys above with none of their permissions. When the screen needs a new field, add it to the list - deliberately.
Adding to it
- A new create endpoint that should be retry-safe: wrap the write in
createOnce()with its ownoperationname, and re-authorize the replayed id in the resource. - A new reader of pictures: build the right
KnowledgeViewerand callKnowledgeImageService::load(); never readknowledge_imagesand serve the file yourself. - A new screen field on articles: add it to the allow-list in
knowledge_save.php.
Related: Knowledge folders and security - Developer Guide ยท REST API