Telegram Documents in Your CRM: Quarantine Files, Not Token-Bearing Links
A document intake design that separates Telegram identifiers, credential-bearing retrieval, content checks and permission to attach a file to an enquiry.
Telegram Documents in Your CRM: Quarantine Files, Not Token-Bearing Links
Do not paste a Telegram download URL into a CRM record. The documented retrieval address contains the bot token, and a working download link says nothing about whether a document is safe. A custom integration needs a different route: accept the event, retrieve the document on the server, keep it in private quarantine, then release an attachment only after content checks and authorization for the enquiry.
This design is for developers and process owners receiving customer documents through the ordinary hosted Telegram Bot API. It requires authorized control of the integration, separate storage and a test CRM. It is not a production downloader, a report of testing a live bot, or a verified built-in feature of 24go.site. The scope is message.document; photos, albums, a local Bot API server and automatic archive extraction need separate decisions.
Separate four different references to a file
The Document object includes a file_id that can be used to retrieve or reuse a file, and a file_unique_id. The latter identifies a file, but the documentation explicitly says it cannot be used to download or reuse one. Neither identifier establishes that a document belongs to the current enquiry or that a particular employee may open it.
The next reference is file_path from the File object. A server uses it to retrieve bytes through the documented address containing the token. This is a transport detail, not an attachment URL for a user. Keep that URL out of CRM fields, analytics, notifications and the employee's browser. Inspect HTTP-client logging too: an exception that includes the full request address can expose a token even if your own code never explicitly logs it.
After retrieval, create your own storage-object identifier. It links a quarantined copy to an internal attachment record. Access for an employee is a separate route: your application checks the user and the enquiry before serving the object. If your storage uses temporary signed URLs, protect them against unintended distribution and bound their validity as well. That does not justify exposing the Telegram retrieval URL.
Preserve the relationship among the incoming event, document and internal object without confusing it with authorization. The same file can arrive in different enquiries. Matching file_unique_id values do not permit disclosure across customers or tenants. Even if storage deduplicates identical bytes, permissions on each logical attachment remain separate.
Preserve metadata before calling getFile
When accepting an event, record the tenant, bot, update identifier, message context and the internal enquiry that is allowed to receive the attachment. Preserve available file_id, file_unique_id, original filename, declared MIME type and declared size. Do not invent missing metadata: the filename, type and size are optional in the documented object. A missing size means unknown, not an empty file.
Document defines the filename and MIME type as values supplied by the sender. A name such as invoice.pdf and a type such as application/pdf are therefore useful interface data and preliminary filters, not proof of content. The getFile contract separately warns that the method may not preserve the original name and MIME type. Keep those values from the incoming object when available, explicitly marked as untrusted metadata.
Never use the sender's filename as a filesystem path or storage key. Generate an internal name and retain the original only as length-limited display data with appropriate escaping. Do not interpolate it into a scanner shell command. Names containing paths, control characters or unexpected extensions should be handled under an agreed policy rather than controlling where bytes are written.
This document route starts after ingress authentication. The separate webhook-secret validation guide covers that boundary. A repeated delivery should not create another retrieval job or attachment; use a stable event identity as described in the idempotency guide. Neither control checks the actual file bytes.
Choose the intake policy before downloading
Agree with the process owner on the documents the workflow really needs. If an enquiry only requires a PDF, do not accept archives and executables for the sake of flexibility. The OWASP File Upload Cheat Sheet recommends an extension allowlist, type validation, generated filenames, size limits and isolated storage. These are layered controls: extension, MIME type and a file signature are each insufficient on their own.
The example acceptance protocol below uses a deliberately chosen application policy: PDF only, with at most 5000000 downloaded bytes. This is not a conversion of a Telegram limit. On the verification date, the hosted getFile documentation states that bots can download files up to 20 MB. Do not confuse this with sending-file limits or the capabilities of a separate local Bot API server. An application may choose a smaller ceiling according to its needs and available resources.
Also bound the duration of each attempt, total retries, quarantine capacity and concurrent jobs. A small input can still be expensive to process. Limiting incoming bytes does not replace limits on memory, execution time and the number of processing tasks. Without those controls, several permitted downloads can exhaust resources needed by other enquiries.
Decide who handles failures and what the customer sees. “Received,” “being checked,” “rejected” and “available” should represent different observed stages. Do not report “document attached” as soon as a file_id arrives. Preserve a useful reason instead of silently dropping the task: unsupported type, excessive size, failed retrieval or incomplete verification.
Retrieve bytes without releasing them to an employee
Call getFile from a server-side worker through the bot's existing protected client. Check the response status and whether a usable file_path is present; that field is optional. Do not build a working retrieval address in browser JavaScript or place the token in queue jobs. Keep the secret in the established server-side credential boundary. A queue record refers to an authorized operation, not a secret-bearing URL.
Telegram guarantees that the link remains valid for at least one hour. This is neither an exact one-hour expiry nor a promise of permanent availability. If a link expires, the documentation says to call getFile again. A retry must retain the original task identity and obey the total attempt budget. Permission errors, unsupported sizes and interrupted streams must not all enter an endless “refresh link” loop.
Stream the download into a temporary private object while counting the bytes actually received. Declared size can support an early refusal, but the effective size boundary must apply to the stream. Stop reading when it exceeds the policy; a partial copy is not a successful download. Do not rely solely on a response length header. If the connection breaks, record an incomplete attempt and remove or isolate the remainder under a defined cleanup policy.
Only trusted server code should build the request for the approved Telegram endpoint. Do not allow a URL supplied in a message to replace that source or let the client automatically carry a secret-bearing request to an arbitrary redirect destination. This is a proposed implementation boundary that needs checking against the actual HTTP library. One successful download does not establish that the boundary holds.
Quarantine is an access rule, not merely a folder name
Quarantine means ordinary employees cannot retrieve unchecked bytes and CRM automation cannot parse them prematurely. Store them outside the public webroot, in separate private storage with minimal permissions. An unpredictable public object name is not authorization. Preview and thumbnail services also process content, so do not run them before the isolated checks intended to protect that processing step.
First check the type policy and actual format, then run the agreed content checks in a constrained environment. A PDF signature alone does not establish safety. If the workflow requires antivirus or content disarm and reconstruction, assign an owner to that service and define which result allows release. An unavailable scanner means “verification incomplete,” not “no threats found.”
Do not send customer documents to a public scanning service without a separately approved basis. OWASP warns about data leakage through public services. Storage, access, retention and backup arrangements must fit the actual workflow and applicable requirements. A general technical article cannot establish the legal basis for processing on behalf of the owner.
Bind the check result to the exact object version, for example through an immutable object and a measured byte hash. Replacing the content after a check invalidates the old positive result. A transformed document is another version that needs its own checks. A database flag reading “checked” must not become permission for whatever file later appears at the same address.
Release only for the authorized enquiry
Before attaching a document to the CRM, recheck the tenant, enquiry and permissions of the current user or service operation. The enquiry may have been closed, moved or made inaccessible while scanning ran. A file_id and a successful download do not authorize ignoring that change.
| Observation | Application decision | Do not |
|---|---|---|
| No usable file_path | Retain a retrieval failure and its reason | Treat it as a ready empty file |
| Declared or actual size exceeds policy | Reject and clean up partial storage | Raise the ceiling for one request without approval |
| Filename and MIME pass, content remains unchecked | Keep quarantine | Give an employee a link for a quick manual look |
| Scanner unavailable, or result belongs to other bytes | Wait or use bounded rechecking | Interpret an absent result as a positive verdict |
| Content checks pass, enquiry access has been revoked | Refuse release | Inherit stale permission from the original job |
| Content and authorization checks pass | Create the permitted CRM relationship to the internal object | Store the secret-bearing Telegram URL |
A remote CRM write can have an uncertain outcome too: the server may save the attachment while its response is lost. Use an idempotency mechanism verified for that CRM or reconcile against a stable operation reference. Do not create a new operation merely because of a timeout. Preserve a separate receipt tying the internal attachment, enquiry, object version and returned CRM identifier together.
Test the route in an isolated environment
Prepare synthetic, non-sensitive documents and a test enquiry with real-customer sales and notifications disabled. The following is a protocol for your implementation, not a report of live network testing. Use substituted Telegram and scanner responses for failures rather than finding a malicious document or generating load against the real API.
- Submit a permitted small PDF. Before the scanner's verdict, the ordinary user retrieval route must refuse access. After a positive verdict and authorization checks, it should return only the permitted object.
- Omit the declared size. Retrieval must remain bounded by actual bytes rather than treating the missing value as zero. Then supply a stream that exceeds the example ceiling: there must be no ready copy or CRM relationship.
- Provide an acceptable filename and MIME type with incompatible content. Confirm that metadata alone cannot approve it and that the employee preview does not receive it.
- Return no
file_path, then simulate an interrupted download. Preserve distinct failure reasons; check that partial files cannot be served and that abandoned data is cleaned up. - Delay the scanner and replace the test object with another version. A stale positive result must not release the new bytes. Separately make the scanner unavailable and confirm that the system does not bypass verification.
- Revoke access to the test enquiry after download. The document must remain inaccessible even if content checks succeed. Repeat the request from another tenant.
- Repeat the incoming event and simulate a lost CRM response. Compare job counts, stored objects and remote relationships, not merely the worker's success message.
- Inspect logs and tracing across the test deployment. They must not contain the token, full retrieval URL or document contents. Keep sanitized identifiers and failure reasons for investigation.
Completion means more than obtaining a file. You need observable evidence that an unchecked version was never served, excessive size stopped the stream, another customer's enquiry stayed inaccessible and a repeat did not add a second attachment. These checks depend on your storage, scanner and CRM. A decision table does not execute them for you.
Keep an operational record that explains the boundary
Record state transitions, waiting time, refusal reason, measured size and policy version. For a failed task, an operator should be able to establish whether retrieval finished, what the scanner checked, which bytes the result covered and whether the CRM relationship was confirmed. Do not collect complete documents in technical logs simply to make debugging convenient.
Assign cleanup for temporary objects and quarantine, a retention period for accepted files and a process for deleting derived copies. Cleanup should not silently turn an old CRM record into an empty link: the interface must distinguish policy-driven deletion from a temporary retrieval failure. Account for your own copies, transformation outputs and the agreed backup lifecycle. Deleting a local copy is not a promise to erase the original document from Telegram.
If private storage, content verification or authorized retrieval is not available yet, keep the integration design in local review. Do not substitute a direct Telegram link for a missing stage. Implement and test the absent boundary before expanding the format allowlist or automatically accepting every document a user sends.