diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dff00a6..5060f50 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,10 +21,10 @@ jobs: runs-on: ${{ github.repository == 'stainless-sdks/linq-api-v3-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} if: (github.event_name == 'push' || github.event.pull_request.head.repo.fork) && (github.event_name != 'push' || github.event.head_commit.message != 'codegen metadata') steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Install uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2 with: version: '0.10.2' @@ -43,10 +43,10 @@ jobs: id-token: write runs-on: ${{ github.repository == 'stainless-sdks/linq-api-v3-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Install uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2 with: version: '0.10.2' @@ -61,7 +61,7 @@ jobs: github.repository == 'stainless-sdks/linq-api-v3-python' && !startsWith(github.ref, 'refs/heads/stl/') id: github-oidc - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: core.setOutput('github_token', await core.getIDToken()); @@ -81,10 +81,10 @@ jobs: runs-on: ${{ github.repository == 'stainless-sdks/linq-api-v3-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} if: github.event_name == 'push' || github.event.pull_request.head.repo.fork steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Install uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2 with: version: '0.10.2' diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 01ec9ff..d5ef9a5 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -17,10 +17,10 @@ jobs: id-token: write steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Install uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2 with: version: '0.9.13' diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index 66245c9..d1f2ad8 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -12,7 +12,7 @@ jobs: if: github.repository == 'linq-team/linq-python' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Check release environment run: | diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6538ca9..6d78745 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.8.0" + ".": "0.9.0" } \ No newline at end of file diff --git a/.stats.yml b/.stats.yml index 28d4e49..50bc9e8 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 34 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/linq/linq-api-v3-68d71a6222b9b76fc00fbf74cb8ac86e5e5a6a65a472969269c912235e3c4cf7.yml -openapi_spec_hash: 8fdc1be6f5741bc4d478af7eddfff24c -config_hash: 3ab31decde29ec61e02db7dcb5313f82 +configured_endpoints: 35 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/linq/linq-api-v3-d7993802c9754a19b91058a03bab7fa59d76d993d8e025b4e046d863566b4a43.yml +openapi_spec_hash: adc3205a32d9469b6eaf6787c7835b84 +config_hash: 7a8a13d75aa72faddd9a7f82f580873c diff --git a/CHANGELOG.md b/CHANGELOG.md index 00dd039..44414a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 0.9.0 (2026-05-13) + +Full Changelog: [v0.8.0...v0.9.0](https://github.com/linq-team/linq-python/compare/v0.8.0...v0.9.0) + +### Features + +* **api:** add delete endpoint ([1daeeb6](https://github.com/linq-team/linq-python/commit/1daeeb6eaa3bf3c3688de581b1cb35714fc9881b)) +* **internal/types:** support eagerly validating pydantic iterators ([ebac43c](https://github.com/linq-team/linq-python/commit/ebac43cb5d8a54eae38f50562ff1cf972c998a4a)) + + +### Bug Fixes + +* **client:** add missing f-string prefix in file type error message ([1fe708e](https://github.com/linq-team/linq-python/commit/1fe708e103ce31e536a237844bd7866ba98423a9)) + + +### Documentation + +* **api:** expand attachments resource documentation ([ec612eb](https://github.com/linq-team/linq-python/commit/ec612eb80312a4ebd49cea6028d99a9665f347d2)) +* **api:** mark status and is_archived fields as deprecated in attachments/chat ([36a77d9](https://github.com/linq-team/linq-python/commit/36a77d9e66f5cd7d52bd42f0e438f663ea8f10cf)) + ## 0.8.0 (2026-05-07) Full Changelog: [v0.7.0...v0.8.0](https://github.com/linq-team/linq-python/compare/v0.7.0...v0.8.0) diff --git a/api.md b/api.md index a4578c2..e542503 100644 --- a/api.md +++ b/api.md @@ -103,6 +103,7 @@ Methods: - client.attachments.create(\*\*params) -> AttachmentCreateResponse - client.attachments.retrieve(attachment_id) -> AttachmentRetrieveResponse +- client.attachments.delete(attachment_id) -> None # Phonenumbers diff --git a/pyproject.toml b/pyproject.toml index 5ac8aba..cc4d17f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "linq-python" -version = "0.8.0" +version = "0.9.0" description = "The official Python library for the linq-api-v3 API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/linq/_client.py b/src/linq/_client.py index b334b6b..2796c87 100644 --- a/src/linq/_client.py +++ b/src/linq/_client.py @@ -230,6 +230,122 @@ def attachments(self) -> AttachmentsResource: - **URL-based (`url` field):** 10MB maximum - **Pre-upload (`attachment_id`):** 100MB maximum + + ## Security & Ownership + + Every attachment is bound to the partner account that created or received it. The API enforces ownership on every operation that touches an attachment — sending, retrieving, deleting. + + **What this means for you:** + + - An attachment created under your API key can only be referenced by your API key. + - Submitting another partner's `attachment_id` returns `404 Not Found`. We do not disclose whether the id exists or belongs to someone else. + - Submitting a CDN URL that resolves to another partner's attachment is rejected before the send is attempted. + - Ownership enforcement applies uniformly across send, create-chat, voice memo, retrieve, and delete operations. + + Every attachment-affecting endpoint requires a valid partner API key. Unauthenticated calls return `401 Unauthorized`. + + ## Attachment URL Patterns + + Attachment URLs in API responses and webhook payloads use one of two layouts, depending on the attachment's tier: + + | Tier | URL pattern | TTL | + |---|---|---| + | Persistent (default) | `https://cdn.linqapp.com/attachments/partners/{partner_id}/{attachment_id}/{filename}` | Long-lived | + | Ephemeral | Pre-signed URL pointing at the ephemeral prefix on `cdn.linqapp.com` | 15 minutes per signed URL — re-fetch via the API for a fresh URL | + + Inbound media you receive over webhooks uses the same layout your outbound sends produce, so the URL you store and the URL you build look identical — no special casing in your client. + + ## Ephemeral Attachments (Privacy Tier) + + For regulated or sensitive content, opt in to the **ephemeral attachments** tier by contacting your Linq support contact. You can request it at two scopes: + + | Scope | Effect | + |---|---| + | **Partner-wide** | Every outbound and inbound attachment on every phone number under your account is routed through the ephemeral tier. | + | **Per phone number** | Only the specified phone numbers route their attachments through the ephemeral tier. The rest stay on the persistent tier. | + + **Behavioral differences vs the persistent default:** + + | Aspect | Persistent | Ephemeral | + |---|---|---| + | Download URL form | Long-lived CDN URL | Pre-signed URL with short TTL | + | Retention floor | Indefinite (until you call `DELETE`) | **Hard backstop: 1 day** — even without an explicit `DELETE`, the platform removes the underlying bytes after 24 hours | + | URL re-fetch | Not required | Fetch via `GET /v3/attachments/{attachmentId}` for a fresh signed URL after TTL expiry | + | Cross-partner isolation | Enforced | Enforced | + + **When to choose ephemeral:** + + - Your downstream system processes the file immediately on receipt and does not need to re-read it later. + - You have a compliance requirement that the platform must not retain attachments beyond a short window. + - The content is high-sensitivity (PHI, financial documents, identity verification) and you do not want it sitting behind a long-lived URL. + + **Important:** ephemeral applies in *both directions* — outbound files you upload **and** inbound media received by the phone numbers in that scope. Download bytes you need to keep promptly, or fetch a fresh signed URL via the API when needed. + + ## Deleting an Attachment + + To permanently remove an attachment you own, use: + + ```http + DELETE /v3/attachments/{attachmentId} + Authorization: Bearer + ``` + + **What this does:** + + 1. Verifies the attachment is owned by your account. Returns `404` otherwise. + 2. Removes the underlying file from Linq storage. + 3. Records an audit entry (timestamp, partner, attachment id). + + **Response codes:** + + | Status | Meaning | + |---|---| + | `204 No Content` | Deletion succeeded. The attachment is removed from Linq storage. | + | `400 Bad Request` | `attachmentId` is not a valid UUID. | + | `401 Unauthorized` | Missing or invalid API key. | + | `404 Not Found` | Attachment does not exist or is not owned by your account. | + | `500 Internal Server Error` | Transient infrastructure issue — safe to retry. | + + **Effect on message history:** + + - Messages that referenced the deleted attachment remain visible. + - The message part that pointed at the attachment is preserved with no attachment reference. + - Webhook payloads previously delivered to you retain the original URL string, but downloads from that URL return `404` going forward. + + Deletion is **irreversible**. Once `204` is returned, the bytes are gone — there is no undelete. + + ## Inbound Media Flow + + When one of your phone numbers receives a message with media (image, video, audio, document), the platform: + + 1. Stores the file under your partner account. + 2. Records metadata linked to the inbound message. + 3. Delivers a webhook whose `parts[]` array includes a `media` part with a `url` pointing at `cdn.linqapp.com`. + 4. If the receiving phone is opted in to ephemeral, the `url` is a short-TTL signed URL. + + You can acknowledge the webhook without fetching the file inline, and lazy-load via `GET /v3/attachments/{attachmentId}` later. For ephemeral attachments, retrieving via the API always returns a freshly-signed URL. + + ## Data Lifecycle Summary + + | Data | Persistent tier | Ephemeral tier | + |---|---|---| + | Attachment bytes | Retained until you `DELETE` | **Auto-removed after 1 day**, also removable via `DELETE` | + | Attachment metadata (id, filename, mime type, size) | Retained until you `DELETE` | Removed alongside the bytes | + | Message body & parts | Retained per message-retention policy | Retained per message-retention policy | + | Audit log of deletions | Retained per platform retention policy | Retained per platform retention policy | + + **In transit:** TLS 1.2+ everywhere. **At rest:** AES-256 (server-side encryption). + + ## Compliance Checklist + + If you're integrating Linq under a security or privacy review, here is the short list: + + - Allowlist exactly one outbound domain: `cdn.linqapp.com`. + - Decide whether you need ephemeral attachments (high-sensitivity content) — request enablement through your Linq support contact. + - Implement `DELETE /v3/attachments/{attachmentId}` calls in your deletion workflow. + - Persist any attachments your application needs long-term — Linq is the authoritative source until you delete, but the ephemeral tier auto-purges after 1 day. + - For audit: every deletion is logged on Linq's side. Surface a confirmation in your application UI based on the `204` response. + - For end-user "right to delete" requests: enumerate attachment ids and `DELETE` each. The platform does not provide a partner-wide wipe endpoint — deletion is per-attachment by design. """ from .resources.attachments import AttachmentsResource @@ -755,6 +871,122 @@ def attachments(self) -> AsyncAttachmentsResource: - **URL-based (`url` field):** 10MB maximum - **Pre-upload (`attachment_id`):** 100MB maximum + + ## Security & Ownership + + Every attachment is bound to the partner account that created or received it. The API enforces ownership on every operation that touches an attachment — sending, retrieving, deleting. + + **What this means for you:** + + - An attachment created under your API key can only be referenced by your API key. + - Submitting another partner's `attachment_id` returns `404 Not Found`. We do not disclose whether the id exists or belongs to someone else. + - Submitting a CDN URL that resolves to another partner's attachment is rejected before the send is attempted. + - Ownership enforcement applies uniformly across send, create-chat, voice memo, retrieve, and delete operations. + + Every attachment-affecting endpoint requires a valid partner API key. Unauthenticated calls return `401 Unauthorized`. + + ## Attachment URL Patterns + + Attachment URLs in API responses and webhook payloads use one of two layouts, depending on the attachment's tier: + + | Tier | URL pattern | TTL | + |---|---|---| + | Persistent (default) | `https://cdn.linqapp.com/attachments/partners/{partner_id}/{attachment_id}/{filename}` | Long-lived | + | Ephemeral | Pre-signed URL pointing at the ephemeral prefix on `cdn.linqapp.com` | 15 minutes per signed URL — re-fetch via the API for a fresh URL | + + Inbound media you receive over webhooks uses the same layout your outbound sends produce, so the URL you store and the URL you build look identical — no special casing in your client. + + ## Ephemeral Attachments (Privacy Tier) + + For regulated or sensitive content, opt in to the **ephemeral attachments** tier by contacting your Linq support contact. You can request it at two scopes: + + | Scope | Effect | + |---|---| + | **Partner-wide** | Every outbound and inbound attachment on every phone number under your account is routed through the ephemeral tier. | + | **Per phone number** | Only the specified phone numbers route their attachments through the ephemeral tier. The rest stay on the persistent tier. | + + **Behavioral differences vs the persistent default:** + + | Aspect | Persistent | Ephemeral | + |---|---|---| + | Download URL form | Long-lived CDN URL | Pre-signed URL with short TTL | + | Retention floor | Indefinite (until you call `DELETE`) | **Hard backstop: 1 day** — even without an explicit `DELETE`, the platform removes the underlying bytes after 24 hours | + | URL re-fetch | Not required | Fetch via `GET /v3/attachments/{attachmentId}` for a fresh signed URL after TTL expiry | + | Cross-partner isolation | Enforced | Enforced | + + **When to choose ephemeral:** + + - Your downstream system processes the file immediately on receipt and does not need to re-read it later. + - You have a compliance requirement that the platform must not retain attachments beyond a short window. + - The content is high-sensitivity (PHI, financial documents, identity verification) and you do not want it sitting behind a long-lived URL. + + **Important:** ephemeral applies in *both directions* — outbound files you upload **and** inbound media received by the phone numbers in that scope. Download bytes you need to keep promptly, or fetch a fresh signed URL via the API when needed. + + ## Deleting an Attachment + + To permanently remove an attachment you own, use: + + ```http + DELETE /v3/attachments/{attachmentId} + Authorization: Bearer + ``` + + **What this does:** + + 1. Verifies the attachment is owned by your account. Returns `404` otherwise. + 2. Removes the underlying file from Linq storage. + 3. Records an audit entry (timestamp, partner, attachment id). + + **Response codes:** + + | Status | Meaning | + |---|---| + | `204 No Content` | Deletion succeeded. The attachment is removed from Linq storage. | + | `400 Bad Request` | `attachmentId` is not a valid UUID. | + | `401 Unauthorized` | Missing or invalid API key. | + | `404 Not Found` | Attachment does not exist or is not owned by your account. | + | `500 Internal Server Error` | Transient infrastructure issue — safe to retry. | + + **Effect on message history:** + + - Messages that referenced the deleted attachment remain visible. + - The message part that pointed at the attachment is preserved with no attachment reference. + - Webhook payloads previously delivered to you retain the original URL string, but downloads from that URL return `404` going forward. + + Deletion is **irreversible**. Once `204` is returned, the bytes are gone — there is no undelete. + + ## Inbound Media Flow + + When one of your phone numbers receives a message with media (image, video, audio, document), the platform: + + 1. Stores the file under your partner account. + 2. Records metadata linked to the inbound message. + 3. Delivers a webhook whose `parts[]` array includes a `media` part with a `url` pointing at `cdn.linqapp.com`. + 4. If the receiving phone is opted in to ephemeral, the `url` is a short-TTL signed URL. + + You can acknowledge the webhook without fetching the file inline, and lazy-load via `GET /v3/attachments/{attachmentId}` later. For ephemeral attachments, retrieving via the API always returns a freshly-signed URL. + + ## Data Lifecycle Summary + + | Data | Persistent tier | Ephemeral tier | + |---|---|---| + | Attachment bytes | Retained until you `DELETE` | **Auto-removed after 1 day**, also removable via `DELETE` | + | Attachment metadata (id, filename, mime type, size) | Retained until you `DELETE` | Removed alongside the bytes | + | Message body & parts | Retained per message-retention policy | Retained per message-retention policy | + | Audit log of deletions | Retained per platform retention policy | Retained per platform retention policy | + + **In transit:** TLS 1.2+ everywhere. **At rest:** AES-256 (server-side encryption). + + ## Compliance Checklist + + If you're integrating Linq under a security or privacy review, here is the short list: + + - Allowlist exactly one outbound domain: `cdn.linqapp.com`. + - Decide whether you need ephemeral attachments (high-sensitivity content) — request enablement through your Linq support contact. + - Implement `DELETE /v3/attachments/{attachmentId}` calls in your deletion workflow. + - Persist any attachments your application needs long-term — Linq is the authoritative source until you delete, but the ephemeral tier auto-purges after 1 day. + - For audit: every deletion is logged on Linq's side. Surface a confirmation in your application UI based on the `204` response. + - For end-user "right to delete" requests: enumerate attachment ids and `DELETE` each. The platform does not provide a partner-wide wipe endpoint — deletion is per-attachment by design. """ from .resources.attachments import AsyncAttachmentsResource @@ -1222,6 +1454,122 @@ def attachments(self) -> attachments.AttachmentsResourceWithRawResponse: - **URL-based (`url` field):** 10MB maximum - **Pre-upload (`attachment_id`):** 100MB maximum + + ## Security & Ownership + + Every attachment is bound to the partner account that created or received it. The API enforces ownership on every operation that touches an attachment — sending, retrieving, deleting. + + **What this means for you:** + + - An attachment created under your API key can only be referenced by your API key. + - Submitting another partner's `attachment_id` returns `404 Not Found`. We do not disclose whether the id exists or belongs to someone else. + - Submitting a CDN URL that resolves to another partner's attachment is rejected before the send is attempted. + - Ownership enforcement applies uniformly across send, create-chat, voice memo, retrieve, and delete operations. + + Every attachment-affecting endpoint requires a valid partner API key. Unauthenticated calls return `401 Unauthorized`. + + ## Attachment URL Patterns + + Attachment URLs in API responses and webhook payloads use one of two layouts, depending on the attachment's tier: + + | Tier | URL pattern | TTL | + |---|---|---| + | Persistent (default) | `https://cdn.linqapp.com/attachments/partners/{partner_id}/{attachment_id}/{filename}` | Long-lived | + | Ephemeral | Pre-signed URL pointing at the ephemeral prefix on `cdn.linqapp.com` | 15 minutes per signed URL — re-fetch via the API for a fresh URL | + + Inbound media you receive over webhooks uses the same layout your outbound sends produce, so the URL you store and the URL you build look identical — no special casing in your client. + + ## Ephemeral Attachments (Privacy Tier) + + For regulated or sensitive content, opt in to the **ephemeral attachments** tier by contacting your Linq support contact. You can request it at two scopes: + + | Scope | Effect | + |---|---| + | **Partner-wide** | Every outbound and inbound attachment on every phone number under your account is routed through the ephemeral tier. | + | **Per phone number** | Only the specified phone numbers route their attachments through the ephemeral tier. The rest stay on the persistent tier. | + + **Behavioral differences vs the persistent default:** + + | Aspect | Persistent | Ephemeral | + |---|---|---| + | Download URL form | Long-lived CDN URL | Pre-signed URL with short TTL | + | Retention floor | Indefinite (until you call `DELETE`) | **Hard backstop: 1 day** — even without an explicit `DELETE`, the platform removes the underlying bytes after 24 hours | + | URL re-fetch | Not required | Fetch via `GET /v3/attachments/{attachmentId}` for a fresh signed URL after TTL expiry | + | Cross-partner isolation | Enforced | Enforced | + + **When to choose ephemeral:** + + - Your downstream system processes the file immediately on receipt and does not need to re-read it later. + - You have a compliance requirement that the platform must not retain attachments beyond a short window. + - The content is high-sensitivity (PHI, financial documents, identity verification) and you do not want it sitting behind a long-lived URL. + + **Important:** ephemeral applies in *both directions* — outbound files you upload **and** inbound media received by the phone numbers in that scope. Download bytes you need to keep promptly, or fetch a fresh signed URL via the API when needed. + + ## Deleting an Attachment + + To permanently remove an attachment you own, use: + + ```http + DELETE /v3/attachments/{attachmentId} + Authorization: Bearer + ``` + + **What this does:** + + 1. Verifies the attachment is owned by your account. Returns `404` otherwise. + 2. Removes the underlying file from Linq storage. + 3. Records an audit entry (timestamp, partner, attachment id). + + **Response codes:** + + | Status | Meaning | + |---|---| + | `204 No Content` | Deletion succeeded. The attachment is removed from Linq storage. | + | `400 Bad Request` | `attachmentId` is not a valid UUID. | + | `401 Unauthorized` | Missing or invalid API key. | + | `404 Not Found` | Attachment does not exist or is not owned by your account. | + | `500 Internal Server Error` | Transient infrastructure issue — safe to retry. | + + **Effect on message history:** + + - Messages that referenced the deleted attachment remain visible. + - The message part that pointed at the attachment is preserved with no attachment reference. + - Webhook payloads previously delivered to you retain the original URL string, but downloads from that URL return `404` going forward. + + Deletion is **irreversible**. Once `204` is returned, the bytes are gone — there is no undelete. + + ## Inbound Media Flow + + When one of your phone numbers receives a message with media (image, video, audio, document), the platform: + + 1. Stores the file under your partner account. + 2. Records metadata linked to the inbound message. + 3. Delivers a webhook whose `parts[]` array includes a `media` part with a `url` pointing at `cdn.linqapp.com`. + 4. If the receiving phone is opted in to ephemeral, the `url` is a short-TTL signed URL. + + You can acknowledge the webhook without fetching the file inline, and lazy-load via `GET /v3/attachments/{attachmentId}` later. For ephemeral attachments, retrieving via the API always returns a freshly-signed URL. + + ## Data Lifecycle Summary + + | Data | Persistent tier | Ephemeral tier | + |---|---|---| + | Attachment bytes | Retained until you `DELETE` | **Auto-removed after 1 day**, also removable via `DELETE` | + | Attachment metadata (id, filename, mime type, size) | Retained until you `DELETE` | Removed alongside the bytes | + | Message body & parts | Retained per message-retention policy | Retained per message-retention policy | + | Audit log of deletions | Retained per platform retention policy | Retained per platform retention policy | + + **In transit:** TLS 1.2+ everywhere. **At rest:** AES-256 (server-side encryption). + + ## Compliance Checklist + + If you're integrating Linq under a security or privacy review, here is the short list: + + - Allowlist exactly one outbound domain: `cdn.linqapp.com`. + - Decide whether you need ephemeral attachments (high-sensitivity content) — request enablement through your Linq support contact. + - Implement `DELETE /v3/attachments/{attachmentId}` calls in your deletion workflow. + - Persist any attachments your application needs long-term — Linq is the authoritative source until you delete, but the ephemeral tier auto-purges after 1 day. + - For audit: every deletion is logged on Linq's side. Surface a confirmation in your application UI based on the `204` response. + - For end-user "right to delete" requests: enumerate attachment ids and `DELETE` each. The platform does not provide a partner-wide wipe endpoint — deletion is per-attachment by design. """ from .resources.attachments import AttachmentsResourceWithRawResponse @@ -1566,6 +1914,122 @@ def attachments(self) -> attachments.AsyncAttachmentsResourceWithRawResponse: - **URL-based (`url` field):** 10MB maximum - **Pre-upload (`attachment_id`):** 100MB maximum + + ## Security & Ownership + + Every attachment is bound to the partner account that created or received it. The API enforces ownership on every operation that touches an attachment — sending, retrieving, deleting. + + **What this means for you:** + + - An attachment created under your API key can only be referenced by your API key. + - Submitting another partner's `attachment_id` returns `404 Not Found`. We do not disclose whether the id exists or belongs to someone else. + - Submitting a CDN URL that resolves to another partner's attachment is rejected before the send is attempted. + - Ownership enforcement applies uniformly across send, create-chat, voice memo, retrieve, and delete operations. + + Every attachment-affecting endpoint requires a valid partner API key. Unauthenticated calls return `401 Unauthorized`. + + ## Attachment URL Patterns + + Attachment URLs in API responses and webhook payloads use one of two layouts, depending on the attachment's tier: + + | Tier | URL pattern | TTL | + |---|---|---| + | Persistent (default) | `https://cdn.linqapp.com/attachments/partners/{partner_id}/{attachment_id}/{filename}` | Long-lived | + | Ephemeral | Pre-signed URL pointing at the ephemeral prefix on `cdn.linqapp.com` | 15 minutes per signed URL — re-fetch via the API for a fresh URL | + + Inbound media you receive over webhooks uses the same layout your outbound sends produce, so the URL you store and the URL you build look identical — no special casing in your client. + + ## Ephemeral Attachments (Privacy Tier) + + For regulated or sensitive content, opt in to the **ephemeral attachments** tier by contacting your Linq support contact. You can request it at two scopes: + + | Scope | Effect | + |---|---| + | **Partner-wide** | Every outbound and inbound attachment on every phone number under your account is routed through the ephemeral tier. | + | **Per phone number** | Only the specified phone numbers route their attachments through the ephemeral tier. The rest stay on the persistent tier. | + + **Behavioral differences vs the persistent default:** + + | Aspect | Persistent | Ephemeral | + |---|---|---| + | Download URL form | Long-lived CDN URL | Pre-signed URL with short TTL | + | Retention floor | Indefinite (until you call `DELETE`) | **Hard backstop: 1 day** — even without an explicit `DELETE`, the platform removes the underlying bytes after 24 hours | + | URL re-fetch | Not required | Fetch via `GET /v3/attachments/{attachmentId}` for a fresh signed URL after TTL expiry | + | Cross-partner isolation | Enforced | Enforced | + + **When to choose ephemeral:** + + - Your downstream system processes the file immediately on receipt and does not need to re-read it later. + - You have a compliance requirement that the platform must not retain attachments beyond a short window. + - The content is high-sensitivity (PHI, financial documents, identity verification) and you do not want it sitting behind a long-lived URL. + + **Important:** ephemeral applies in *both directions* — outbound files you upload **and** inbound media received by the phone numbers in that scope. Download bytes you need to keep promptly, or fetch a fresh signed URL via the API when needed. + + ## Deleting an Attachment + + To permanently remove an attachment you own, use: + + ```http + DELETE /v3/attachments/{attachmentId} + Authorization: Bearer + ``` + + **What this does:** + + 1. Verifies the attachment is owned by your account. Returns `404` otherwise. + 2. Removes the underlying file from Linq storage. + 3. Records an audit entry (timestamp, partner, attachment id). + + **Response codes:** + + | Status | Meaning | + |---|---| + | `204 No Content` | Deletion succeeded. The attachment is removed from Linq storage. | + | `400 Bad Request` | `attachmentId` is not a valid UUID. | + | `401 Unauthorized` | Missing or invalid API key. | + | `404 Not Found` | Attachment does not exist or is not owned by your account. | + | `500 Internal Server Error` | Transient infrastructure issue — safe to retry. | + + **Effect on message history:** + + - Messages that referenced the deleted attachment remain visible. + - The message part that pointed at the attachment is preserved with no attachment reference. + - Webhook payloads previously delivered to you retain the original URL string, but downloads from that URL return `404` going forward. + + Deletion is **irreversible**. Once `204` is returned, the bytes are gone — there is no undelete. + + ## Inbound Media Flow + + When one of your phone numbers receives a message with media (image, video, audio, document), the platform: + + 1. Stores the file under your partner account. + 2. Records metadata linked to the inbound message. + 3. Delivers a webhook whose `parts[]` array includes a `media` part with a `url` pointing at `cdn.linqapp.com`. + 4. If the receiving phone is opted in to ephemeral, the `url` is a short-TTL signed URL. + + You can acknowledge the webhook without fetching the file inline, and lazy-load via `GET /v3/attachments/{attachmentId}` later. For ephemeral attachments, retrieving via the API always returns a freshly-signed URL. + + ## Data Lifecycle Summary + + | Data | Persistent tier | Ephemeral tier | + |---|---|---| + | Attachment bytes | Retained until you `DELETE` | **Auto-removed after 1 day**, also removable via `DELETE` | + | Attachment metadata (id, filename, mime type, size) | Retained until you `DELETE` | Removed alongside the bytes | + | Message body & parts | Retained per message-retention policy | Retained per message-retention policy | + | Audit log of deletions | Retained per platform retention policy | Retained per platform retention policy | + + **In transit:** TLS 1.2+ everywhere. **At rest:** AES-256 (server-side encryption). + + ## Compliance Checklist + + If you're integrating Linq under a security or privacy review, here is the short list: + + - Allowlist exactly one outbound domain: `cdn.linqapp.com`. + - Decide whether you need ephemeral attachments (high-sensitivity content) — request enablement through your Linq support contact. + - Implement `DELETE /v3/attachments/{attachmentId}` calls in your deletion workflow. + - Persist any attachments your application needs long-term — Linq is the authoritative source until you delete, but the ephemeral tier auto-purges after 1 day. + - For audit: every deletion is logged on Linq's side. Surface a confirmation in your application UI based on the `204` response. + - For end-user "right to delete" requests: enumerate attachment ids and `DELETE` each. The platform does not provide a partner-wide wipe endpoint — deletion is per-attachment by design. """ from .resources.attachments import AsyncAttachmentsResourceWithRawResponse @@ -1910,6 +2374,122 @@ def attachments(self) -> attachments.AttachmentsResourceWithStreamingResponse: - **URL-based (`url` field):** 10MB maximum - **Pre-upload (`attachment_id`):** 100MB maximum + + ## Security & Ownership + + Every attachment is bound to the partner account that created or received it. The API enforces ownership on every operation that touches an attachment — sending, retrieving, deleting. + + **What this means for you:** + + - An attachment created under your API key can only be referenced by your API key. + - Submitting another partner's `attachment_id` returns `404 Not Found`. We do not disclose whether the id exists or belongs to someone else. + - Submitting a CDN URL that resolves to another partner's attachment is rejected before the send is attempted. + - Ownership enforcement applies uniformly across send, create-chat, voice memo, retrieve, and delete operations. + + Every attachment-affecting endpoint requires a valid partner API key. Unauthenticated calls return `401 Unauthorized`. + + ## Attachment URL Patterns + + Attachment URLs in API responses and webhook payloads use one of two layouts, depending on the attachment's tier: + + | Tier | URL pattern | TTL | + |---|---|---| + | Persistent (default) | `https://cdn.linqapp.com/attachments/partners/{partner_id}/{attachment_id}/{filename}` | Long-lived | + | Ephemeral | Pre-signed URL pointing at the ephemeral prefix on `cdn.linqapp.com` | 15 minutes per signed URL — re-fetch via the API for a fresh URL | + + Inbound media you receive over webhooks uses the same layout your outbound sends produce, so the URL you store and the URL you build look identical — no special casing in your client. + + ## Ephemeral Attachments (Privacy Tier) + + For regulated or sensitive content, opt in to the **ephemeral attachments** tier by contacting your Linq support contact. You can request it at two scopes: + + | Scope | Effect | + |---|---| + | **Partner-wide** | Every outbound and inbound attachment on every phone number under your account is routed through the ephemeral tier. | + | **Per phone number** | Only the specified phone numbers route their attachments through the ephemeral tier. The rest stay on the persistent tier. | + + **Behavioral differences vs the persistent default:** + + | Aspect | Persistent | Ephemeral | + |---|---|---| + | Download URL form | Long-lived CDN URL | Pre-signed URL with short TTL | + | Retention floor | Indefinite (until you call `DELETE`) | **Hard backstop: 1 day** — even without an explicit `DELETE`, the platform removes the underlying bytes after 24 hours | + | URL re-fetch | Not required | Fetch via `GET /v3/attachments/{attachmentId}` for a fresh signed URL after TTL expiry | + | Cross-partner isolation | Enforced | Enforced | + + **When to choose ephemeral:** + + - Your downstream system processes the file immediately on receipt and does not need to re-read it later. + - You have a compliance requirement that the platform must not retain attachments beyond a short window. + - The content is high-sensitivity (PHI, financial documents, identity verification) and you do not want it sitting behind a long-lived URL. + + **Important:** ephemeral applies in *both directions* — outbound files you upload **and** inbound media received by the phone numbers in that scope. Download bytes you need to keep promptly, or fetch a fresh signed URL via the API when needed. + + ## Deleting an Attachment + + To permanently remove an attachment you own, use: + + ```http + DELETE /v3/attachments/{attachmentId} + Authorization: Bearer + ``` + + **What this does:** + + 1. Verifies the attachment is owned by your account. Returns `404` otherwise. + 2. Removes the underlying file from Linq storage. + 3. Records an audit entry (timestamp, partner, attachment id). + + **Response codes:** + + | Status | Meaning | + |---|---| + | `204 No Content` | Deletion succeeded. The attachment is removed from Linq storage. | + | `400 Bad Request` | `attachmentId` is not a valid UUID. | + | `401 Unauthorized` | Missing or invalid API key. | + | `404 Not Found` | Attachment does not exist or is not owned by your account. | + | `500 Internal Server Error` | Transient infrastructure issue — safe to retry. | + + **Effect on message history:** + + - Messages that referenced the deleted attachment remain visible. + - The message part that pointed at the attachment is preserved with no attachment reference. + - Webhook payloads previously delivered to you retain the original URL string, but downloads from that URL return `404` going forward. + + Deletion is **irreversible**. Once `204` is returned, the bytes are gone — there is no undelete. + + ## Inbound Media Flow + + When one of your phone numbers receives a message with media (image, video, audio, document), the platform: + + 1. Stores the file under your partner account. + 2. Records metadata linked to the inbound message. + 3. Delivers a webhook whose `parts[]` array includes a `media` part with a `url` pointing at `cdn.linqapp.com`. + 4. If the receiving phone is opted in to ephemeral, the `url` is a short-TTL signed URL. + + You can acknowledge the webhook without fetching the file inline, and lazy-load via `GET /v3/attachments/{attachmentId}` later. For ephemeral attachments, retrieving via the API always returns a freshly-signed URL. + + ## Data Lifecycle Summary + + | Data | Persistent tier | Ephemeral tier | + |---|---|---| + | Attachment bytes | Retained until you `DELETE` | **Auto-removed after 1 day**, also removable via `DELETE` | + | Attachment metadata (id, filename, mime type, size) | Retained until you `DELETE` | Removed alongside the bytes | + | Message body & parts | Retained per message-retention policy | Retained per message-retention policy | + | Audit log of deletions | Retained per platform retention policy | Retained per platform retention policy | + + **In transit:** TLS 1.2+ everywhere. **At rest:** AES-256 (server-side encryption). + + ## Compliance Checklist + + If you're integrating Linq under a security or privacy review, here is the short list: + + - Allowlist exactly one outbound domain: `cdn.linqapp.com`. + - Decide whether you need ephemeral attachments (high-sensitivity content) — request enablement through your Linq support contact. + - Implement `DELETE /v3/attachments/{attachmentId}` calls in your deletion workflow. + - Persist any attachments your application needs long-term — Linq is the authoritative source until you delete, but the ephemeral tier auto-purges after 1 day. + - For audit: every deletion is logged on Linq's side. Surface a confirmation in your application UI based on the `204` response. + - For end-user "right to delete" requests: enumerate attachment ids and `DELETE` each. The platform does not provide a partner-wide wipe endpoint — deletion is per-attachment by design. """ from .resources.attachments import AttachmentsResourceWithStreamingResponse @@ -2254,6 +2834,122 @@ def attachments(self) -> attachments.AsyncAttachmentsResourceWithStreamingRespon - **URL-based (`url` field):** 10MB maximum - **Pre-upload (`attachment_id`):** 100MB maximum + + ## Security & Ownership + + Every attachment is bound to the partner account that created or received it. The API enforces ownership on every operation that touches an attachment — sending, retrieving, deleting. + + **What this means for you:** + + - An attachment created under your API key can only be referenced by your API key. + - Submitting another partner's `attachment_id` returns `404 Not Found`. We do not disclose whether the id exists or belongs to someone else. + - Submitting a CDN URL that resolves to another partner's attachment is rejected before the send is attempted. + - Ownership enforcement applies uniformly across send, create-chat, voice memo, retrieve, and delete operations. + + Every attachment-affecting endpoint requires a valid partner API key. Unauthenticated calls return `401 Unauthorized`. + + ## Attachment URL Patterns + + Attachment URLs in API responses and webhook payloads use one of two layouts, depending on the attachment's tier: + + | Tier | URL pattern | TTL | + |---|---|---| + | Persistent (default) | `https://cdn.linqapp.com/attachments/partners/{partner_id}/{attachment_id}/{filename}` | Long-lived | + | Ephemeral | Pre-signed URL pointing at the ephemeral prefix on `cdn.linqapp.com` | 15 minutes per signed URL — re-fetch via the API for a fresh URL | + + Inbound media you receive over webhooks uses the same layout your outbound sends produce, so the URL you store and the URL you build look identical — no special casing in your client. + + ## Ephemeral Attachments (Privacy Tier) + + For regulated or sensitive content, opt in to the **ephemeral attachments** tier by contacting your Linq support contact. You can request it at two scopes: + + | Scope | Effect | + |---|---| + | **Partner-wide** | Every outbound and inbound attachment on every phone number under your account is routed through the ephemeral tier. | + | **Per phone number** | Only the specified phone numbers route their attachments through the ephemeral tier. The rest stay on the persistent tier. | + + **Behavioral differences vs the persistent default:** + + | Aspect | Persistent | Ephemeral | + |---|---|---| + | Download URL form | Long-lived CDN URL | Pre-signed URL with short TTL | + | Retention floor | Indefinite (until you call `DELETE`) | **Hard backstop: 1 day** — even without an explicit `DELETE`, the platform removes the underlying bytes after 24 hours | + | URL re-fetch | Not required | Fetch via `GET /v3/attachments/{attachmentId}` for a fresh signed URL after TTL expiry | + | Cross-partner isolation | Enforced | Enforced | + + **When to choose ephemeral:** + + - Your downstream system processes the file immediately on receipt and does not need to re-read it later. + - You have a compliance requirement that the platform must not retain attachments beyond a short window. + - The content is high-sensitivity (PHI, financial documents, identity verification) and you do not want it sitting behind a long-lived URL. + + **Important:** ephemeral applies in *both directions* — outbound files you upload **and** inbound media received by the phone numbers in that scope. Download bytes you need to keep promptly, or fetch a fresh signed URL via the API when needed. + + ## Deleting an Attachment + + To permanently remove an attachment you own, use: + + ```http + DELETE /v3/attachments/{attachmentId} + Authorization: Bearer + ``` + + **What this does:** + + 1. Verifies the attachment is owned by your account. Returns `404` otherwise. + 2. Removes the underlying file from Linq storage. + 3. Records an audit entry (timestamp, partner, attachment id). + + **Response codes:** + + | Status | Meaning | + |---|---| + | `204 No Content` | Deletion succeeded. The attachment is removed from Linq storage. | + | `400 Bad Request` | `attachmentId` is not a valid UUID. | + | `401 Unauthorized` | Missing or invalid API key. | + | `404 Not Found` | Attachment does not exist or is not owned by your account. | + | `500 Internal Server Error` | Transient infrastructure issue — safe to retry. | + + **Effect on message history:** + + - Messages that referenced the deleted attachment remain visible. + - The message part that pointed at the attachment is preserved with no attachment reference. + - Webhook payloads previously delivered to you retain the original URL string, but downloads from that URL return `404` going forward. + + Deletion is **irreversible**. Once `204` is returned, the bytes are gone — there is no undelete. + + ## Inbound Media Flow + + When one of your phone numbers receives a message with media (image, video, audio, document), the platform: + + 1. Stores the file under your partner account. + 2. Records metadata linked to the inbound message. + 3. Delivers a webhook whose `parts[]` array includes a `media` part with a `url` pointing at `cdn.linqapp.com`. + 4. If the receiving phone is opted in to ephemeral, the `url` is a short-TTL signed URL. + + You can acknowledge the webhook without fetching the file inline, and lazy-load via `GET /v3/attachments/{attachmentId}` later. For ephemeral attachments, retrieving via the API always returns a freshly-signed URL. + + ## Data Lifecycle Summary + + | Data | Persistent tier | Ephemeral tier | + |---|---|---| + | Attachment bytes | Retained until you `DELETE` | **Auto-removed after 1 day**, also removable via `DELETE` | + | Attachment metadata (id, filename, mime type, size) | Retained until you `DELETE` | Removed alongside the bytes | + | Message body & parts | Retained per message-retention policy | Retained per message-retention policy | + | Audit log of deletions | Retained per platform retention policy | Retained per platform retention policy | + + **In transit:** TLS 1.2+ everywhere. **At rest:** AES-256 (server-side encryption). + + ## Compliance Checklist + + If you're integrating Linq under a security or privacy review, here is the short list: + + - Allowlist exactly one outbound domain: `cdn.linqapp.com`. + - Decide whether you need ephemeral attachments (high-sensitivity content) — request enablement through your Linq support contact. + - Implement `DELETE /v3/attachments/{attachmentId}` calls in your deletion workflow. + - Persist any attachments your application needs long-term — Linq is the authoritative source until you delete, but the ephemeral tier auto-purges after 1 day. + - For audit: every deletion is logged on Linq's side. Surface a confirmation in your application UI based on the `204` response. + - For end-user "right to delete" requests: enumerate attachment ids and `DELETE` each. The platform does not provide a partner-wide wipe endpoint — deletion is per-attachment by design. """ from .resources.attachments import AsyncAttachmentsResourceWithStreamingResponse diff --git a/src/linq/_files.py b/src/linq/_files.py index 0fdce17..76da9e0 100644 --- a/src/linq/_files.py +++ b/src/linq/_files.py @@ -99,7 +99,7 @@ async def async_to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles elif is_sequence_t(files): files = [(key, await _async_transform_file(file)) for key, file in files] else: - raise TypeError("Unexpected file type input {type(files)}, expected mapping or sequence") + raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence") return files diff --git a/src/linq/_models.py b/src/linq/_models.py index e22dd2a..69f41a6 100644 --- a/src/linq/_models.py +++ b/src/linq/_models.py @@ -25,7 +25,9 @@ ClassVar, Protocol, Required, + Annotated, ParamSpec, + TypeAlias, TypedDict, TypeGuard, final, @@ -79,7 +81,15 @@ from ._constants import RAW_RESPONSE_HEADER if TYPE_CHECKING: + from pydantic import GetCoreSchemaHandler, ValidatorFunctionWrapHandler + from pydantic_core import CoreSchema, core_schema from pydantic_core.core_schema import ModelField, ModelSchema, LiteralSchema, ModelFieldsSchema +else: + try: + from pydantic_core import CoreSchema, core_schema + except ImportError: + CoreSchema = None + core_schema = None __all__ = ["BaseModel", "GenericModel"] @@ -396,6 +406,76 @@ def model_dump_json( ) +class _EagerIterable(list[_T], Generic[_T]): + """ + Accepts any Iterable[T] input (including generators), consumes it + eagerly, and validates all items upfront. + + Validation preserves the original container type where possible + (e.g. a set[T] stays a set[T]). Serialization (model_dump / JSON) + always emits a list — round-tripping through model_dump() will not + restore the original container type. + """ + + @classmethod + def __get_pydantic_core_schema__( + cls, + source_type: Any, + handler: GetCoreSchemaHandler, + ) -> CoreSchema: + (item_type,) = get_args(source_type) or (Any,) + item_schema: CoreSchema = handler.generate_schema(item_type) + list_of_items_schema: CoreSchema = core_schema.list_schema(item_schema) + + return core_schema.no_info_wrap_validator_function( + cls._validate, + list_of_items_schema, + serialization=core_schema.plain_serializer_function_ser_schema( + cls._serialize, + info_arg=False, + ), + ) + + @staticmethod + def _validate(v: Iterable[_T], handler: "ValidatorFunctionWrapHandler") -> Any: + original_type: type[Any] = type(v) + + # Normalize to list so list_schema can validate each item + if isinstance(v, list): + items: list[_T] = v + else: + try: + items = list(v) + except TypeError as e: + raise TypeError("Value is not iterable") from e + + # Validate items against the inner schema + validated: list[_T] = handler(items) + + # Reconstruct original container type + if original_type is list: + return validated + # str(list) produces the list's repr, not a string built from items, + # so skip reconstruction for str and its subclasses. + if issubclass(original_type, str): + return validated + try: + return original_type(validated) + except (TypeError, ValueError): + # If the type cannot be reconstructed, just return the validated list + return validated + + @staticmethod + def _serialize(v: Iterable[_T]) -> list[_T]: + """Always serialize as a list so Pydantic's JSON encoder is happy.""" + if isinstance(v, list): + return v + return list(v) + + +EagerIterable: TypeAlias = Annotated[Iterable[_T], _EagerIterable] + + def _construct_field(value: object, field: FieldInfo, key: str) -> object: if value is None: return field_get_default(field) diff --git a/src/linq/_version.py b/src/linq/_version.py index 57ea29d..11cdca6 100644 --- a/src/linq/_version.py +++ b/src/linq/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "linq" -__version__ = "0.8.0" # x-release-please-version +__version__ = "0.9.0" # x-release-please-version diff --git a/src/linq/resources/attachments.py b/src/linq/resources/attachments.py index 1f66942..faf3822 100644 --- a/src/linq/resources/attachments.py +++ b/src/linq/resources/attachments.py @@ -5,7 +5,7 @@ import httpx from ..types import SupportedContentType, attachment_create_params -from .._types import Body, Query, Headers, NotGiven, not_given +from .._types import Body, Query, Headers, NoneType, NotGiven, not_given from .._utils import path_template, maybe_transform, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource @@ -87,6 +87,122 @@ class AttachmentsResource(SyncAPIResource): - **URL-based (`url` field):** 10MB maximum - **Pre-upload (`attachment_id`):** 100MB maximum + + ## Security & Ownership + + Every attachment is bound to the partner account that created or received it. The API enforces ownership on every operation that touches an attachment — sending, retrieving, deleting. + + **What this means for you:** + + - An attachment created under your API key can only be referenced by your API key. + - Submitting another partner's `attachment_id` returns `404 Not Found`. We do not disclose whether the id exists or belongs to someone else. + - Submitting a CDN URL that resolves to another partner's attachment is rejected before the send is attempted. + - Ownership enforcement applies uniformly across send, create-chat, voice memo, retrieve, and delete operations. + + Every attachment-affecting endpoint requires a valid partner API key. Unauthenticated calls return `401 Unauthorized`. + + ## Attachment URL Patterns + + Attachment URLs in API responses and webhook payloads use one of two layouts, depending on the attachment's tier: + + | Tier | URL pattern | TTL | + |---|---|---| + | Persistent (default) | `https://cdn.linqapp.com/attachments/partners/{partner_id}/{attachment_id}/{filename}` | Long-lived | + | Ephemeral | Pre-signed URL pointing at the ephemeral prefix on `cdn.linqapp.com` | 15 minutes per signed URL — re-fetch via the API for a fresh URL | + + Inbound media you receive over webhooks uses the same layout your outbound sends produce, so the URL you store and the URL you build look identical — no special casing in your client. + + ## Ephemeral Attachments (Privacy Tier) + + For regulated or sensitive content, opt in to the **ephemeral attachments** tier by contacting your Linq support contact. You can request it at two scopes: + + | Scope | Effect | + |---|---| + | **Partner-wide** | Every outbound and inbound attachment on every phone number under your account is routed through the ephemeral tier. | + | **Per phone number** | Only the specified phone numbers route their attachments through the ephemeral tier. The rest stay on the persistent tier. | + + **Behavioral differences vs the persistent default:** + + | Aspect | Persistent | Ephemeral | + |---|---|---| + | Download URL form | Long-lived CDN URL | Pre-signed URL with short TTL | + | Retention floor | Indefinite (until you call `DELETE`) | **Hard backstop: 1 day** — even without an explicit `DELETE`, the platform removes the underlying bytes after 24 hours | + | URL re-fetch | Not required | Fetch via `GET /v3/attachments/{attachmentId}` for a fresh signed URL after TTL expiry | + | Cross-partner isolation | Enforced | Enforced | + + **When to choose ephemeral:** + + - Your downstream system processes the file immediately on receipt and does not need to re-read it later. + - You have a compliance requirement that the platform must not retain attachments beyond a short window. + - The content is high-sensitivity (PHI, financial documents, identity verification) and you do not want it sitting behind a long-lived URL. + + **Important:** ephemeral applies in *both directions* — outbound files you upload **and** inbound media received by the phone numbers in that scope. Download bytes you need to keep promptly, or fetch a fresh signed URL via the API when needed. + + ## Deleting an Attachment + + To permanently remove an attachment you own, use: + + ```http + DELETE /v3/attachments/{attachmentId} + Authorization: Bearer + ``` + + **What this does:** + + 1. Verifies the attachment is owned by your account. Returns `404` otherwise. + 2. Removes the underlying file from Linq storage. + 3. Records an audit entry (timestamp, partner, attachment id). + + **Response codes:** + + | Status | Meaning | + |---|---| + | `204 No Content` | Deletion succeeded. The attachment is removed from Linq storage. | + | `400 Bad Request` | `attachmentId` is not a valid UUID. | + | `401 Unauthorized` | Missing or invalid API key. | + | `404 Not Found` | Attachment does not exist or is not owned by your account. | + | `500 Internal Server Error` | Transient infrastructure issue — safe to retry. | + + **Effect on message history:** + + - Messages that referenced the deleted attachment remain visible. + - The message part that pointed at the attachment is preserved with no attachment reference. + - Webhook payloads previously delivered to you retain the original URL string, but downloads from that URL return `404` going forward. + + Deletion is **irreversible**. Once `204` is returned, the bytes are gone — there is no undelete. + + ## Inbound Media Flow + + When one of your phone numbers receives a message with media (image, video, audio, document), the platform: + + 1. Stores the file under your partner account. + 2. Records metadata linked to the inbound message. + 3. Delivers a webhook whose `parts[]` array includes a `media` part with a `url` pointing at `cdn.linqapp.com`. + 4. If the receiving phone is opted in to ephemeral, the `url` is a short-TTL signed URL. + + You can acknowledge the webhook without fetching the file inline, and lazy-load via `GET /v3/attachments/{attachmentId}` later. For ephemeral attachments, retrieving via the API always returns a freshly-signed URL. + + ## Data Lifecycle Summary + + | Data | Persistent tier | Ephemeral tier | + |---|---|---| + | Attachment bytes | Retained until you `DELETE` | **Auto-removed after 1 day**, also removable via `DELETE` | + | Attachment metadata (id, filename, mime type, size) | Retained until you `DELETE` | Removed alongside the bytes | + | Message body & parts | Retained per message-retention policy | Retained per message-retention policy | + | Audit log of deletions | Retained per platform retention policy | Retained per platform retention policy | + + **In transit:** TLS 1.2+ everywhere. **At rest:** AES-256 (server-side encryption). + + ## Compliance Checklist + + If you're integrating Linq under a security or privacy review, here is the short list: + + - Allowlist exactly one outbound domain: `cdn.linqapp.com`. + - Decide whether you need ephemeral attachments (high-sensitivity content) — request enablement through your Linq support contact. + - Implement `DELETE /v3/attachments/{attachmentId}` calls in your deletion workflow. + - Persist any attachments your application needs long-term — Linq is the authoritative source until you delete, but the ephemeral tier auto-purges after 1 day. + - For audit: every deletion is logged on Linq's side. Surface a confirmation in your application UI based on the `204` response. + - For end-user "right to delete" requests: enumerate attachment ids and `DELETE` each. The platform does not provide a partner-wide wipe endpoint — deletion is per-attachment by design. """ @cached_property @@ -275,8 +391,10 @@ def retrieve( timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AttachmentRetrieveResponse: """ - Retrieve metadata for a specific attachment including its status, file - information, and URLs for downloading. + Retrieve metadata for a specific attachment including file information, and URLs + for downloading. + + `status`: (**deprecated** — will be removed in a future API version) Args: extra_headers: Send extra headers @@ -297,6 +415,40 @@ def retrieve( cast_to=AttachmentRetrieveResponse, ) + def delete( + self, + attachment_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Permanently delete an attachment owned by the authenticated partner. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not attachment_id: + raise ValueError(f"Expected a non-empty value for `attachment_id` but received {attachment_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + path_template("/v3/attachments/{attachment_id}", attachment_id=attachment_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + class AsyncAttachmentsResource(AsyncAPIResource): """ @@ -362,6 +514,122 @@ class AsyncAttachmentsResource(AsyncAPIResource): - **URL-based (`url` field):** 10MB maximum - **Pre-upload (`attachment_id`):** 100MB maximum + + ## Security & Ownership + + Every attachment is bound to the partner account that created or received it. The API enforces ownership on every operation that touches an attachment — sending, retrieving, deleting. + + **What this means for you:** + + - An attachment created under your API key can only be referenced by your API key. + - Submitting another partner's `attachment_id` returns `404 Not Found`. We do not disclose whether the id exists or belongs to someone else. + - Submitting a CDN URL that resolves to another partner's attachment is rejected before the send is attempted. + - Ownership enforcement applies uniformly across send, create-chat, voice memo, retrieve, and delete operations. + + Every attachment-affecting endpoint requires a valid partner API key. Unauthenticated calls return `401 Unauthorized`. + + ## Attachment URL Patterns + + Attachment URLs in API responses and webhook payloads use one of two layouts, depending on the attachment's tier: + + | Tier | URL pattern | TTL | + |---|---|---| + | Persistent (default) | `https://cdn.linqapp.com/attachments/partners/{partner_id}/{attachment_id}/{filename}` | Long-lived | + | Ephemeral | Pre-signed URL pointing at the ephemeral prefix on `cdn.linqapp.com` | 15 minutes per signed URL — re-fetch via the API for a fresh URL | + + Inbound media you receive over webhooks uses the same layout your outbound sends produce, so the URL you store and the URL you build look identical — no special casing in your client. + + ## Ephemeral Attachments (Privacy Tier) + + For regulated or sensitive content, opt in to the **ephemeral attachments** tier by contacting your Linq support contact. You can request it at two scopes: + + | Scope | Effect | + |---|---| + | **Partner-wide** | Every outbound and inbound attachment on every phone number under your account is routed through the ephemeral tier. | + | **Per phone number** | Only the specified phone numbers route their attachments through the ephemeral tier. The rest stay on the persistent tier. | + + **Behavioral differences vs the persistent default:** + + | Aspect | Persistent | Ephemeral | + |---|---|---| + | Download URL form | Long-lived CDN URL | Pre-signed URL with short TTL | + | Retention floor | Indefinite (until you call `DELETE`) | **Hard backstop: 1 day** — even without an explicit `DELETE`, the platform removes the underlying bytes after 24 hours | + | URL re-fetch | Not required | Fetch via `GET /v3/attachments/{attachmentId}` for a fresh signed URL after TTL expiry | + | Cross-partner isolation | Enforced | Enforced | + + **When to choose ephemeral:** + + - Your downstream system processes the file immediately on receipt and does not need to re-read it later. + - You have a compliance requirement that the platform must not retain attachments beyond a short window. + - The content is high-sensitivity (PHI, financial documents, identity verification) and you do not want it sitting behind a long-lived URL. + + **Important:** ephemeral applies in *both directions* — outbound files you upload **and** inbound media received by the phone numbers in that scope. Download bytes you need to keep promptly, or fetch a fresh signed URL via the API when needed. + + ## Deleting an Attachment + + To permanently remove an attachment you own, use: + + ```http + DELETE /v3/attachments/{attachmentId} + Authorization: Bearer + ``` + + **What this does:** + + 1. Verifies the attachment is owned by your account. Returns `404` otherwise. + 2. Removes the underlying file from Linq storage. + 3. Records an audit entry (timestamp, partner, attachment id). + + **Response codes:** + + | Status | Meaning | + |---|---| + | `204 No Content` | Deletion succeeded. The attachment is removed from Linq storage. | + | `400 Bad Request` | `attachmentId` is not a valid UUID. | + | `401 Unauthorized` | Missing or invalid API key. | + | `404 Not Found` | Attachment does not exist or is not owned by your account. | + | `500 Internal Server Error` | Transient infrastructure issue — safe to retry. | + + **Effect on message history:** + + - Messages that referenced the deleted attachment remain visible. + - The message part that pointed at the attachment is preserved with no attachment reference. + - Webhook payloads previously delivered to you retain the original URL string, but downloads from that URL return `404` going forward. + + Deletion is **irreversible**. Once `204` is returned, the bytes are gone — there is no undelete. + + ## Inbound Media Flow + + When one of your phone numbers receives a message with media (image, video, audio, document), the platform: + + 1. Stores the file under your partner account. + 2. Records metadata linked to the inbound message. + 3. Delivers a webhook whose `parts[]` array includes a `media` part with a `url` pointing at `cdn.linqapp.com`. + 4. If the receiving phone is opted in to ephemeral, the `url` is a short-TTL signed URL. + + You can acknowledge the webhook without fetching the file inline, and lazy-load via `GET /v3/attachments/{attachmentId}` later. For ephemeral attachments, retrieving via the API always returns a freshly-signed URL. + + ## Data Lifecycle Summary + + | Data | Persistent tier | Ephemeral tier | + |---|---|---| + | Attachment bytes | Retained until you `DELETE` | **Auto-removed after 1 day**, also removable via `DELETE` | + | Attachment metadata (id, filename, mime type, size) | Retained until you `DELETE` | Removed alongside the bytes | + | Message body & parts | Retained per message-retention policy | Retained per message-retention policy | + | Audit log of deletions | Retained per platform retention policy | Retained per platform retention policy | + + **In transit:** TLS 1.2+ everywhere. **At rest:** AES-256 (server-side encryption). + + ## Compliance Checklist + + If you're integrating Linq under a security or privacy review, here is the short list: + + - Allowlist exactly one outbound domain: `cdn.linqapp.com`. + - Decide whether you need ephemeral attachments (high-sensitivity content) — request enablement through your Linq support contact. + - Implement `DELETE /v3/attachments/{attachmentId}` calls in your deletion workflow. + - Persist any attachments your application needs long-term — Linq is the authoritative source until you delete, but the ephemeral tier auto-purges after 1 day. + - For audit: every deletion is logged on Linq's side. Surface a confirmation in your application UI based on the `204` response. + - For end-user "right to delete" requests: enumerate attachment ids and `DELETE` each. The platform does not provide a partner-wide wipe endpoint — deletion is per-attachment by design. """ @cached_property @@ -550,8 +818,10 @@ async def retrieve( timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AttachmentRetrieveResponse: """ - Retrieve metadata for a specific attachment including its status, file - information, and URLs for downloading. + Retrieve metadata for a specific attachment including file information, and URLs + for downloading. + + `status`: (**deprecated** — will be removed in a future API version) Args: extra_headers: Send extra headers @@ -572,6 +842,40 @@ async def retrieve( cast_to=AttachmentRetrieveResponse, ) + async def delete( + self, + attachment_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = not_given, + ) -> None: + """ + Permanently delete an attachment owned by the authenticated partner. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not attachment_id: + raise ValueError(f"Expected a non-empty value for `attachment_id` but received {attachment_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + path_template("/v3/attachments/{attachment_id}", attachment_id=attachment_id), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + class AttachmentsResourceWithRawResponse: def __init__(self, attachments: AttachmentsResource) -> None: @@ -583,6 +887,9 @@ def __init__(self, attachments: AttachmentsResource) -> None: self.retrieve = to_raw_response_wrapper( attachments.retrieve, ) + self.delete = to_raw_response_wrapper( + attachments.delete, + ) class AsyncAttachmentsResourceWithRawResponse: @@ -595,6 +902,9 @@ def __init__(self, attachments: AsyncAttachmentsResource) -> None: self.retrieve = async_to_raw_response_wrapper( attachments.retrieve, ) + self.delete = async_to_raw_response_wrapper( + attachments.delete, + ) class AttachmentsResourceWithStreamingResponse: @@ -607,6 +917,9 @@ def __init__(self, attachments: AttachmentsResource) -> None: self.retrieve = to_streamed_response_wrapper( attachments.retrieve, ) + self.delete = to_streamed_response_wrapper( + attachments.delete, + ) class AsyncAttachmentsResourceWithStreamingResponse: @@ -619,3 +932,6 @@ def __init__(self, attachments: AsyncAttachmentsResource) -> None: self.retrieve = async_to_streamed_response_wrapper( attachments.retrieve, ) + self.delete = async_to_streamed_response_wrapper( + attachments.delete, + ) diff --git a/src/linq/types/attachment_create_response.py b/src/linq/types/attachment_create_response.py index 7e5093a..dbe180b 100644 --- a/src/linq/types/attachment_create_response.py +++ b/src/linq/types/attachment_create_response.py @@ -11,10 +11,7 @@ class AttachmentCreateResponse(BaseModel): attachment_id: str - """ - Unique identifier for the attachment (for status checks via GET - /v3/attachments/{id}) - """ + """Unique identifier for the attachment""" download_url: str """Permanent CDN URL for the file. diff --git a/src/linq/types/attachment_retrieve_response.py b/src/linq/types/attachment_retrieve_response.py index 92e3a07..0404e9b 100644 --- a/src/linq/types/attachment_retrieve_response.py +++ b/src/linq/types/attachment_retrieve_response.py @@ -65,7 +65,10 @@ class AttachmentRetrieveResponse(BaseModel): """Size of the attachment in bytes""" status: Literal["pending", "complete", "failed"] - """Current upload/processing status""" + """ + **DEPRECATED:** This field is deprecated and will be removed in a future API + version. + """ download_url: Optional[str] = None """URL to download the attachment""" diff --git a/src/linq/types/chat.py b/src/linq/types/chat.py index 1d0138d..75463f9 100644 --- a/src/linq/types/chat.py +++ b/src/linq/types/chat.py @@ -72,7 +72,10 @@ class Chat(BaseModel): """ is_archived: bool - """Whether the chat is archived""" + """ + **DEPRECATED:** This field is deprecated and will be removed in a future API + version. + """ is_group: bool """Whether this is a group chat""" diff --git a/tests/api_resources/test_attachments.py b/tests/api_resources/test_attachments.py index e29ceef..0d559e4 100644 --- a/tests/api_resources/test_attachments.py +++ b/tests/api_resources/test_attachments.py @@ -102,6 +102,48 @@ def test_path_params_retrieve(self, client: LinqAPIV3) -> None: "", ) + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_method_delete(self, client: LinqAPIV3) -> None: + attachment = client.attachments.delete( + "abc12345-1234-5678-9abc-def012345678", + ) + assert attachment is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_raw_response_delete(self, client: LinqAPIV3) -> None: + response = client.attachments.with_raw_response.delete( + "abc12345-1234-5678-9abc-def012345678", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + attachment = response.parse() + assert attachment is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_streaming_response_delete(self, client: LinqAPIV3) -> None: + with client.attachments.with_streaming_response.delete( + "abc12345-1234-5678-9abc-def012345678", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + attachment = response.parse() + assert attachment is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + def test_path_params_delete(self, client: LinqAPIV3) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `attachment_id` but received ''"): + client.attachments.with_raw_response.delete( + "", + ) + class TestAsyncAttachments: parametrize = pytest.mark.parametrize( @@ -189,3 +231,45 @@ async def test_path_params_retrieve(self, async_client: AsyncLinqAPIV3) -> None: await async_client.attachments.with_raw_response.retrieve( "", ) + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_method_delete(self, async_client: AsyncLinqAPIV3) -> None: + attachment = await async_client.attachments.delete( + "abc12345-1234-5678-9abc-def012345678", + ) + assert attachment is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_raw_response_delete(self, async_client: AsyncLinqAPIV3) -> None: + response = await async_client.attachments.with_raw_response.delete( + "abc12345-1234-5678-9abc-def012345678", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + attachment = await response.parse() + assert attachment is None + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncLinqAPIV3) -> None: + async with async_client.attachments.with_streaming_response.delete( + "abc12345-1234-5678-9abc-def012345678", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + attachment = await response.parse() + assert attachment is None + + assert cast(Any, response.is_closed) is True + + @pytest.mark.skip(reason="Mock server tests are disabled") + @parametrize + async def test_path_params_delete(self, async_client: AsyncLinqAPIV3) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `attachment_id` but received ''"): + await async_client.attachments.with_raw_response.delete( + "", + ) diff --git a/tests/test_models.py b/tests/test_models.py index c735e0b..40fa36b 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,7 +1,8 @@ import json -from typing import TYPE_CHECKING, Any, Dict, List, Union, Optional, cast +from typing import TYPE_CHECKING, Any, Dict, List, Union, Iterable, Optional, cast from datetime import datetime, timezone -from typing_extensions import Literal, Annotated, TypeAliasType +from collections import deque +from typing_extensions import Literal, Annotated, TypedDict, TypeAliasType import pytest import pydantic @@ -9,7 +10,7 @@ from linq._utils import PropertyInfo from linq._compat import PYDANTIC_V1, parse_obj, model_dump, model_json -from linq._models import DISCRIMINATOR_CACHE, BaseModel, construct_type +from linq._models import DISCRIMINATOR_CACHE, BaseModel, EagerIterable, construct_type class BasicModel(BaseModel): @@ -961,3 +962,56 @@ def __getattr__(self, attr: str) -> Item: ... assert model.a.prop == 1 assert isinstance(model.a, Item) assert model.other == "foo" + + +# NOTE: Workaround for Pydantic Iterable behavior. +# Iterable fields are replaced with a ValidatorIterator and may be consumed +# during serialization, which can cause subsequent dumps to return empty data. +# See: https://github.com/pydantic/pydantic/issues/9541 +@pytest.mark.parametrize( + "data, expected_validated", + [ + ([1, 2, 3], [1, 2, 3]), + ((1, 2, 3), (1, 2, 3)), + (set([1, 2, 3]), set([1, 2, 3])), + (iter([1, 2, 3]), [1, 2, 3]), + ([], []), + ((x for x in [1, 2, 3]), [1, 2, 3]), + (map(lambda x: x, [1, 2, 3]), [1, 2, 3]), + (frozenset([1, 2, 3]), frozenset([1, 2, 3])), + (deque([1, 2, 3]), deque([1, 2, 3])), + ], + ids=["list", "tuple", "set", "iterator", "empty", "generator", "map", "frozenset", "deque"], +) +@pytest.mark.skipif(PYDANTIC_V1, reason="this is only supported in pydantic v2") +def test_iterable_construction(data: Iterable[int], expected_validated: Iterable[int]) -> None: + class TypeWithIterable(TypedDict): + items: EagerIterable[int] + + class Model(BaseModel): + data: TypeWithIterable + + m = Model.model_validate({"data": {"items": data}}) + assert m.data["items"] == expected_validated + + # Verify repeated dumps don't lose data (the original bug) + assert m.model_dump()["data"]["items"] == list(expected_validated) + assert m.model_dump()["data"]["items"] == list(expected_validated) + + +@pytest.mark.skipif(PYDANTIC_V1, reason="this is only supported in pydantic v2") +def test_iterable_construction_str_falls_back_to_list() -> None: + # str is iterable (over chars), but str(list_of_chars) produces the list's repr + # rather than reconstructing a string from items. We special-case str to fall + # back to list instead of attempting reconstruction. + class TypeWithIterable(TypedDict): + items: EagerIterable[str] + + class Model(BaseModel): + data: TypeWithIterable + + m = Model.model_validate({"data": {"items": "hello"}}) + + # falls back to list of chars rather than calling str(["h", "e", "l", "l", "o"]) + assert m.data["items"] == ["h", "e", "l", "l", "o"] + assert m.model_dump()["data"]["items"] == ["h", "e", "l", "l", "o"]