From 54e294dd47ce6a3b0fce7e05ac6e20400e6bcbb3 Mon Sep 17 00:00:00 2001 From: "jinzheng.architect" Date: Fri, 16 Oct 2026 15:33:44 +0800 Subject: [PATCH] Add M-Team metafile download through the signed link M-Team serves a .torrent only through a signed link: genDlToken returns it, and fetching it may redirect once. Add a linked metafile route for that flow without widening the direct contract TJUPT uses. - site: NewLinkedMetafileFetchConfig declares a linked route. The new MaxLinkRequests limit and LinkRequestsAttempted usage count the requests before the one metafile GET; MaxRequests still means that GET and RedirectsFollowed stays 0. Both fields are omitempty, so TJUPT reports and sealed binding records keep their exact bytes, and Record.Validate bounds the link count. - httpguard: SecretLink holds a signed URL that redacts itself when formatted, and GetLinkOnce sends one credential-free GET of it, reporting a redirect target only when the caller approves it. - mteam: route mteam.download_by_token.v1 POSTs genDlToken, accepts only an HTTPS dlv2 link on an M-Team host signed for the requested ID, pauses 3s, GETs it on a fresh client bound to that host, and follows one redirect only to an HTTPS m-team.cc or m-team.io host on the default port. Not-found, daily-limit, and burst refusals map to not_found and rate_limited. - cli: site metafile fetch accepts --api-key-stdin, names the required credential flag before reading stdin, and reports the link accounting, linked scope, evidence basis, and warnings. not_found joins the public stop reasons. Live, the route was exercised only against IDs with no torrent: genDlToken signs a link for any ID, so not_found is read from the link's JSON answer. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- docs/ADDING_A_SITE.md | 20 +- docs/ARCHITECTURE.md | 34 +- docs/AUTOMATION.md | 6 +- docs/FEATURES.md | 9 +- docs/MTEAM_ADAPTER.md | 131 ++++-- docs/README.md | 2 +- docs/THREAT_MODEL.md | 38 +- docs/guide/metafiles.md | 19 +- docs/guide/sites.md | 4 +- internal/cli/run.go | 2 +- internal/cli/site_contract_test.go | 8 +- internal/cli/site_metafile.go | 112 +++++- internal/cli/site_metafile_test.go | 195 ++++++++- internal/site/httpguard/client.go | 122 ++++++ internal/site/httpguard/link_test.go | 195 +++++++++ internal/site/metafile.go | 113 ++++-- internal/site/metafile_test.go | 59 +++ internal/site/mteam/adapter.go | 7 +- internal/site/mteam/adapter_test.go | 2 +- internal/site/mteam/metafile.go | 515 ++++++++++++++++++++++++ internal/site/mteam/metafile_test.go | 370 +++++++++++++++++ internal/site/sitetest/sitetest.go | 6 +- internal/sitebinding/repository_test.go | 86 ++++ internal/sitebinding/types.go | 1 + 25 files changed, 1912 insertions(+), 149 deletions(-) create mode 100644 internal/site/httpguard/link_test.go create mode 100644 internal/site/mteam/metafile.go create mode 100644 internal/site/mteam/metafile_test.go diff --git a/README.md b/README.md index 53c3aa7..a6d462b 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,8 @@ capabilities at the edge, not assumptions in the core domain model. and password login with an optional two-step code that issues the session cookie; and an experimental M-Team adapter with session, account, search, and - detail reads through the official API and a site-issued API key. + detail reads plus acknowledged metafile fetch through the official API and a + site-issued API key. - **Downloaders:** qBittorrent and Transmission reads, plus reviewed stopped adoption, recheck/start, stop, and keep-data removal of one exact job. - **Reconciliation:** one report that keeps site, downloader, metafile, and @@ -72,7 +73,7 @@ The complete inventory, including what is deliberately not implemented, is in |---|---|---| | Zero-write | `torrent inspect/verify`, `storage probe/map`, `seed discover/plan`, `client status/list`, ordinary `site` reads and `site bonus review`, `reconcile report`, and every `plan`, `status`, `list`, and `inspect` subcommand | None. Reads can still update atime, hydrate offline placeholders, or be recorded by the remote side. | | Private store | `metafile store init/import`, `storage profile create`, `storage index refresh/refresh-discover`, `reconcile refresh-report`, `site bonus exchange prepare` | The explicit command itself. Owner-only and no-clobber; not encrypted. | -| Tracker-visible | `site metafile fetch` (one GET), `site bonus exchange submit` (at most one POST), `site login` (one POST and one verifying GET) | `--acknowledge-site-effect`, `--acknowledge-bonus-exchange`; `site login` is the command itself, with the cookie saved only to an owner-only file or a pipe | +| Tracker-visible | `site metafile fetch` (one GET; on M-Team, a token POST and the signed-link GET, plus at most one redirect hop), `site bonus exchange submit` (at most one POST), `site login` (one POST and one verifying GET) | `--acknowledge-site-effect`, `--acknowledge-bonus-exchange`; `site login` is the command itself, with the cookie saved only to an owner-only file or a pipe | | Target filesystem | `seed materialize run/resume/abandon` | `--acknowledge-filesystem-write`, `--acknowledge-abandon` | | Downloader | `client adopt/activate/stop/remove run/resume` | `--acknowledge-client-add`, `--acknowledge-client-recheck`, `--acknowledge-client-stop`, `--acknowledge-client-removal`; repeats, re-adds, and observation-only adoption have their own flags | | Source deletion | `seed retire run/resume`, `seed retire parent-cleanup run/resume` | `--acknowledge-source-deletion`, `--acknowledge-empty-parent-removal` | diff --git a/docs/ADDING_A_SITE.md b/docs/ADDING_A_SITE.md index c116a2a..00dd71a 100644 --- a/docs/ADDING_A_SITE.md +++ b/docs/ADDING_A_SITE.md @@ -138,7 +138,11 @@ preflight from the network: - **Opening a session** builds process-local state only. It must reject a canceled context and an undeclared auth method without sending anything. - **Reading** sends at most one request; `MaxRequests` is fixed at one in the - detail, metafile, and bonus-review limits. Each receipt echoes the pinned + detail, metafile, and bonus-review limits. The one exception is a linked + metafile route, declared with `site.NewLinkedMetafileFetchConfig`: before its + one metafile `GET` it may make up to `MaxLinkRequests` (at most two) requests + for a site-issued link, counted in `LinkRequestsAttempted`, and must treat + that link as a secret (`httpguard.SecretLink`). Each receipt echoes the pinned origin and route ID. An invalid input, a done context, or a closed session must fail with zero requests. Their stop reasons are `invalid_reference` or `invalid_selector`, `context_done` (wrapping `context.Canceled`), and @@ -255,23 +259,23 @@ and do it in a separate behavior-preserving commit. | NexusPHP forks, including TJUPT | Cookie sessions match `cookie_header`, and HTML responses match the existing ports. | Page recognition and parsers for that fork, with synthetic fixtures. Forks differ, so do not assume TJUPT's pages. | | Unit3D | Cookie-session web pages fit. | Using its token-authenticated API instead runs into the gaps below. | | Gazelle-based trackers | Cookie sessions fit; their JSON responses need a JSON parser rather than HTML recognition. | Where an API key replaces the session cookie, the gaps below apply. | -| M-Team | Status, account, search, and detail are implemented in `internal/site/mteam` over the JSON API with an API key. | The two-step download: the open gap below. | +| M-Team | Status, account, search, detail, and the signed-link metafile download are implemented in `internal/site/mteam` over the JSON API with an API key. | Bonus commands and reconciliation: the open gaps below. | ## Gaps for API-token sites These are the places that assumed a cookie, HTML, or a single origin. The -M-Team adapter closed what its four reads needed; the rest is design work for -whichever pull request first needs it. Each open item changes a public contract +M-Team adapter closed what its four reads and its download needed; the rest is +design work for whichever pull request first needs it. Each open item changes a public contract or a security control, so it needs its own review. | Gap | Status | Where | What is left | |---|---|---|---| | Only one auth method existed | Done | `domain.AuthMethodAPIKeyHeader` (`api_key_header`); `knownAuthMethod` in `internal/site/descriptor.go` | Nothing. | -| Credential input was cookie-only | Partly done | `--api-key-stdin` and `readAPIKeyCredential` in `internal/cli` serve `site status`, `account`, `search`, and `detail` | `site metafile fetch`, bonus commands, and `reconcile` (`--site-cookie-stdin`, the bundle's `site_cookie`) still take cookies only. | -| The CLI gated on cookies | Partly done | `siteRead` in `internal/cli/site.go` and `site detail` check the method the caller chose | Four `SupportsAuth(domain.AuthMethodCookieHeader)` checks remain, in `site_bonus.go`, `site_metafile.go`, `site_bonus_exchange.go`, and `reconcile.go`. | +| Credential input was cookie-only | Partly done | `--api-key-stdin` and `readAPIKeyCredential` in `internal/cli` serve `site status`, `account`, `search`, and `detail`; `site metafile fetch` reads it with `readEffectfulAPIKeyCredential` | Bonus commands and `reconcile` (`--site-cookie-stdin`, the bundle's `site_cookie`) still take cookies only. | +| The CLI gated on cookies | Partly done | `siteRead` in `internal/cli/site.go`, `site detail`, and `site metafile fetch` check the method the caller chose | Three `SupportsAuth(domain.AuthMethodCookieHeader)` checks remain, in `site_bonus.go`, `site_bonus_exchange.go`, and `reconcile.go`. | | The transport only sent `Cookie` | Done | `httpguard.NewWithHeaderCredential` binds one validated, non-reserved header | Nothing. | | Redaction did not know the header | Done | `security.Redact` covers `x-api-key` header lines and `apiKey`-style fields | Nothing. | | No JSON requests | Done | `httpguard.Client.PostReadOnce`: one bounded, non-replayable POST with no redirect and no retry, covered in the threat model | Nothing for reads. Effectful API calls still need their own acknowledged port. | -| One origin per site | Done for reads | The API origin is the descriptor `BaseURL` | A download served from another host needs a design decision before that host is contacted. | -| The download is two requests | Open | `MetafileFetchLimits.MaxRequests` must be exactly one, and the receipt has one route ID | A new port or versioned limits and receipts for token-then-download, an acknowledgement that names both requests, and handling of a signed URL that is itself a secret. See [MTEAM_ADAPTER.md](MTEAM_ADAPTER.md#not-supported-yet). | +| One origin per site | Done | The API origin is the descriptor `BaseURL`; a signed link and its one redirect may reach only hosts the adapter allowlists (`siteHost` in `internal/site/mteam/metafile.go`), each on a fresh credential-free client | A new site's allowlist needs the same review before its hosts are contacted. | +| The download is two requests | Done | `site.NewLinkedMetafileFetchConfig` declares a linked route; `MetafileFetchLimits.MaxLinkRequests` and `MetafileFetchUsage.LinkRequestsAttempted` count the requests before the one metafile `GET`, and the sealed record checks them; `httpguard.SecretLink` and `GetLinkOnce` keep the signed URL secret | Nothing. Both fields are omitted for direct routes, so TJUPT records are unchanged. See [MTEAM_ADAPTER.md](MTEAM_ADAPTER.md#metafile-download). | | Site-specific CLI text | Done | `detailRouteWarnings` in `internal/cli/site_detail.go` keys the `site detail` warning by route ID; an unlisted route gets only the generic sentence | Add a sentence there when a new detail route has something specific to say. | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 91437d3..3cb0b30 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -699,11 +699,12 @@ uninitialized staging entries are not counted as committed artifacts. metafile artifact: ```text -site metafile fetch --cookie-stdin --acknowledge-site-effect +site metafile fetch (--cookie-stdin | --api-key-stdin) --acknowledge-site-effect --metafile-store DIR SITE REMOTE_ID - -> validate one site, one remote ID, limits, capability, and store - -> read the cookie only after that zero-write preflight succeeds - -> send one bounded GET, with no redirect and no retry + -> validate one site, one remote ID, limits, capability, auth method, and store + -> read the credential only after that zero-write preflight succeeds + -> linked routes only: request a site-issued link, bounded by MaxLinkRequests + -> send one bounded metafile GET, with no automatic redirect and no retry -> strictly validate the complete exact response -> publish only through the existing private, no-clobber store primitive -> after successful artifact import, publish a sealed historical binding @@ -715,7 +716,22 @@ mode. The store must already be initialized; fetch never turns an arbitrary directory into a store. A site adapter must explicitly declare `torrent.metafile.read_effectful`, support the selected stdin authentication method, and validate its own remote-ID syntax without credentials. This keeps -the CLI and report generic when a second site adapter is added. +the CLI and report generic across site adapters. + +Most routes are direct: TJUPT's single cookie-authenticated GET on the site +origin. M-Team's `mteam.download_by_token.v1` is a linked route, declared with +`site.NewLinkedMetafileFetchConfig`. Its session first POSTs the API for a +signed link, pauses for the site's request interval, then GETs that link on a +fresh credential-free client bound to the link's host. A 3xx answer whose +target is an HTTPS host under the adapter's own domains is GET once more on +another such client; any other target, or a second redirect, stops as +`redirect_rejected` without being contacted. `httpguard.SecretLink` carries the +signed link and redirect target, redacts them when formatted, and never puts +them in an error. `MaxRequests` stays one and still counts only the metafile +GET; the token request and a redirect hop are `LinkRequestsAttempted`, bounded +by `MaxLinkRequests` (at most two), and `RedirectsFollowed` stays zero because +no hop is followed by the HTTP stack. The CLI accepts a successful linked fetch +only when the session made exactly `1 + LinkRequestsAttempted` requests. The site-to-metafile relation first becomes an invocation-scoped `observed_exact_variant` only when the store import explicitly returns a valid @@ -729,7 +745,9 @@ the report-only observation. B2 adds a binding-last `site.metafile.binding.v1` commit marker only after the artifact import returns complete success. The sealed record preserves the canonical site ref, adapter origin/route, whole-raw artifact link, bounded -single-request account, and historical observation interval. Its publication +single-request account, and historical observation interval. A linked route +adds its bounded link-request account in fields that direct routes omit, so +TJUPT records keep their exact bytes. Its publication and every load jointly verify the record and referenced private artifact in one operation-bound physical store session. This is not a two-object transaction: an artifact may remain as an unreferenced immutable object if marker publication @@ -751,8 +769,8 @@ post-commit completion is not confirmed. Request attempts and logical store writes are therefore reported separately; neither is inferred from the other or from the overall outcome. -Raw response bytes, request and redirect URLs, cookies, announce URLs, -passkeys, server filenames, object paths, and temporary paths never enter JSON, +Raw response bytes, request and redirect URLs, site-issued download links, +cookies, API keys, announce URLs, passkeys, server filenames, object paths, and temporary paths never enter JSON, human output, errors, or a side record. The ordinary store-root path disclosure remains opt-in. Non-usage failures are reported before the command returns its operational or integrity exit; site fetch itself does not use exit `4`. diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 152e4a5..9d58f0d 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -97,8 +97,8 @@ Per-command details are in | Flag | Used by | Stdin content | |---|---|---| -| `--cookie-stdin` | `site` reads, `site bonus exchange submit` for cookie-only sites, `site metafile fetch` | The complete `Cookie` header value | -| `--api-key-stdin` | `site status`, `site account`, `site search`, and `site detail` for sites that authenticate with an API key (M-Team) | The site-issued API key | +| `--cookie-stdin` | `site` reads, `site bonus exchange submit` for cookie-only sites, `site metafile fetch` for cookie sites (TJUPT) | The complete `Cookie` header value | +| `--api-key-stdin` | `site status`, `site account`, `site search`, `site detail`, and `site metafile fetch` for sites that authenticate with an API key (M-Team) | The site-issued API key | | `--password-stdin` | `client` commands, `seed retire` commands that contact a downloader, and `reconcile` with a downloader | The downloader password | | `--site-cookie-stdin` | `reconcile report` with a live site observation and no downloader | The complete `Cookie` header value | | `--credential-bundle-stdin` | `reconcile report` with both a live site observation and a downloader | `{"schema":"ptctl.credentials/v1","site_cookie":"...","downloader_password":"..."}` | @@ -142,7 +142,7 @@ to proceed if it no longer matches. | Flag | Command | Authorizes | |---|---|---| -| `--acknowledge-site-effect` | `site metafile fetch` | One tracker-visible GET of a private metafile into the private store | +| `--acknowledge-site-effect` | `site metafile fetch` | One tracker-visible GET of a private metafile into the private store, preceded on a linked route (M-Team) by at most two counted requests for a site-issued link | | `--acknowledge-bonus-exchange` | `site bonus exchange submit` | At most one bonus-exchange POST after a durable attempt marker | | `--acknowledge-state-prune` | `site bonus exchange prune` | Replacing one terminal exchange's records with a tombstone | | `--acknowledge-history-forget` | `site bonus exchange forget` | Irreversibly deleting that last historical evidence | diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 00076b9..7bbccb4 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -108,8 +108,13 @@ deliberately does not. For step-by-step usage, see the seeders, leechers, promotion factors, and category names, and torrent detail for one remote ID, through one read-only POST per invocation to the official JSON API, authenticated by a site-issued API key read only from stdin, with - no redirect, proxy, or retry; M-Team metafile download is not implemented - yet; + no redirect, proxy, or retry; +- an explicitly acknowledged M-Team metafile fetch for one remote ID: one + token POST for a signed download link, one credential-free GET of that link, + and at most one further GET only for a redirect to an M-Team HTTPS host, with + the link treated as a secret that is never printed or stored, the link + requests counted separately from the one metafile GET, and the same strict + validation and private-store publication as TJUPT; - qBittorrent and Transmission status and torrent-list reads over HTTPS (or explicit numeric loopback HTTP), with passwords accepted only through stdin; - read-only reconciliation that can first observe one authenticated live site diff --git a/docs/MTEAM_ADAPTER.md b/docs/MTEAM_ADAPTER.md index 2e9e23a..01e5f78 100644 --- a/docs/MTEAM_ADAPTER.md +++ b/docs/MTEAM_ADAPTER.md @@ -4,23 +4,26 @@ M-Team (馒头PT, TP :: mTorrent) is the second experimental site and the first that uses a site-issued API key instead of a session cookie. The adapter talks -only to the official JSON API at `https://api2.m-team.cc` and declares four -read capabilities: +only to M-Team's own hosts, starting at the official JSON API at +`https://api2.m-team.cc`, and declares four reads and one acknowledged +download: - session check (`site status`); - account snapshot (`site account`); - torrent search (`site search`), with category names; -- torrent detail (`site detail`). - -Metafile download is not implemented yet; see -[Not supported yet](#not-supported-yet). The reads were smoke-tested live on -2026-10-16 with a newly created API key: `site status` reported -`authenticated`, `site account` read the profile, `site search` returned results -with category names in both table and JSON output, and `site detail` observed a -public software torrent and reported `not_found` for an ID with no torrent. A -creation time the API returned for that key matched UTC+8, confirming how -[times](#results) are read. The unit tests use synthetic responses shaped after -the public API. +- torrent detail (`site detail`); +- metafile download (`site metafile fetch`), which is tracker-visible and needs + `--acknowledge-site-effect`; see [Metafile download](#metafile-download). + +The reads were smoke-tested live on 2026-10-16 with a newly created API key: +`site status` reported `authenticated`, `site account` read the profile, `site +search` returned results with category names in both table and JSON output, and +`site detail` observed a public software torrent and reported `not_found` for +an ID with no torrent. A creation time the API returned for that key matched +UTC+8, confirming how [times](#results) are read. The download was checked live +the same day for connectivity only, against an ID with no torrent, because the +test account was still in its newbie-task period. The unit tests use synthetic +responses shaped after the public API. ## Getting an API key @@ -40,19 +43,22 @@ printf '%s' "$MTEAM_API_KEY" | ptctl site account --api-key-stdin mteam printf '%s' "$MTEAM_API_KEY" | ptctl site search --api-key-stdin mteam "Ubuntu" printf '%s' "$MTEAM_API_KEY" | ptctl site search --api-key-stdin --output json mteam "Ubuntu" printf '%s' "$MTEAM_API_KEY" | ptctl site detail --api-key-stdin mteam REMOTE_ID +printf '%s' "$MTEAM_API_KEY" | ptctl site metafile fetch --api-key-stdin \ + --acknowledge-site-effect --metafile-store "$PTCTL_STORE" mteam REMOTE_ID ``` To keep the key out of shell history and your environment, pipe it from a password manager instead, for example `op read op://Private/M-Team/api-key | ptctl site account --api-key-stdin mteam`. -Without `--api-key-stdin`, `status`, `account`, `search`, and `detail` fail -with a usage error before anything is read; `--cookie-stdin` is refused because -the adapter does not accept cookies. +Without `--api-key-stdin`, every M-Team command fails with a usage error before +anything is read; `--cookie-stdin` is refused because the adapter does not +accept cookies. ## Requests -Each command sends exactly one request and never retries: +Each read sends exactly one request and never retries (the download takes more; +see [Metafile download](#metafile-download)): | Command | Request | Body | |---|---|---| @@ -61,7 +67,7 @@ Each command sends exactly one request and never retries: | `site detail` | `POST /api/torrent/detail` | a `multipart/form-data` form with the one field `id` | The API exposes these reads as POST requests. All three endpoints only read; -ptctl sends no other endpoint. In particular, `site detail` never calls +the reads send no other endpoint. In particular, `site detail` never calls `/api/torrent/viewHits`, which the website's own detail page calls to count a view. The request uses the same strict transport as every site read: @@ -150,32 +156,80 @@ These lines name the cause instead: | `site CMD timed out: context deadline exceeded` | The 45-second deadline passed. | Check connectivity. | | `site CMD failed` | Anything else: an unexpected HTTP status such as 403, a response that is not JSON, or an unknown API code. | If it persists with a valid key, open an issue with the command and time. Never include the key. | | `site torrent detail read failed` | `site detail` did not observe the torrent. The report's `REQUEST STOP` names the reason, such as `not_found`, `authentication_required`, `rate_limited`, or `unrecognized_response`. | Check the ID and key; wait before trying again after `rate_limited`. | - -## Not supported yet - -**Metafile download.** Downloading a `.torrent` from M-Team takes two -requests: `POST /api/torrent/genDlToken` returns a signed URL that carries a -personal credential, and fetching that URL can redirect to another host. The -site also limits how often one torrent can be downloaded per day. ptctl's -metafile fetch contract allows exactly one acknowledged request to one fixed -origin, with no redirects, and seals that single route in the persisted -`ptctl.site-metafile-binding/v1` record. Supporting M-Team needs a new, -versioned contract that acknowledges both requests by name, treats the signed -URL as a secret that is never printed or stored, pins the download host, and -accounts for the daily limit. That is a security review of its own, so it is -not part of this first adapter. For the same API, see how other tools handle -it: [MoviePilot #6950](https://github.com/jxxghp/MoviePilot/issues/6950), +| `site metafile fetch failed` | `site metafile fetch` stored nothing. The report's `REQUEST STOP` names the reason; see [Metafile download](#metafile-download). | Check the ID and key. After `rate_limited`, wait, and remember the per-torrent daily limit. Open an issue for a persistent `redirect_rejected`, never including the link. | + +## Metafile download + +`site metafile fetch` saves one torrent's exact `.torrent` into the private +store, as described in [metafiles.md](guide/metafiles.md). M-Team hands out the +file only through a signed link, so the route `mteam.download_by_token.v1` takes +two or three requests, in this order, and stops at the first one that fails: + +1. `POST /api/torrent/genDlToken` on `api2.m-team.cc`, with the API key and a + `multipart/form-data` form with the one field `id`. The answer carries a + signed download link. It is accepted only as HTTPS on an M-Team host, with + the path `/api/rss/dlv2`, signed for exactly the requested ID. +2. After a 3-second pause, one `GET` of that link. The API key is not sent: the + signature in the link is the credential. +3. Only when that answer redirects to an HTTPS host under `m-team.cc` or + `m-team.io` on the default port, one `GET` of the target. Any other target, + including another site, a lookalike domain, an explicit port, plain HTTP, + `magnet:`, or a second redirect, stops as `redirect_rejected` without being + contacted. + +The signed link and any redirect target are secrets. Each `GET` uses a fresh, +credential-free connection bound to that one host, with the same strict +transport as the reads otherwise. Neither URL is ever printed, logged, put in +the report, or stored; errors name the cause, not the URL. The last answer must +be the bencoded metafile itself, which is then checked and sealed exactly as for +TJUPT. The API's refusals arrive as HTTP 200 JSON and are mapped to the +report's `REQUEST STOP`: + +| Answer | `REQUEST STOP` | +|---|---| +| The key or link was refused (HTTP 401 or 403, or API code `401`) | `authentication_required` | +| No such torrent (code `1` with the fixed not-found message and no data) | `not_found` | +| The per-torrent daily limit (the site allows 10 downloads of one torrent a day), a request burst, API code `4`, or HTTP 429 | `rate_limited` | +| A link or redirect outside the hosts above | `redirect_rejected` | +| Any other status, media type, or answer | `http_status_rejected`, `content_type_rejected`, `empty_response`, or `unrecognized_response` | + +Each link request may count as a download on the site, even when no metafile +comes back. Keep that in mind on accounts with download conditions, such as +during the newbie-task period. + +**Accounting.** The report and the sealed binding record keep the +single-request shape TJUPT uses and add the link requests next to it. +`max_requests` stays 1 and counts the metafile `GET`. `max_link_requests` is 2, +and `link_requests_attempted` counts the token request plus a redirect hop, so +`requests_made` is 2 or 3. `redirects_followed` stays 0: the redirect hop is a +separate counted request, not one the HTTP stack follows on its own. The +acknowledgement scope is `site_link_requests_then_one_remote_metafile_get`, the +evidence basis starts with `effectful_site_issued_link_get_for_remote_id`, and +the table output adds `LINK REQUEST LIMIT` and `LINK REQUESTS USED`. Direct +routes omit these fields, so TJUPT output and records are unchanged. + +**Live check.** On 2026-10-16 the route was run only against IDs with no +torrent, so no file was downloaded. `genDlToken` signs a link even for an ID +that does not exist, so `not_found` can only be read from the link's answer: +ptctl reported `not_found` with `requests_made` 2, the token request and the +link `GET`. The link points at `api2.m-team.cc`, the API host itself. The +redirect hop for a real torrent has not been observed live yet; whatever host it +uses must pass the allowlist above, or the fetch stops as `redirect_rejected` +before contacting it. For how other tools use the same API, see +[MoviePilot #6950](https://github.com/jxxghp/MoviePilot/issues/6950), [pt-tools #585](https://github.com/sunerpy/pt-tools/pull/585), [Jackett #15744](https://github.com/Jackett/Jackett/issues/15744), and [ptool](https://pkg.go.dev/github.com/sagan/ptool/site/mtorrent). -Until then, download the `.torrent` from the website yourself and import it -into the private store. The file contains your passkey, so keep it private: +A `.torrent` downloaded from the website yourself can still be imported into the +private store instead. The file contains your passkey, so keep it private: ```bash ptctl metafile store import --store "$PTCTL_STORE" release.torrent ``` +## Not supported yet + **Reconciliation.** `reconcile` reads live site detail with a cookie only, so `--site-ref mteam/ID` is refused. `site detail` works on its own. @@ -184,6 +238,7 @@ implemented. ## Fixtures -Tests in `internal/site/mteam` use only synthetic responses and the key -`MTEAM-KEY-CANARY-...`. Never commit a real API key, a profile response, or a -signed download URL. +Tests in `internal/site/mteam` use only synthetic responses, the key +`MTEAM-KEY-CANARY-...`, a signed link with `sign=SIGN-CANARY`, and a synthetic +metafile announcing to `tracker.invalid`. Never commit a real API key, a +profile response, a signed download URL, or a real `.torrent`. diff --git a/docs/README.md b/docs/README.md index bfd8b31..dcdac0d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,7 +18,7 @@ documents that matter to them. - [Features](FEATURES.md): everything implemented today and what is deliberately not implemented. - [M-Team adapter](MTEAM_ADAPTER.md): creating an API key, the four M-Team - reads, their error lines, and why download is not supported yet. + reads, the signed-link metafile download, and their error lines. ## Contributing code diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 7a2f30d..5de71cb 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -111,8 +111,16 @@ forwarding cookies or API keys. A local proxy that answers DNS with fake-IP addresses (`198.18.0.0/15`) therefore makes site reads fail closed; the CLI names that cause instead of dialing the proxy. -The effectful metafile fetch is stricter: it rejects every redirect so that one -acknowledgement cannot expand into another tracker-visible request. The report +The effectful metafile fetch is stricter. A direct route, such as TJUPT's, +rejects every redirect so that one acknowledgement cannot expand into another +tracker-visible request. A linked route, such as M-Team's, declares its extra +requests up front: the acknowledgement scope names them and `MaxLinkRequests` +bounds them at two. Its site-issued link and at most one redirect target are +contacted only over HTTPS on the default port at a host under the adapter's own +registrable domains, each through a fresh credential-free client bound to that +host, so the API key never reaches it and the DNS checks above still apply. The +link is a bearer credential: `httpguard.SecretLink` redacts it when formatted +and keeps it out of errors, reports, and records. The report accounts for whether the sole transport attempt started even when DNS, TLS, or response processing later fails; it never derives a zero request count merely from an error. @@ -139,9 +147,12 @@ with echo turned off before each prompt appears (input typed ahead of a prompt can still be echoed), restores echo if interrupted, and saves the cookie under the user config directory, which no command reads back implicitly; a terminal is accepted only there, never with `--credential-bundle-stdin`. -The M-Team adapter sends at most one bounded POST per command to one of two -read-only JSON API endpoints (`member/profile` and `torrent/search`), with a -non-replayable body of at most 16 KiB, and never retries. HTTP 429 is terminal. There is no cross-process limiter in the alpha, so +The M-Team adapter's reads send at most one bounded POST per command to one of +three read-only JSON API endpoints (`member/profile`, `torrent/search`, and +`torrent/detail`), with a non-replayable body of at most 16 KiB, and never +retry. Its metafile fetch sends one token POST, waits three seconds, and then +makes at most two GETs as described above; the site's per-torrent daily +download limit and burst refusals stop it as `rate_limited`. HTTP 429 is terminal. There is no cross-process limiter in the alpha, so callers must not loop or parallelize site commands. There is no Cloudflare or CAPTCHA bypass. @@ -222,9 +233,11 @@ journals may retain bytes. After final marker removal the program has no basis to claim earlier success, so later absence is unattributed. Neither protocol coordinates a cloned or rolled-back store history. -`site metafile fetch` is scoped to one validated remote ID and one GET. It does -not perform a preceding detail lookup, follow a redirect, retry, or fan out to -related IDs. +`site metafile fetch` is scoped to one validated remote ID and one metafile GET. +A linked route adds at most two counted link requests before it (for M-Team, +the token POST and one allowlisted redirect hop). It does not perform a +preceding detail lookup, let the HTTP stack follow a redirect, retry, or fan +out to related IDs. A live reconciliation may first use one independent, bounded site-detail GET. It then opens one audited read-only downloader session and performs two bounded @@ -1472,9 +1485,10 @@ The B1 site metafile fetch crosses two independent boundaries. The tracker may record its passkey-bearing GET, so the command requires an explicit site-effect acknowledgement scoped to one site reference. All usage, limits, the one remote ID, capability, authentication method, and initialized store's -privacy/no-clobber assurances are validated before the cookie is read from -stdin. It then sends at most one bounded GET, with no detail lookup, redirect, -or retry, and passes the bounded exact response directly to the existing +privacy/no-clobber assurances are validated before the cookie or API key is +read from stdin. It then sends at most one bounded metafile GET, preceded on a +linked route by at most `MaxLinkRequests` bounded link requests, with no detail +lookup, automatic redirect, or retry, and passes the bounded exact response directly to the existing no-clobber store primitive, which requires strict validation before publication. The invocation-only `observed_exact_variant` relation records the exact store @@ -1486,7 +1500,7 @@ has returned the valid exact reference, a later durability or post-publication failure does not erase the observation, but the observation still does not prove durability. Request accounting, logical store writes, and durability assurance remain separate even on failure. No raw response, request URL, -cookie, announce material, object or temporary path may be written to stdout, +site-issued download link, cookie, API key, announce material, object or temporary path may be written to stdout, reports, errors, or an arbitrary destination. Only after a fully successful artifact import may the command publish a sealed diff --git a/docs/guide/metafiles.md b/docs/guide/metafiles.md index d815a83..2cff785 100644 --- a/docs/guide/metafiles.md +++ b/docs/guide/metafiles.md @@ -26,7 +26,7 @@ ptctl metafile store inspect \ Fetch one exact private metafile directly into that initialized store. This is an effectful operation: the tracker may record the GET, so the acknowledgement must be explicit. All usage, the single remote ID, limits, capability, and -store assurances are checked before the cookie is read from stdin: +store assurances are checked before the credential is read from stdin: ```bash printf '%s' "$TJUPT_COOKIE" | ptctl site metafile fetch \ @@ -36,8 +36,21 @@ printf '%s' "$TJUPT_COOKIE" | ptctl site metafile fetch \ tjupt REMOTE_ID ``` -The command performs no torrent-detail lookup and sends at most one GET. It -follows no redirect, performs no retry, and offers no raw stdout or arbitrary +M-Team takes its API key instead. Its route first asks the API for a signed +download link, then GETs it; the link is never printed or stored, and those +link requests are counted separately (see +[MTEAM_ADAPTER.md](../MTEAM_ADAPTER.md#metafile-download)): + +```bash +printf '%s' "$MTEAM_API_KEY" | ptctl site metafile fetch \ + --api-key-stdin \ + --acknowledge-site-effect \ + --metafile-store "D:\Private\ptctl-metafiles" \ + mteam REMOTE_ID +``` + +The command performs no torrent-detail lookup and sends at most one metafile +GET. It follows no redirect on its own, performs no retry, and offers no raw stdout or arbitrary destination. The validated response goes through the ordinary exact-byte, no-clobber store publication path. Its report may record the invocation-scoped `observed_exact_variant` relation only when that store import explicitly diff --git a/docs/guide/sites.md b/docs/guide/sites.md index a5bb0ca..4667ce9 100644 --- a/docs/guide/sites.md +++ b/docs/guide/sites.md @@ -127,7 +127,9 @@ M-Team reads use a site-issued API key instead of a cookie, passed with `--api-key-stdin` under the same stdin-only rules. `status`, `account`, `search`, and `detail` each send one read-only POST to M-Team's JSON API and never retry; search results add seeders, leechers, promotion, and category-name -columns. Metafile fetch and bonus commands are not available for M-Team yet, +columns. `site metafile fetch --api-key-stdin` downloads one `.torrent` into the +private store through M-Team's signed link, as described in +[metafiles.md](metafiles.md). Bonus commands are not available for M-Team yet, and `reconcile` reads live site detail with a cookie only. Setup, results, and error lines are in [MTEAM_ADAPTER.md](../MTEAM_ADAPTER.md): diff --git a/internal/cli/run.go b/internal/cli/run.go index 8780a6f..f1625a5 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -147,7 +147,7 @@ Usage: ptctl site bonus exchange list --state-store DIR [--max-operations N] [--output table|json] ptctl site bonus exchange prune --state-store DIR --intent-record RECORD_ID --operation-id ID --acknowledge-state-prune [--output table|json] ptctl site bonus exchange forget --state-store DIR --retention-record RECORD_ID --operation-id ID --acknowledge-history-forget [--output table|json] - ptctl site metafile fetch --cookie-stdin --acknowledge-site-effect --metafile-store DIR [--output table|json] SITE REMOTE_ID + ptctl site metafile fetch (--cookie-stdin | --api-key-stdin) --acknowledge-site-effect --metafile-store DIR [--output table|json] SITE REMOTE_ID ptctl site metafile binding list --metafile-store DIR [--output table|json] ptctl site metafile binding inspect --metafile-store DIR [--output table|json] RECORD_ID diff --git a/internal/cli/site_contract_test.go b/internal/cli/site_contract_test.go index 43c68da..2831328 100644 --- a/internal/cli/site_contract_test.go +++ b/internal/cli/site_contract_test.go @@ -48,7 +48,8 @@ const mteamDescriptorJSON = ` { "auth.check", "account.read", "torrent.search", - "torrent.detail" + "torrent.detail", + "torrent.metafile.read_effectful" ] }` @@ -67,7 +68,7 @@ func TestBuiltinSiteDiscoveryOutputIsStable(t *testing.T) { {args: []string{"site", "capabilities", "--output", "json", "mteam"}, want: descriptorListJSON(mteamDescriptorJSON)}, {args: []string{"site", "list"}, want: "" + "ID NAME STABILITY BASE URL CAPABILITIES\n" + - "mteam M-Team / 馒头PT experimental https://api2.m-team.cc/ 4\n" + + "mteam M-Team / 馒头PT experimental https://api2.m-team.cc/ 5\n" + "tjupt TJUPT / 北洋园PT experimental https://www.tjupt.org/ 9\n"}, {args: []string{"site", "capabilities", "tjupt"}, want: "" + "SITE KIND VALUE\n" + @@ -87,7 +88,8 @@ func TestBuiltinSiteDiscoveryOutputIsStable(t *testing.T) { "mteam capability auth.check\n" + "mteam capability account.read\n" + "mteam capability torrent.search\n" + - "mteam capability torrent.detail\n"}, + "mteam capability torrent.detail\n" + + "mteam capability torrent.metafile.read_effectful\n"}, } for _, test := range tests { t.Run(strings.Join(test.args, " "), func(t *testing.T) { diff --git a/internal/cli/site_metafile.go b/internal/cli/site_metafile.go index 0e5c044..f3a5114 100644 --- a/internal/cli/site_metafile.go +++ b/internal/cli/site_metafile.go @@ -91,6 +91,7 @@ func (a *app) siteMetafileFetch(args []string) error { fs := newFlagSet("site metafile fetch") output := fs.String("output", "table", "table or json") cookieStdin := fs.Bool("cookie-stdin", false, "read the session Cookie header value from stdin") + apiKeyStdin := fs.Bool("api-key-stdin", false, "read a site-issued API key from stdin") acknowledge := fs.Bool("acknowledge-site-effect", false, "acknowledge that this GET may be recorded as a torrent download") storeRoot := fs.String("metafile-store", "", "initialized private metafile store root") showAbsolute := fs.Bool("show-absolute-paths", false, "include the absolute store root in output; object paths are never shown") @@ -103,8 +104,11 @@ func (a *app) siteMetafileFetch(args []string) error { if fs.NArg() != 2 || fs.Arg(0) == "" || fs.Arg(1) == "" { return usageError("site metafile fetch requires SITE and REMOTE_ID") } - if !*cookieStdin { - return usageError("--cookie-stdin is required; credentials are never accepted in argv") + if *cookieStdin && *apiKeyStdin { + return usageError("--cookie-stdin and --api-key-stdin are mutually exclusive") + } + if !*cookieStdin && !*apiKeyStdin { + return usageError("%s is required; credentials are never accepted in argv", requiredCredentialFlag(a.registry, fs.Arg(0))) } if !*acknowledge { return usageError("--acknowledge-site-effect is required because the GET may be recorded as a torrent download") @@ -136,8 +140,12 @@ func (a *app) siteMetafileFetch(args []string) error { if !descriptor.Supports(domain.CapabilityMetafile) { return usageError("site %q does not declare capability %q", descriptor.ID, domain.CapabilityMetafile) } - if !descriptor.SupportsAuth(domain.AuthMethodCookieHeader) { - return usageError("site %q does not support cookie_header authentication", descriptor.ID) + method, readSecret := domain.AuthMethodCookieHeader, readEffectfulSiteCredential + if *apiKeyStdin { + method, readSecret = domain.AuthMethodAPIKeyHeader, readEffectfulAPIKeyCredential + } + if !descriptor.SupportsAuth(method) { + return usageError("site %q does not support %s authentication", descriptor.ID, method) } fetcher, ok := adapter.(site.MetafileFetcher) if !ok { @@ -151,6 +159,7 @@ func (a *app) siteMetafileFetch(args []string) error { if err != nil || descriptorOrigin != config.Origin { return fmt.Errorf("site %q has an unsafe metafile-fetch origin", descriptor.ID) } + fetchLimits.MaxLinkRequests = config.LinkRequests ref := domain.TorrentRef{SiteID: descriptor.ID, RemoteID: fs.Arg(1)} if err := fetcher.ValidateMetafileRef(ref); err != nil { return usageError("site metafile fetch: invalid SITE/REMOTE_ID") @@ -166,7 +175,7 @@ func (a *app) siteMetafileFetch(args []string) error { } report.StoreOperation.Store = storeSummary(store.Info(), *showAbsolute) - credential, err := readEffectfulSiteCredential(a.stdin) + credential, err := readSecret(a.stdin) if err != nil { report.Outcome = "blocked" report.Blockers = append(report.Blockers, "credential.read_failed") @@ -260,9 +269,13 @@ func (a *app) siteMetafileFetch(args []string) error { report.Blockers = append(report.Blockers, "binding.observation_receipt_disagrees") mappedErr = fmt.Errorf("site metafile observation disagrees with its request receipt") } else { + basis := "effectful_same_origin_get_for_remote_id" + if config.LinkRequests > 0 { + basis = "effectful_site_issued_link_get_for_remote_id" + } report.Binding = siteMetafileBindingSummary{ Status: "observed_exact_variant", EvidenceLevel: "direct_observation", - EvidenceBasis: []string{"effectful_same_origin_get_for_remote_id", "complete_bounded_response", "whole_response_sha256_equals_metafile_variant_id"}, + EvidenceBasis: []string{basis, "complete_bounded_response", "whole_response_sha256_equals_metafile_variant_id"}, Observation: &observation, BlockerCodes: []string{}, } observed = binding @@ -320,18 +333,27 @@ func (a *app) siteMetafileFetch(args []string) error { func (a *app) siteMetafileFetchHelp() { fmt.Fprint(a.stdout, `Usage: - ptctl site metafile fetch --cookie-stdin --acknowledge-site-effect --metafile-store DIR [flags] SITE REMOTE_ID + ptctl site metafile fetch (--cookie-stdin | --api-key-stdin) --acknowledge-site-effect --metafile-store DIR [flags] SITE REMOTE_ID This command performs one explicitly acknowledged, effectful torrent-metafile GET and imports the exact bounded response into an initialized private metafile store. -It never follows redirects, retries, or prints raw bytes. After a complete -private-artifact import, it publishes a sealed historical site-to-variant binding -record in the same store. The response, artifact, and binding durability remain -separate evidence axes; the binding is not proof of current site state. +It never retries or prints raw bytes. After a complete private-artifact import, +it publishes a sealed historical site-to-variant binding record in the same +store. The response, artifact, and binding durability remain separate evidence +axes; the binding is not proof of current site state. + +Most sites use a direct route: one GET on the site origin, no redirects. A +linked route (mteam) first asks the site API for a signed one-time download +link, then GETs it; one redirect is followed only to the site's own HTTPS +hosts, and the link is never printed or stored. Each link request may count as +a download on the site, and is reported as a link request. + +Credentials (stdin only, one line): + --cookie-stdin session Cookie header value (tjupt) + --api-key-stdin site-issued API key (mteam) Flags: --acknowledge-site-effect acknowledge that the GET may count as a download - --cookie-stdin read one Cookie header value from stdin --max-metafile-bytes N response byte limit (default 8 MiB; max 32 MiB) --metafile-store DIR initialized private metafile store --output table|json output format @@ -342,10 +364,21 @@ Flags: func newSiteMetafileFetchReport(ref domain.TorrentRef, config site.MetafileFetchConfig, fetchLimits site.MetafileFetchLimits, storeLimits metastore.Limits, showAbsolute bool, storeRoot string) siteMetafileFetchReport { storeOperation := failedMetafileStoreReport("metafile.store.import", "write_private_metafile_store", storeLimits, "store.not_attempted", showAbsolute, storeRoot, "") + scope := "one_remote_metafile_get" + warnings := []string{"the site observation is a direct non-atomic HTTPS observation, not a site signature or proof of current site state", "the private metafile store is permission-isolated, not encrypted"} + if config.LinkRequests > 0 { + // A linked route asks the site for a signed download link before the + // metafile GET. The link is a credential and every hop may be counted. + scope = "site_link_requests_then_one_remote_metafile_get" + warnings = append(warnings, + "the site-issued download link is a credential; it is used once and is never printed or stored", + "link requests may count as downloads on the site even when no metafile is returned", + ) + } return siteMetafileFetchReport{ kind: "site.metafile.fetch", Outcome: "blocked", Effect: []string{site.MetafileFetchEffect, "write_private_metafile_store", "write_private_site_metafile_binding"}, - Acknowledgement: siteMetafileAcknowledgement{Provided: true, Scope: "one_remote_metafile_get"}, + Acknowledgement: siteMetafileAcknowledgement{Provided: true, Scope: scope}, Site: siteMetafileSiteSummary{Ref: ref, ExpectedOrigin: config.Origin, ExpectedRoute: config.RouteID}, Binding: siteMetafileBindingSummary{Status: "declared_unbound", EvidenceLevel: "declared", EvidenceBasis: []string{"user_supplied_site_reference"}, BlockerCodes: []string{"binding.exact_variant_not_established"}}, Persistent: siteMetafilePersistentBinding{ @@ -355,7 +388,7 @@ func newSiteMetafileFetchReport(ref domain.TorrentRef, config site.MetafileFetch Request: siteMetafileRequestSummary{Status: "not_started", Receipt: site.MetafileFetchReceipt{Effect: site.MetafileFetchEffect, Ref: ref, Origin: config.Origin, RouteID: config.RouteID, Limits: fetchLimits}}, StoreOperation: storeOperation, Blockers: []string{}, Issues: []string{}, - Warnings: []string{"the site observation is a direct non-atomic HTTPS observation, not a site signature or proof of current site state", "the private metafile store is permission-isolated, not encrypted"}, + Warnings: warnings, } } @@ -479,19 +512,51 @@ func readFetchedMetafile(fetched *site.FetchedMetafile, maxBytes int64) ([]byte, } func readEffectfulSiteCredential(reader io.Reader) (site.Credential, error) { - if err := rejectTTYSecret(reader); err != nil { + raw, err := readEffectfulSecret(reader) + if err != nil { + return site.Credential{}, err + } + return canonicalCookieCredential(raw) +} + +func readEffectfulAPIKeyCredential(reader io.Reader) (site.Credential, error) { + raw, err := readEffectfulSecret(reader) + if err != nil { return site.Credential{}, err } + return canonicalAPIKeyCredential(raw) +} + +// readEffectfulSecret reads one secret line and removes only its final line +// ending; any other surrounding whitespace is rejected by the canonical check. +func readEffectfulSecret(reader io.Reader) ([]byte, error) { + if err := rejectTTYSecret(reader); err != nil { + return nil, err + } raw, err := io.ReadAll(io.LimitReader(reader, (64<<10)+3)) if err != nil { - return site.Credential{}, fmt.Errorf("read site credential failed") + return nil, fmt.Errorf("read site credential failed") } if bytes.HasSuffix(raw, []byte("\r\n")) { raw = raw[:len(raw)-2] } else if bytes.HasSuffix(raw, []byte("\n")) { raw = raw[:len(raw)-1] } - return canonicalCookieCredential(raw) + return raw, nil +} + +// canonicalAPIKeyCredential accepts one API key of visible ASCII with no +// whitespace at all. +func canonicalAPIKeyCredential(raw []byte) (site.Credential, error) { + if len(raw) == 0 || len(raw) > 64<<10 { + return site.Credential{}, fmt.Errorf("site credential is not a canonical API key") + } + for _, value := range raw { + if value <= 0x20 || value > 0x7e { + return site.Credential{}, fmt.Errorf("site credential is not a canonical ASCII API key") + } + } + return site.NewAPIKeyCredential(string(raw)) } // canonicalCookieCredential accepts one Cookie header value with no @@ -526,7 +591,8 @@ func validateSuccessfulMetafileFetch(ref domain.TorrentRef, config site.Metafile if fetched == nil || config.Validate() != nil || receipt.Effect != site.MetafileFetchEffect || receipt.Ref != ref || receipt.Origin != config.Origin || receipt.RouteID != config.RouteID || receipt.Limits != limits || receipt.StopReason != "" || !receipt.Complete { return fmt.Errorf("fetch receipt identity is invalid") } - if requestsMade != 1 || receipt.Used.RequestsAttempted != 1 || receipt.Used.AutomaticRetries != 0 || receipt.Used.RedirectsFollowed != 0 { + links := receipt.Used.LinkRequestsAttempted + if links < 0 || links > limits.MaxLinkRequests || requestsMade != 1+links || receipt.Used.RequestsAttempted != 1 || receipt.Used.AutomaticRetries != 0 || receipt.Used.RedirectsFollowed != 0 { return fmt.Errorf("fetch request accounting is invalid") } if receipt.ObservedAtStart.IsZero() || receipt.ObservedAtEnd.IsZero() || receipt.ObservedAtEnd.Before(receipt.ObservedAtStart) { @@ -550,6 +616,8 @@ func publicMetafileFetchReceipt(ref domain.TorrentRef, config site.MetafileFetch RedirectsFollowed: boundedFetchCounter(receipt.Used.RedirectsFollowed, limits.MaxRequests+1), ResponseBytesRead: boundedFetchBytes(receipt.Used.ResponseBytesRead, limits.MaxResponseBytes+1), ResponseBytesKnown: receipt.Used.ResponseBytesKnown && receipt.Used.ResponseBytesRead >= 0 && receipt.Used.ResponseBytesRead <= limits.MaxResponseBytes+1, + // Direct routes never make link requests, so this stays omitted. + LinkRequestsAttempted: boundedFetchCounter(receipt.Used.LinkRequestsAttempted, limits.MaxLinkRequests+1), }, StopReason: publicMetafileStopReason(receipt.StopReason), } @@ -586,7 +654,7 @@ func boundedFetchBytes(value, maximum int64) int64 { func publicMetafileStopReason(value string) string { switch value { - case "invalid_limits", "invalid_reference", "context_done", "session_closed", "request_budget_exhausted", "request_accounting_invalid", "site_request_failed", "authentication_required", "rate_limited", "redirect_rejected", "http_status_rejected", "empty_response", "challenge_response", "unrecognized_response", "content_type_rejected", "response_authority_invalid", "context_cancelled": + case "invalid_limits", "invalid_reference", "context_done", "session_closed", "request_budget_exhausted", "request_accounting_invalid", "site_request_failed", "authentication_required", "not_found", "rate_limited", "redirect_rejected", "http_status_rejected", "empty_response", "challenge_response", "unrecognized_response", "content_type_rejected", "response_authority_invalid", "context_cancelled": return value case "": return "" @@ -657,7 +725,11 @@ func writeSiteMetafileFetchHuman(out io.Writer, report siteMetafileFetchReport) if store.Metafile != nil { fmt.Fprintf(w, "METAFILE VERSION\t%s\nPRIVATE\t%t\nMULTI-FILE\t%t\nCONTENT BYTES\t%d\nFILES\t%d\n", terminalSafe(store.Metafile.Version), store.Metafile.Private, store.Metafile.MultiFile, store.Metafile.TotalLength, store.Metafile.FileCount) } - fmt.Fprintf(w, "\nREQUEST LIMIT\t%d\nRESPONSE LIMIT\t%d bytes\nHEADER LIMIT\t%d bytes\n", report.Request.Receipt.Limits.MaxRequests, report.Request.Receipt.Limits.MaxResponseBytes, report.Request.Receipt.Limits.MaxResponseHeaderBytes) + fmt.Fprintf(w, "\nREQUEST LIMIT\t%d\n", report.Request.Receipt.Limits.MaxRequests) + if report.Request.Receipt.Limits.MaxLinkRequests > 0 { + fmt.Fprintf(w, "LINK REQUEST LIMIT\t%d\nLINK REQUESTS USED\t%d\n", report.Request.Receipt.Limits.MaxLinkRequests, report.Request.Receipt.Used.LinkRequestsAttempted) + } + fmt.Fprintf(w, "RESPONSE LIMIT\t%d bytes\nHEADER LIMIT\t%d bytes\n", report.Request.Receipt.Limits.MaxResponseBytes, report.Request.Receipt.Limits.MaxResponseHeaderBytes) if report.Request.Receipt.Used.ResponseBytesKnown { fmt.Fprintf(w, "RESPONSE USED\t%d bytes\n", report.Request.Receipt.Used.ResponseBytesRead) } else { diff --git a/internal/cli/site_metafile_test.go b/internal/cli/site_metafile_test.go index 077c3d2..72b26cf 100644 --- a/internal/cli/site_metafile_test.go +++ b/internal/cli/site_metafile_test.go @@ -25,12 +25,24 @@ type fakeMetafileFetchAdapter struct { lastCredential string forcedFetchError error configError error + // linked makes the fake an API-key site whose route spends linkRequests + // before the metafile GET; requestSkew misreports the session total. + linked bool + linkRequests int + requestSkew int +} + +func (adapter *fakeMetafileFetchAdapter) authMethod() domain.AuthMethod { + if adapter.linked { + return domain.AuthMethodAPIKeyHeader + } + return domain.AuthMethodCookieHeader } func (adapter *fakeMetafileFetchAdapter) Descriptor() domain.SiteDescriptor { return domain.SiteDescriptor{ ID: "fakept", Name: "Fake PT", BaseURL: "https://fake.invalid/", Stability: "test", - AuthMethods: []domain.AuthMethod{domain.AuthMethodCookieHeader}, + AuthMethods: []domain.AuthMethod{adapter.authMethod()}, Capabilities: []domain.Capability{domain.CapabilityMetafile}, } } @@ -46,6 +58,9 @@ func (adapter *fakeMetafileFetchAdapter) MetafileFetchConfig() (site.MetafileFet if adapter.configError != nil { return site.MetafileFetchConfig{}, adapter.configError } + if adapter.linked { + return site.NewLinkedMetafileFetchConfig("https://fake.invalid", "fake.download_by_id.v1", 2) + } return site.NewMetafileFetchConfig("https://fake.invalid", "fake.download_by_id.v1") } @@ -53,19 +68,21 @@ func (adapter *fakeMetafileFetchAdapter) OpenMetafileFetchSession(ctx context.Co if err := ctx.Err(); err != nil { return nil, err } - if credential.Method() != domain.AuthMethodCookieHeader { + if credential.Method() != adapter.authMethod() { return nil, fmt.Errorf("wrong auth") } adapter.opened++ adapter.lastCredential = credential.SecretValue() - return &fakeMetafileFetchSession{raw: bytes.Clone(adapter.raw), forcedError: adapter.forcedFetchError}, nil + return &fakeMetafileFetchSession{raw: bytes.Clone(adapter.raw), forcedError: adapter.forcedFetchError, linkRequests: adapter.linkRequests, requestSkew: adapter.requestSkew}, nil } type fakeMetafileFetchSession struct { - raw []byte - forcedError error - requests int - closed bool + raw []byte + forcedError error + requests int + closed bool + linkRequests int + requestSkew int } func (session *fakeMetafileFetchSession) FetchMetafile(ctx context.Context, ref domain.TorrentRef, limits site.MetafileFetchLimits) (*site.FetchedMetafile, site.MetafileFetchReceipt, error) { @@ -84,15 +101,16 @@ func (session *fakeMetafileFetchSession) FetchMetafile(ctx context.Context, ref receipt.StopReason = "request_budget_exhausted" return nil, receipt, fmt.Errorf("request budget exhausted") } - session.requests++ + session.requests += 1 + session.linkRequests receipt.Used.RequestsAttempted = 1 + receipt.Used.LinkRequestsAttempted = session.linkRequests if session.forcedError != nil { receipt.ObservedAtEnd = time.Now().UTC() receipt.StopReason = "site.synthetic_failure" return nil, receipt, session.forcedError } end := time.Now().UTC() - fetched, err := site.NewFetchedMetafile(ref, receipt.Origin, receipt.RouteID, start, end, session.raw) + fetched, err := site.NewLinkedFetchedMetafile(ref, receipt.Origin, receipt.RouteID, start, end, session.linkRequests, session.raw) if err != nil { return nil, receipt, err } @@ -103,7 +121,9 @@ func (session *fakeMetafileFetchSession) FetchMetafile(ctx context.Context, ref return fetched, receipt, nil } -func (session *fakeMetafileFetchSession) RequestsMade() int { return session.requests } +func (session *fakeMetafileFetchSession) RequestsMade() int { + return session.requests + session.requestSkew +} func (session *fakeMetafileFetchSession) Close() error { session.closed = true return nil @@ -174,6 +194,10 @@ func TestSiteMetafileFetchStoresExactVariantAndHidesSecrets(t *testing.T) { assertJSONArray(t, "fetch issues", envelope.Data.Issues) assertJSONArray(t, "fetch warnings", envelope.Data.Warnings) assertJSONStringsExclude(t, out.Bytes(), storeRoot, name, passkey, cookie, "announce?passkey") + if strings.Contains(out.String(), "link_request") || !strings.Contains(out.String(), `"scope": "one_remote_metafile_get"`) || + !strings.Contains(out.String(), `"effectful_same_origin_get_for_remote_id"`) || len(envelope.Data.Warnings) == 0 || strings.Contains(string(envelope.Data.Warnings), "link") { + t.Fatalf("direct route report changed: %s", out.String()) + } out.Reset() a = &app{stdin: strings.NewReader(cookie + "\n"), stdout: &out, stderr: &errOut, registry: site.NewRegistry(adapter)} @@ -350,7 +374,7 @@ func TestSiteMetafileFetchHumanReportOrdersBlockersBeforeEvidence(t *testing.T) blockers := strings.Index(text, "BLOCKERS") siteSection := strings.Index(text, "REMOTE ID") storeSection := strings.Index(text, "STORE OUTCOME") - if blockers < 0 || siteSection < blockers || storeSection < siteSection || !strings.Contains(text, "OBSERVED VARIANT") || !strings.Contains(text, "AUTOMATIC RETRIES") || !strings.Contains(text, "PERSISTENT BINDING") || !strings.Contains(text, "RECORD ID") { + if blockers < 0 || siteSection < blockers || storeSection < siteSection || !strings.Contains(text, "OBSERVED VARIANT") || !strings.Contains(text, "AUTOMATIC RETRIES") || !strings.Contains(text, "PERSISTENT BINDING") || !strings.Contains(text, "RECORD ID") || strings.Contains(text, "LINK REQUEST") { t.Fatalf("unclear human report: %s", text) } for _, secret := range []string{storeRoot, name, passkey, cookie} { @@ -372,6 +396,155 @@ func TestEffectfulSiteCredentialIsCanonicalASCII(t *testing.T) { } } +func TestEffectfulAPIKeyCredentialIsCanonicalASCII(t *testing.T) { + for _, value := range []string{"KEY-CANARY-1", "KEY-CANARY-1\n", "KEY-CANARY-1\r\n"} { + credential, err := readEffectfulAPIKeyCredential(strings.NewReader(value)) + if err != nil || credential.Method() != domain.AuthMethodAPIKeyHeader || credential.SecretValue() != "KEY-CANARY-1" { + t.Fatalf("canonical API key %q rejected: %v", value, err) + } + } + for _, value := range []string{"", "\n", " KEY\n", "KEY \n", "K EY\n", "KEY\t\n", "KEY\n\n", "KEY \n"} { + if _, err := readEffectfulAPIKeyCredential(strings.NewReader(value)); err == nil { + t.Fatalf("unsafe API key accepted: %q", value) + } + } +} + +func TestSiteMetafileFetchLinkedRouteAccountsForLinkRequests(t *testing.T) { + const ( + name = "LINKED-NAME-CANARY.bin" + passkey = "LINKED-PASSKEY-CANARY" + key = "LINKED-API-KEY-CANARY" + ) + for _, links := range []int{1, 2} { + t.Run(strconv.Itoa(links), func(t *testing.T) { + storeRoot := filepath.Join(physicalCLITempDir(t), "LINKED-STORE-PATH-CANARY") + if _, _, err := metastore.Init(storeRoot); err != nil { + t.Fatal(err) + } + adapter := &fakeMetafileFetchAdapter{raw: sitePrivateTrackerMetafile(name, []byte("x"), passkey), linked: true, linkRequests: links} + var out bytes.Buffer + a := &app{stdin: strings.NewReader(key + "\n"), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + if err := a.siteMetafileFetch([]string{"--api-key-stdin", "--acknowledge-site-effect", "--metafile-store", storeRoot, "--output", "json", "fakept", "42"}); err != nil { + t.Fatalf("linked fetch failed: %v stdout=%s", err, out.String()) + } + if adapter.opened != 1 || adapter.lastCredential != key { + t.Fatalf("unexpected session: opened=%d", adapter.opened) + } + var envelope struct { + Data struct { + Outcome string `json:"outcome"` + Acknowledgement struct { + Scope string `json:"scope"` + } `json:"acknowledgement"` + Binding struct { + Status string `json:"status"` + EvidenceBasis []string `json:"evidence_basis"` + } `json:"binding"` + Persistent struct { + Outcome string `json:"outcome"` + } `json:"persistent_binding"` + Request struct { + RequestsMade int `json:"requests_made"` + Redirects int `json:"redirects"` + Receipt site.MetafileFetchReceipt `json:"receipt"` + } `json:"request"` + Warnings []string `json:"warnings"` + } `json:"data"` + } + if err := json.Unmarshal(out.Bytes(), &envelope); err != nil { + t.Fatal(err) + } + data := envelope.Data + if data.Outcome != "stored" || data.Persistent.Outcome != "stored" || data.Binding.Status != "observed_exact_variant" || + data.Acknowledgement.Scope != "site_link_requests_then_one_remote_metafile_get" || + len(data.Binding.EvidenceBasis) == 0 || data.Binding.EvidenceBasis[0] != "effectful_site_issued_link_get_for_remote_id" || + data.Request.RequestsMade != 1+links || data.Request.Redirects != 0 || + data.Request.Receipt.Limits.MaxLinkRequests != 2 || data.Request.Receipt.Used.LinkRequestsAttempted != links || + data.Request.Receipt.Used.RequestsAttempted != 1 || !strings.Contains(strings.Join(data.Warnings, "\n"), "download link is a credential") { + t.Fatalf("unexpected linked report: %s", out.String()) + } + assertJSONStringsExclude(t, out.Bytes(), storeRoot, name, passkey, key, "announce?passkey") + + out.Reset() + a = &app{stdin: strings.NewReader(key + "\n"), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + if err := a.siteMetafileFetch([]string{"--api-key-stdin", "--acknowledge-site-effect", "--metafile-store", storeRoot, "fakept", "42"}); err != nil { + t.Fatal(err) + } + if text := out.String(); !strings.Contains(text, "LINK REQUEST LIMIT 2\n") || !strings.Contains(text, "LINK REQUESTS USED "+strconv.Itoa(links)+"\n") || + strings.Contains(text, key) || strings.Contains(text, passkey) { + t.Fatalf("unexpected linked human report: %s", text) + } + }) + } +} + +func TestSiteMetafileFetchLinkedRouteRejectsInconsistentAccounts(t *testing.T) { + for _, test := range []struct { + name string + linkRequests int + skew int + }{ + {name: "uncounted link request", linkRequests: 1, skew: -1}, + {name: "unreported request", linkRequests: 1, skew: 1}, + {name: "link request over budget", linkRequests: 3}, + } { + t.Run(test.name, func(t *testing.T) { + storeRoot := filepath.Join(physicalCLITempDir(t), "store") + if _, _, err := metastore.Init(storeRoot); err != nil { + t.Fatal(err) + } + adapter := &fakeMetafileFetchAdapter{raw: sitePrivateTrackerMetafile("x.bin", []byte("x"), "INCONSISTENT-CANARY"), linked: true, linkRequests: test.linkRequests, requestSkew: test.skew} + var out bytes.Buffer + a := &app{stdin: strings.NewReader("KEY\n"), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + if err := a.siteMetafileFetch([]string{"--api-key-stdin", "--acknowledge-site-effect", "--metafile-store", storeRoot, "--output", "json", "fakept", "42"}); err == nil { + t.Fatalf("inconsistent account accepted: %s", out.String()) + } + if !strings.Contains(out.String(), `"outcome": "blocked"`) || strings.Contains(out.String(), "observed_exact_variant") || strings.Contains(out.String(), `"writes_performed": 1`) { + t.Fatalf("inconsistent account was published: %s", out.String()) + } + }) + } +} + +func TestSiteMetafileFetchNamesAndChecksTheCredentialFlagBeforeReadingIt(t *testing.T) { + missingStore := filepath.Join(physicalCLITempDir(t), "missing-store") + flags := []string{"--acknowledge-site-effect", "--metafile-store", missingStore} + for _, test := range []struct { + adapter *fakeMetafileFetchAdapter + args []string + want string + }{ + {adapter: &fakeMetafileFetchAdapter{linked: true}, args: []string{"fakept", "42"}, want: "--api-key-stdin is required; credentials are never accepted in argv"}, + {adapter: &fakeMetafileFetchAdapter{linked: true}, args: []string{"--cookie-stdin", "fakept", "42"}, want: `site "fakept" does not support cookie_header authentication`}, + {adapter: &fakeMetafileFetchAdapter{}, args: []string{"fakept", "42"}, want: "--cookie-stdin is required; credentials are never accepted in argv"}, + {adapter: &fakeMetafileFetchAdapter{}, args: []string{"--api-key-stdin", "fakept", "42"}, want: `site "fakept" does not support api_key_header authentication`}, + {adapter: &fakeMetafileFetchAdapter{}, args: []string{"--cookie-stdin", "--api-key-stdin", "fakept", "42"}, want: "--cookie-stdin and --api-key-stdin are mutually exclusive"}, + } { + secret := &trackingReader{} + application := &app{stdin: secret, stdout: &bytes.Buffer{}, stderr: &bytes.Buffer{}, registry: site.NewRegistry(test.adapter)} + if err := application.siteMetafileFetch(append(append([]string{}, flags...), test.args...)); err == nil || err.Error() != test.want || secret.read || test.adapter.opened != 0 { + t.Fatalf("args=%q err=%v secretRead=%t", test.args, err, secret.read) + } + } + for _, test := range []struct { + args []string + want string + }{ + {args: []string{"mteam", "1"}, want: "--api-key-stdin is required; credentials are never accepted in argv"}, + {args: []string{"tjupt", "1"}, want: "--cookie-stdin is required; credentials are never accepted in argv"}, + {args: []string{"--api-key-stdin", "tjupt", "1"}, want: `site "tjupt" does not support api_key_header authentication`}, + {args: []string{"--cookie-stdin", "mteam", "1"}, want: `site "mteam" does not support cookie_header authentication`}, + } { + secret := &trackingReader{} + var out, errOut bytes.Buffer + args := append(append([]string{"site", "metafile", "fetch"}, flags...), test.args...) + if code := Run(args, secret, &out, &errOut); code != 2 || out.Len() != 0 || secret.read || !strings.Contains(errOut.String(), test.want) { + t.Fatalf("args=%q code=%d stdout=%q stderr=%q secretRead=%t", test.args, code, out.String(), errOut.String(), secret.read) + } + } +} + func TestSiteMetafileFetchRedactsAdapterErrorsAndReceiptText(t *testing.T) { storeRoot := filepath.Join(physicalCLITempDir(t), "store") if _, _, err := metastore.Init(storeRoot); err != nil { diff --git a/internal/site/httpguard/client.go b/internal/site/httpguard/client.go index 5dd7098..e10d81d 100644 --- a/internal/site/httpguard/client.go +++ b/internal/site/httpguard/client.go @@ -96,6 +96,12 @@ func NewWithHeaderCredential(baseURL, header, value string, minInterval time.Dur return newClient(baseURL, name, value, minInterval) } +// NewWithoutCredential binds no credential. It is for a URL whose own signed +// query authorizes the request, such as a download link a site API issued. +func NewWithoutCredential(baseURL string, minInterval time.Duration) (*Client, error) { + return newClient(baseURL, "", "", minInterval) +} + // reservedHeaders are set by the client itself or frame the message, so a // credential header must never replace them. var reservedHeaders = map[string]bool{ @@ -458,6 +464,122 @@ func (c *Client) PostReadOnce(ctx context.Context, relativePath, contentType str return c.roundTrip(ctx, req, result, maxBody, maxHeaderBytes, nil) } +// SecretLink is one exact absolute HTTPS URL whose query carries authority, +// such as a signed download link. It formats as redacted and holds the URL +// behind a pointer, so formatting a struct that holds a SecretLink prints an +// address rather than the URL. Never print, log, or store its URL. +type SecretLink struct { + value *url.URL +} + +const maxSecretLinkBytes = 4096 + +// NewSecretLink parses raw as an absolute HTTPS URL without user info or a +// fragment. The query is kept exactly as given. +func NewSecretLink(raw string) (SecretLink, error) { + if raw == "" || len(raw) > maxSecretLinkBytes || !asciiHeaderValue(raw) || strings.ContainsAny(raw, " \\") { + return SecretLink{}, fmt.Errorf("site link is invalid") + } + parsed, err := url.Parse(raw) + if err != nil || !validSecretLink(parsed) { + return SecretLink{}, fmt.Errorf("site link is invalid") + } + return SecretLink{value: parsed}, nil +} + +func validSecretLink(link *url.URL) bool { + return link != nil && link.Scheme == "https" && link.Opaque == "" && link.Host != "" && link.Hostname() != "" && + link.User == nil && link.Fragment == "" && link.RawFragment == "" && link.RawPath == "" && !link.ForceQuery +} + +// URL returns a copy that the caller may inspect but must keep secret. +func (link SecretLink) URL() *url.URL { + if link.value == nil { + return nil + } + copyOfLink := *link.value + return ©OfLink +} + +func (link SecretLink) IsZero() bool { return link.value == nil } + +func (link SecretLink) String() string { return "[REDACTED]" } +func (link SecretLink) GoString() string { return "httpguard.SecretLink{[REDACTED]}" } + +// GetLinkOnce performs one non-following, non-retrying GET of an exact link on +// this client's own origin; the query is sent verbatim. For a redirect with one +// absolute or relative HTTPS Location that approve accepts, it also returns the +// target as a SecretLink. The redirect is never followed, and neither the link +// nor the Location appears in the result or an error. +func (c *Client) GetLinkOnce(ctx context.Context, link SecretLink, accept string, maxBody, maxHeaderBytes int64, approve func(*url.URL) bool) (StrictResponse, SecretLink, error) { + var result StrictResponse + if maxBody <= 0 || maxBody > 32<<20 || maxHeaderBytes <= 0 || maxHeaderBytes > hardMaxResponseHeaders { + return result, SecretLink{}, fmt.Errorf("site response budget is invalid") + } + if accept == "" || !asciiHeaderValue(accept) { + return result, SecretLink{}, fmt.Errorf("site accept header is invalid") + } + target := link.URL() + if !validSecretLink(target) { + return result, SecretLink{}, fmt.Errorf("site link is invalid") + } + if !strings.EqualFold(target.Hostname(), c.base.Hostname()) || effectivePort(target) != effectivePort(c.base) { + return result, SecretLink{}, fmt.Errorf("site request escaped configured origin") + } + if err := c.wait(ctx); err != nil { + return result, SecretLink{}, err + } + if err := ctx.Err(); err != nil { + return result, SecretLink{}, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil) + if err != nil { + return result, SecretLink{}, fmt.Errorf("build site request failed") + } + req.Header.Set("Accept", accept) + req.Header.Set("Accept-Encoding", "identity") + req.Header.Set("User-Agent", readOnlyUserAgent) + c.applyCredential(req) + req.Close = true + var next SecretLink + capture := func(resp *http.Response) error { + if approve == nil || resp.StatusCode < 300 || resp.StatusCode > 399 { + return nil + } + locations := resp.Header.Values("Location") + if len(locations) != 1 { + return nil + } + if location, ok := linkRedirectTarget(target, locations[0]); ok && approve(SecretLink{value: location}.URL()) { + next = SecretLink{value: location} + } + return nil + } + response, err := c.roundTripCapturing(ctx, req, result, maxBody, maxHeaderBytes, nil, capture) + if err != nil { + return response, SecretLink{}, err + } + return response, next, nil +} + +// linkRedirectTarget resolves one Location against the link it answered. Any +// HTTPS host is returned; the caller's approve function decides which host may +// be contacted next. +func linkRedirectTarget(from *url.URL, raw string) (*url.URL, bool) { + if raw == "" || len(raw) > maxSecretLinkBytes || !asciiHeaderValue(raw) || strings.ContainsAny(raw, " \\") { + return nil, false + } + ref, err := url.Parse(raw) + if err != nil || ref.User != nil || ref.Fragment != "" || ref.RawPath != "" { + return nil, false + } + target := from.ResolveReference(ref) + if !validSecretLink(target) { + return nil, false + } + return target, true +} + const readOnlyUserAgent = "ptctl/0.1 (+https://github.com/tonycoder-hub/ptctl; conservative-read-only-client)" func (c *Client) applyCredential(req *http.Request) { diff --git a/internal/site/httpguard/link_test.go b/internal/site/httpguard/link_test.go new file mode 100644 index 0000000..50a5ccc --- /dev/null +++ b/internal/site/httpguard/link_test.go @@ -0,0 +1,195 @@ +package httpguard + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "testing" +) + +const testLink = "https://example.test/api/rss/dlv2?tid=42&sign=SIGN-CANARY%2B&uid=7" + +func mustSecretLink(t *testing.T, raw string) SecretLink { + t.Helper() + link, err := NewSecretLink(raw) + if err != nil { + t.Fatal(err) + } + return link +} + +func TestNewSecretLinkValidatesAndRedacts(t *testing.T) { + link := mustSecretLink(t, testLink) + if link.IsZero() || link.URL().String() != testLink { + t.Fatalf("link was not kept exactly") + } + link.URL().RawQuery = "changed" + if link.URL().RawQuery != "tid=42&sign=SIGN-CANARY%2B&uid=7" { + t.Fatalf("URL returned shared state") + } + holder := struct { + Exported SecretLink + private SecretLink + }{link, link} + for _, formatted := range []string{ + link.String(), link.GoString(), fmt.Sprint(link), fmt.Sprintf("%v %+v %#v", holder, holder, holder), + } { + if strings.Contains(formatted, "CANARY") { + t.Fatalf("formatted link leaked: %q", formatted) + } + } + for _, raw := range []string{ + "", + "http://example.test/x?sign=CANARY", + "https://user:CANARY@example.test/x", + "https://example.test/x?sign=CANARY#fragment", + "https://example.test/x?sign=CANARY ", + "https://example.test/x?sign=CANARY\r\n", + "https://example.test/x?sign=CANARY-é", + "https://example.test\\x?sign=CANARY", + "https://example.test/x?", + "https:example.test/x?sign=CANARY", + "/api/rss/dlv2?sign=CANARY", + "magnet:?xt=urn:btih:CANARY", + "https://example.test/x?sign=CANARY" + strings.Repeat("a", maxSecretLinkBytes), + } { + if link, err := NewSecretLink(raw); err == nil || !link.IsZero() || strings.Contains(err.Error(), "CANARY") { + t.Fatalf("raw=%q accepted or leaked: %v", raw, err) + } + } +} + +func TestNewWithoutCredentialSendsNoCredential(t *testing.T) { + client, err := NewWithoutCredential("https://example.test/", 0) + if err != nil { + t.Fatal(err) + } + defer client.Close() + if client.credentialHeader != "" || client.credentialValue != "" { + t.Fatalf("credential bound") + } + if client, err := NewWithoutCredential("http://example.test/", 0); err == nil || client != nil { + t.Fatalf("plain HTTP accepted") + } +} + +func TestGetLinkOnceSendsExactLinkOnce(t *testing.T) { + calls := 0 + client := strictTestClient(t, roundTripFunc(func(request *http.Request) (*http.Response, error) { + calls++ + if request.Method != http.MethodGet || request.URL.String() != testLink || request.URL.RawQuery != "tid=42&sign=SIGN-CANARY%2B&uid=7" { + t.Fatalf("request was not the exact link") + } + if request.Header.Get("Cookie") != "" || request.Header.Get("X-Api-Key") != "" || request.Header.Get("User-Agent") != readOnlyUserAgent || + request.Header.Get("Accept") != "application/x-bittorrent" || request.Header.Get("Accept-Encoding") != "identity" || !request.Close { + t.Fatalf("headers=%v close=%v", request.Header, request.Close) + } + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"application/x-bittorrent"}}, Body: io.NopCloser(strings.NewReader("d4:infod4:name1:xee")), Request: request}, nil + }), "") + response, next, err := client.GetLinkOnce(context.Background(), mustSecretLink(t, testLink), "application/x-bittorrent", 1<<20, 32<<10, func(*url.URL) bool { + t.Fatal("approve called for a non-redirect") + return false + }) + if err != nil || calls != 1 || client.RequestsMade() != 1 { + t.Fatalf("calls=%d requests=%d err=%v", calls, client.RequestsMade(), err) + } + if !next.IsZero() || response.StatusCode != http.StatusOK || response.MediaType != "application/x-bittorrent" || + string(response.Body) != "d4:infod4:name1:xee" || !response.ResponseBytesKnown || response.RedirectID != "" { + t.Fatalf("response=%+v next=%v", response, next) + } +} + +func TestGetLinkOnceReturnsOnlyAnApprovedRedirect(t *testing.T) { + const cdn = "https://cdn.example.test/file.torrent?token=CDN-CANARY" + for _, test := range []struct { + name string + locations []string + approve func(*url.URL) bool + want string + }{ + {name: "approved absolute", locations: []string{cdn}, approve: hostIs("cdn.example.test"), want: cdn}, + {name: "approved relative", locations: []string{"/files/1.torrent?k=CANARY"}, approve: hostIs("example.test"), want: "https://example.test/files/1.torrent?k=CANARY"}, + {name: "not approved", locations: []string{cdn}, approve: hostIs("other.test")}, + {name: "no approve function", locations: []string{cdn}}, + {name: "magnet", locations: []string{"magnet:?xt=urn:btih:CANARY"}, approve: approveAll}, + {name: "plain http", locations: []string{"http://cdn.example.test/file.torrent?token=CANARY"}, approve: approveAll}, + {name: "user info", locations: []string{"https://u:CANARY@cdn.example.test/f"}, approve: approveAll}, + {name: "fragment", locations: []string{cdn + "#CANARY"}, approve: approveAll}, + {name: "two locations", locations: []string{cdn, cdn}, approve: approveAll}, + {name: "no location", approve: approveAll}, + } { + t.Run(test.name, func(t *testing.T) { + client := strictTestClient(t, roundTripFunc(func(request *http.Request) (*http.Response, error) { + header := http.Header{"Content-Type": {"text/html"}} + for _, location := range test.locations { + header.Add("Location", location) + } + return &http.Response{StatusCode: http.StatusFound, Header: header, Body: io.NopCloser(strings.NewReader("")), Request: request}, nil + }), "") + response, next, err := client.GetLinkOnce(context.Background(), mustSecretLink(t, testLink), "application/x-bittorrent", 1<<20, 32<<10, test.approve) + if err != nil || response.StatusCode != http.StatusFound || response.RedirectID != "" || client.RequestsMade() != 1 { + t.Fatalf("response=%+v err=%v", response, err) + } + if test.want == "" { + if !next.IsZero() { + t.Fatalf("redirect target returned") + } + return + } + if next.IsZero() || next.URL().String() != test.want { + t.Fatalf("redirect target was not returned exactly") + } + }) + } +} + +func TestGetLinkOnceRefusesBeforeSending(t *testing.T) { + calls := 0 + client := strictTestClient(t, roundTripFunc(func(*http.Request) (*http.Response, error) { + calls++ + return nil, fmt.Errorf("unexpected request") + }), "") + for _, test := range []struct { + name string + link SecretLink + accept string + body int64 + }{ + {name: "other host", link: mustSecretLink(t, "https://other.test/x?sign=CANARY"), accept: "*/*", body: 1 << 20}, + {name: "other port", link: mustSecretLink(t, "https://example.test:8443/x?sign=CANARY"), accept: "*/*", body: 1 << 20}, + {name: "zero link", accept: "*/*", body: 1 << 20}, + {name: "bad accept", link: mustSecretLink(t, testLink), accept: "a\r\nb", body: 1 << 20}, + {name: "bad budget", link: mustSecretLink(t, testLink), accept: "*/*", body: 0}, + } { + if _, next, err := client.GetLinkOnce(context.Background(), test.link, test.accept, test.body, 32<<10, approveAll); err == nil || !next.IsZero() || strings.Contains(err.Error(), "CANARY") { + t.Fatalf("%s: err=%v", test.name, err) + } + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, _, err := client.GetLinkOnce(ctx, mustSecretLink(t, testLink), "*/*", 1<<20, 32<<10, nil); err == nil { + t.Fatal("canceled context sent a request") + } + if calls != 0 || client.RequestsMade() != 0 { + t.Fatalf("calls=%d requests=%d", calls, client.RequestsMade()) + } +} + +func TestGetLinkOnceErrorsNeverCarryTheLink(t *testing.T) { + client := strictTestClient(t, roundTripFunc(func(request *http.Request) (*http.Response, error) { + return nil, &url.Error{Op: "Get", URL: request.URL.String(), Err: fmt.Errorf("dial failed")} + }), "") + _, _, err := client.GetLinkOnce(context.Background(), mustSecretLink(t, testLink), "*/*", 1<<20, 32<<10, nil) + if err == nil || strings.Contains(err.Error(), "CANARY") || strings.Contains(err.Error(), "dlv2") { + t.Fatalf("err=%v", err) + } +} + +func hostIs(host string) func(*url.URL) bool { + return func(target *url.URL) bool { return target.Hostname() == host } +} + +func approveAll(*url.URL) bool { return true } diff --git a/internal/site/metafile.go b/internal/site/metafile.go index 4fba7ce..abba1b4 100644 --- a/internal/site/metafile.go +++ b/internal/site/metafile.go @@ -24,14 +24,22 @@ const ( defaultMetafileResponseBytes = int64(8 << 20) hardMetafileResponseBytes = int64(32 << 20) hardMetafileHeaderBytes = int64(64 << 10) + + // maxMetafileLinkRequests bounds the site requests a route may make before + // the metafile request: asking for a signed link, then one redirect. + maxMetafileLinkRequests = 2 ) -// MetafileFetchLimits bounds the sole remote effect and all response material -// retained by a fetch session. MaxRequests is intentionally fixed at one. +// MetafileFetchLimits bounds the remote effects and all response material +// retained by a fetch session. MaxRequests counts the one request that returns +// the metafile and is intentionally fixed at one. MaxLinkRequests bounds the +// site requests a linked route makes first to obtain that request's URL; it is +// zero, and omitted, for a route that fetches the metafile directly. type MetafileFetchLimits struct { MaxRequests int `json:"max_requests"` MaxResponseBytes int64 `json:"max_response_bytes"` MaxResponseHeaderBytes int64 `json:"max_response_header_bytes"` + MaxLinkRequests int `json:"max_link_requests,omitempty"` } func DefaultMetafileFetchLimits() MetafileFetchLimits { @@ -52,15 +60,24 @@ func (limits MetafileFetchLimits) Validate() error { if limits.MaxResponseHeaderBytes <= 0 || limits.MaxResponseHeaderBytes > hardMetafileHeaderBytes { return fmt.Errorf("metafile response header budget is outside the supported range") } + if limits.MaxLinkRequests < 0 || limits.MaxLinkRequests > maxMetafileLinkRequests { + return fmt.Errorf("metafile link request budget is outside the supported range") + } return nil } +// MetafileFetchUsage accounts for one fetch. RequestsAttempted counts the +// request expected to return the metafile, and LinkRequestsAttempted the +// requests made before it. RedirectsFollowed stays zero: the transport never +// follows a redirect, and a linked route that requests a redirect target +// counts the answered redirect as a link request. type MetafileFetchUsage struct { - RequestsAttempted int `json:"requests_attempted"` - AutomaticRetries int `json:"automatic_retries"` - RedirectsFollowed int `json:"redirects_followed"` - ResponseBytesRead int64 `json:"response_bytes_read"` - ResponseBytesKnown bool `json:"response_bytes_known"` + RequestsAttempted int `json:"requests_attempted"` + AutomaticRetries int `json:"automatic_retries"` + RedirectsFollowed int `json:"redirects_followed"` + ResponseBytesRead int64 `json:"response_bytes_read"` + ResponseBytesKnown bool `json:"response_bytes_known"` + LinkRequestsAttempted int `json:"link_requests_attempted,omitempty"` } // MetafileFetchReceipt is safe to serialize. It contains no response bytes, @@ -80,14 +97,22 @@ type MetafileFetchReceipt struct { // MetafileFetchConfig is credential-free adapter provenance. Callers obtain // and pin it before reading a credential, then compare every effect receipt to -// the same canonical origin and stable route identifier. +// the same canonical origin and stable route identifier. LinkRequests is the +// most site requests the route makes before the metafile request. type MetafileFetchConfig struct { - Origin string `json:"origin"` - RouteID string `json:"route_id"` + Origin string `json:"origin"` + RouteID string `json:"route_id"` + LinkRequests int `json:"link_requests,omitempty"` } func NewMetafileFetchConfig(origin, routeID string) (MetafileFetchConfig, error) { - config := MetafileFetchConfig{Origin: origin, RouteID: routeID} + return NewLinkedMetafileFetchConfig(origin, routeID, 0) +} + +// NewLinkedMetafileFetchConfig is for a route that must first ask the site +// for the metafile URL, making at most linkRequests requests before it. +func NewLinkedMetafileFetchConfig(origin, routeID string, linkRequests int) (MetafileFetchConfig, error) { + config := MetafileFetchConfig{Origin: origin, RouteID: routeID, LinkRequests: linkRequests} if err := config.Validate(); err != nil { return MetafileFetchConfig{}, err } @@ -98,9 +123,20 @@ func (config MetafileFetchConfig) Validate() error { if err := validateCanonicalOrigin(config.Origin); err != nil { return err } + if config.LinkRequests < 0 || config.LinkRequests > maxMetafileLinkRequests { + return fmt.Errorf("metafile link request budget is outside the supported range") + } return validateRouteID(config.RouteID) } +// DefaultLimits returns DefaultMetafileFetchLimits with the link request +// budget this route needs. +func (config MetafileFetchConfig) DefaultLimits() MetafileFetchLimits { + limits := DefaultMetafileFetchLimits() + limits.MaxLinkRequests = config.LinkRequests + return limits +} + // MetafileRefValidator lets callers reject an adapter-specific remote // reference before obtaining or reading a credential. type MetafileRefValidator interface { @@ -127,14 +163,15 @@ type MetafileFetchSession interface { // it from the exact response and consumers can only obtain a fresh reader or // bind a completed import to that response digest. type FetchedMetafile struct { - ref domain.TorrentRef - origin string - routeID string - start time.Time - end time.Time - raw []byte - digest [sha256.Size]byte - authority *fetchAuthority + ref domain.TorrentRef + origin string + routeID string + start time.Time + end time.Time + linkRequests int + raw []byte + digest [sha256.Size]byte + authority *fetchAuthority } type fetchAuthority struct{} @@ -146,10 +183,17 @@ type fetchAuthority struct{} // copies during construction are therefore bounded at 16 MiB by default and // 64 MiB at the hard ceiling, excluding allocator and transport overhead. func NewFetchedMetafile(ref domain.TorrentRef, origin, routeID string, start, end time.Time, raw []byte) (*FetchedMetafile, error) { + return NewLinkedFetchedMetafile(ref, origin, routeID, start, end, 0, raw) +} + +// NewLinkedFetchedMetafile is NewFetchedMetafile for a linked route that made +// linkRequests site requests before the one that returned raw. The receipt +// must then account for exactly that many link requests. +func NewLinkedFetchedMetafile(ref domain.TorrentRef, origin, routeID string, start, end time.Time, linkRequests int, raw []byte) (*FetchedMetafile, error) { if err := validatePublicRef(ref); err != nil { return nil, err } - if err := (MetafileFetchConfig{Origin: origin, RouteID: routeID}).Validate(); err != nil { + if err := (MetafileFetchConfig{Origin: origin, RouteID: routeID, LinkRequests: linkRequests}).Validate(); err != nil { return nil, err } if start.IsZero() || end.IsZero() || end.Before(start) { @@ -160,14 +204,15 @@ func NewFetchedMetafile(ref domain.TorrentRef, origin, routeID string, start, en } copyOfRaw := bytes.Clone(raw) return &FetchedMetafile{ - ref: ref, - origin: origin, - routeID: routeID, - start: start.UTC(), - end: end.UTC(), - raw: copyOfRaw, - digest: sha256.Sum256(copyOfRaw), - authority: &fetchAuthority{}, + ref: ref, + origin: origin, + routeID: routeID, + start: start.UTC(), + end: end.UTC(), + linkRequests: linkRequests, + raw: copyOfRaw, + digest: sha256.Sum256(copyOfRaw), + authority: &fetchAuthority{}, }, nil } @@ -219,6 +264,7 @@ func (f *FetchedMetafile) MatchesReceipt(receipt MetafileFetchReceipt) bool { receipt.Complete && receipt.StopReason == "" && receipt.Used.RequestsAttempted == 1 && receipt.Used.AutomaticRetries == 0 && receipt.Used.RedirectsFollowed == 0 && receipt.Used.ResponseBytesKnown && + receipt.Used.LinkRequestsAttempted == f.linkRequests && f.linkRequests <= receipt.Limits.MaxLinkRequests && receipt.Used.ResponseBytesRead == int64(len(f.raw)) && int64(len(f.raw)) <= receipt.Limits.MaxResponseBytes } @@ -278,8 +324,9 @@ func (f *FetchedMetafile) BindImported(variantID string, bytesConsumed int64) (* return nil, err } return &ObservedMetafileBinding{ - observation: observation, - authority: f.authority, + observation: observation, + linkRequests: f.linkRequests, + authority: f.authority, }, nil } @@ -292,8 +339,9 @@ func (f FetchedMetafile) MarshalJSON() ([]byte, error) { // ObservedMetafileBinding retains process-local authority separately from its // serializable DTO. A deserialized public observation cannot regain authority. type ObservedMetafileBinding struct { - observation domain.SiteMetafileObservation - authority *fetchAuthority + observation domain.SiteMetafileObservation + linkRequests int + authority *fetchAuthority } func (binding *ObservedMetafileBinding) PublicCopy() domain.SiteMetafileObservation { @@ -326,6 +374,7 @@ func (binding *ObservedMetafileBinding) MatchesReceipt(receipt MetafileFetchRece receipt.Complete && receipt.StopReason == "" && receipt.Used.RequestsAttempted == 1 && receipt.Used.AutomaticRetries == 0 && receipt.Used.RedirectsFollowed == 0 && receipt.Used.ResponseBytesKnown && + receipt.Used.LinkRequestsAttempted == binding.linkRequests && binding.linkRequests <= receipt.Limits.MaxLinkRequests && receipt.Used.ResponseBytesRead == observation.ResponseBytes && observation.ResponseBytes <= receipt.Limits.MaxResponseBytes } diff --git a/internal/site/metafile_test.go b/internal/site/metafile_test.go index a0f1cd5..3bb5246 100644 --- a/internal/site/metafile_test.go +++ b/internal/site/metafile_test.go @@ -41,6 +41,8 @@ func TestDefaultMetafileFetchLimitsAreBounded(t *testing.T) { {MaxRequests: 1, MaxResponseBytes: 0, MaxResponseHeaderBytes: 1}, {MaxRequests: 1, MaxResponseBytes: (32 << 20) + 1, MaxResponseHeaderBytes: 1}, {MaxRequests: 1, MaxResponseBytes: 1, MaxResponseHeaderBytes: (64 << 10) + 1}, + {MaxRequests: 1, MaxResponseBytes: 1, MaxResponseHeaderBytes: 1, MaxLinkRequests: -1}, + {MaxRequests: 1, MaxResponseBytes: 1, MaxResponseHeaderBytes: 1, MaxLinkRequests: 3}, } { if err := invalid.Validate(); err == nil { t.Fatalf("invalid limits accepted: %#v", invalid) @@ -58,11 +60,68 @@ func TestMetafileFetchConfigIsCanonicalAndCredentialFree(t *testing.T) { {Origin: "http://fake.example", RouteID: "fake.download.v1"}, {Origin: "https://fake.example/", RouteID: "fake.download.v1"}, {Origin: "https://fake.example", RouteID: "cookie=value"}, + {Origin: "https://fake.example", RouteID: "fake.download.v1", LinkRequests: -1}, + {Origin: "https://fake.example", RouteID: "fake.download.v1", LinkRequests: 3}, } { if err := invalid.Validate(); err == nil { t.Fatalf("invalid config accepted: %#v", invalid) } } + if config.DefaultLimits() != site.DefaultMetafileFetchLimits() { + t.Fatalf("direct route defaults drifted: %#v", config.DefaultLimits()) + } + encoded, err := json.Marshal(struct { + Config site.MetafileFetchConfig + Limits site.MetafileFetchLimits + Used site.MetafileFetchUsage + }{config, config.DefaultLimits(), site.MetafileFetchUsage{RequestsAttempted: 1}}) + if err != nil || strings.Contains(string(encoded), "link_request") { + t.Fatalf("direct route JSON gained link fields: %s err=%v", encoded, err) + } + linked, err := site.NewLinkedMetafileFetchConfig("https://fake.example", "fake.linked.v1", 2) + if err != nil || linked.LinkRequests != 2 || linked.DefaultLimits().MaxLinkRequests != 2 || linked.DefaultLimits().MaxRequests != 1 { + t.Fatalf("linked config=%#v err=%v", linked, err) + } + if _, err := site.NewLinkedMetafileFetchConfig("https://fake.example", "fake.linked.v1", 3); err == nil { + t.Fatal("linked config over the link budget accepted") + } +} + +func TestLinkedFetchedMetafileMatchesOnlyItsLinkAccount(t *testing.T) { + raw := []byte("d4:infod4:name1:xee") + ref := domain.TorrentRef{SiteID: "fakept", RemoteID: "42"} + start := time.Date(2026, 10, 16, 1, 2, 3, 0, time.UTC) + end := start.Add(time.Second) + if _, err := site.NewLinkedFetchedMetafile(ref, "https://fake.example", "fake.linked.v1", start, end, 3, raw); err == nil { + t.Fatal("link count over the budget accepted") + } + fetched, err := site.NewLinkedFetchedMetafile(ref, "https://fake.example", "fake.linked.v1", start, end, 1, raw) + if err != nil { + t.Fatal(err) + } + limits := site.DefaultMetafileFetchLimits() + limits.MaxLinkRequests = 2 + receipt := site.MetafileFetchReceipt{ + Effect: site.MetafileFetchEffect, Ref: ref, Origin: "https://fake.example", RouteID: "fake.linked.v1", + ObservedAtStart: start, ObservedAtEnd: end, Complete: true, Limits: limits, + Used: site.MetafileFetchUsage{RequestsAttempted: 1, ResponseBytesRead: int64(len(raw)), ResponseBytesKnown: true, LinkRequestsAttempted: 1}, + } + if !fetched.MatchesReceipt(receipt) { + t.Fatal("linked receipt rejected") + } + for _, mutate := range []func(*site.MetafileFetchReceipt){ + func(r *site.MetafileFetchReceipt) { r.Used.LinkRequestsAttempted = 0 }, + func(r *site.MetafileFetchReceipt) { r.Used.LinkRequestsAttempted = 2 }, + func(r *site.MetafileFetchReceipt) { r.Limits.MaxLinkRequests = 0 }, + func(r *site.MetafileFetchReceipt) { r.Used.RequestsAttempted = 2 }, + func(r *site.MetafileFetchReceipt) { r.Used.RedirectsFollowed = 1 }, + } { + changed := receipt + mutate(&changed) + if fetched.MatchesReceipt(changed) { + t.Fatalf("mismatched receipt accepted: %#v", changed.Used) + } + } } func TestFetchedMetafileIsOpaqueImmutableAndExactlyBindable(t *testing.T) { diff --git a/internal/site/mteam/adapter.go b/internal/site/mteam/adapter.go index f49b342..9d8e14c 100644 --- a/internal/site/mteam/adapter.go +++ b/internal/site/mteam/adapter.go @@ -51,7 +51,9 @@ const ( // Adapter reads M-Team through one strict POST per command. It never retries, // never follows redirects, and never echoes the API key or a response body. type Adapter struct { - newClient guardedClientFactory + newClient guardedClientFactory + newLinkClient linkClientFactory + pause func(context.Context, time.Duration) error } type guardedClient interface { @@ -73,7 +75,7 @@ func newGuardedClient(baseURL, apiKey string, minInterval time.Duration) (guarde } func New() *Adapter { - return &Adapter{newClient: newGuardedClient} + return &Adapter{newClient: newGuardedClient, newLinkClient: newLinkClient} } func (a *Adapter) Descriptor() domain.SiteDescriptor { @@ -88,6 +90,7 @@ func (a *Adapter) Descriptor() domain.SiteDescriptor { domain.CapabilityAccountRead, domain.CapabilitySearch, domain.CapabilityDetail, + domain.CapabilityMetafile, }, } } diff --git a/internal/site/mteam/adapter_test.go b/internal/site/mteam/adapter_test.go index 53c626a..6015f64 100644 --- a/internal/site/mteam/adapter_test.go +++ b/internal/site/mteam/adapter_test.go @@ -83,7 +83,7 @@ func TestIdentityIsPinned(t *testing.T) { want := domain.SiteDescriptor{ ID: "mteam", Name: "M-Team / 馒头PT", BaseURL: "https://api2.m-team.cc/", Stability: "experimental", AuthMethods: []domain.AuthMethod{domain.AuthMethodAPIKeyHeader}, - Capabilities: []domain.Capability{domain.CapabilityAuthCheck, domain.CapabilityAccountRead, domain.CapabilitySearch, domain.CapabilityDetail}, + Capabilities: []domain.Capability{domain.CapabilityAuthCheck, domain.CapabilityAccountRead, domain.CapabilitySearch, domain.CapabilityDetail, domain.CapabilityMetafile}, } if got := New().Descriptor(); !reflect.DeepEqual(got, want) { t.Fatalf("descriptor=%#v", got) diff --git a/internal/site/mteam/metafile.go b/internal/site/mteam/metafile.go new file mode 100644 index 0000000..b01a128 --- /dev/null +++ b/internal/site/mteam/metafile.go @@ -0,0 +1,515 @@ +package mteam + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" + "github.com/tonycoder-hub/ptctl/internal/site/httpguard" +) + +const ( + MetafileOrigin = Origin + // MetafileRouteID names the linked download: one POST to + // api/torrent/genDlToken for a signed link, one GET of that link, and, only + // when the link redirects to another M-Team host, one GET of the target. + MetafileRouteID = "mteam.download_by_token.v1" + + tokenPath = "api/torrent/genDlToken" + signedLinkPath = "/api/rss/dlv2" + metafileAccept = "application/x-bittorrent,application/octet-stream;q=0.9" + + // metafileLinkRequests counts the token request and one redirect. + metafileLinkRequests = 2 + maxTokenBytes = 64 << 10 +) + +// metafileLimitMarkers identify a refusal for the per-torrent daily download +// limit or a request burst, which the API reports with the generic code "1". +// The text is only compared, never surfaced. +var metafileLimitMarkers = []string{"最多下載", "最多下载", "請求太多", "请求太多"} + +// siteDomains are the registrable domains a signed link or its redirect target +// may use. Any other host, or a non-HTTPS target such as magnet:, is never +// contacted. +var siteDomains = []string{"m-team.cc", "m-team.io"} + +var ( + _ site.MetafileFetcher = (*Adapter)(nil) + _ site.MetafileFetchSession = (*metafileFetchSession)(nil) +) + +type linkClient interface { + GetLinkOnce(context.Context, httpguard.SecretLink, string, int64, int64, func(*url.URL) bool) (httpguard.StrictResponse, httpguard.SecretLink, error) + RequestsMade() int + Close() error +} + +// linkClientFactory binds one credential-free client to one link host. +type linkClientFactory func(baseURL string) (linkClient, error) + +func newLinkClient(baseURL string) (linkClient, error) { + client, err := httpguard.NewWithoutCredential(baseURL, 0) + if err != nil { + return nil, err + } + return client, nil +} + +func (a *Adapter) ValidateMetafileRef(ref domain.TorrentRef) error { + return validateTorrentRef(ref) +} + +func (a *Adapter) MetafileFetchConfig() (site.MetafileFetchConfig, error) { + config, err := site.NewLinkedMetafileFetchConfig(MetafileOrigin, MetafileRouteID, metafileLinkRequests) + if err != nil { + return site.MetafileFetchConfig{}, fmt.Errorf("M-Team metafile fetch configuration is invalid") + } + return config, nil +} + +func (a *Adapter) OpenMetafileFetchSession(ctx context.Context, credential site.Credential) (site.MetafileFetchSession, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + config, err := a.MetafileFetchConfig() + if err != nil { + return nil, err + } + if credential.Method() != domain.AuthMethodAPIKeyHeader { + return nil, fmt.Errorf("M-Team metafile fetch requires api_key_header authentication") + } + if !validAPIKey(credential.SecretValue()) { + return nil, fmt.Errorf("M-Team API key is malformed: %w", site.ErrCredentialMalformed) + } + client, err := a.clientFactory()(DefaultBaseURL, credential.SecretValue(), minRequestInterval) + if err != nil || client == nil { + return nil, fmt.Errorf("open M-Team metafile fetch session failed") + } + return &metafileFetchSession{api: client, newLink: a.linkClientFactory(), pause: a.pauseFunc(), config: config}, nil +} + +func (a *Adapter) linkClientFactory() linkClientFactory { + if a != nil && a.newLinkClient != nil { + return a.newLinkClient + } + return newLinkClient +} + +func (a *Adapter) pauseFunc() func(context.Context, time.Duration) error { + if a != nil && a.pause != nil { + return a.pause + } + return pause +} + +func pause(ctx context.Context, wait time.Duration) error { + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return nil + } +} + +type metafileFetchSession struct { + api guardedClient + newLink linkClientFactory + pause func(context.Context, time.Duration) error + config site.MetafileFetchConfig + mu sync.Mutex + links []linkClient + usage site.MetafileFetchUsage + used bool + closed bool +} + +// fetchStop is a failed step: the public stop reason and the adapter error. +type fetchStop struct { + reason string + err error +} + +func stopWith(reason, format string, args ...any) *fetchStop { + return &fetchStop{reason: reason, err: fmt.Errorf(format, args...)} +} + +func (session *metafileFetchSession) FetchMetafile(ctx context.Context, ref domain.TorrentRef, limits site.MetafileFetchLimits) (*site.FetchedMetafile, site.MetafileFetchReceipt, error) { + now := time.Now().UTC() + receipt := site.MetafileFetchReceipt{ + Effect: site.MetafileFetchEffect, + Origin: session.config.Origin, + RouteID: session.config.RouteID, + ObservedAtStart: now, + ObservedAtEnd: now, + Limits: limits, + } + if err := limits.Validate(); err != nil || limits.MaxLinkRequests != session.config.LinkRequests { + receipt.StopReason = "invalid_limits" + return nil, receipt, fmt.Errorf("M-Team metafile fetch limits are invalid") + } + if err := validateTorrentRef(ref); err != nil { + receipt.StopReason = "invalid_reference" + return nil, receipt, err + } + receipt.Ref = ref + if err := ctx.Err(); err != nil { + receipt.StopReason = "context_done" + return nil, receipt, err + } + + session.mu.Lock() + if session.closed { + session.mu.Unlock() + receipt.StopReason = "session_closed" + return nil, receipt, fmt.Errorf("M-Team metafile fetch session is closed") + } + if session.used { + receipt.Used.RequestsAttempted = session.usage.RequestsAttempted + receipt.Used.LinkRequestsAttempted = session.usage.LinkRequestsAttempted + session.mu.Unlock() + receipt.StopReason = "request_budget_exhausted" + return nil, receipt, fmt.Errorf("M-Team metafile fetch request budget is exhausted") + } + session.used = true + session.mu.Unlock() + + raw, stop := session.fetch(ctx, ref, limits, &receipt) + session.mu.Lock() + session.usage = receipt.Used + session.mu.Unlock() + if stop != nil { + receipt.StopReason = stop.reason + return nil, receipt, stop.err + } + fetched, err := site.NewLinkedFetchedMetafile(ref, session.config.Origin, session.config.RouteID, receipt.ObservedAtStart, receipt.ObservedAtEnd, receipt.Used.LinkRequestsAttempted, raw) + if err != nil { + receipt.StopReason = "response_authority_invalid" + return nil, receipt, fmt.Errorf("M-Team metafile response authority could not be created") + } + receipt.Complete = true + return fetched, receipt, nil +} + +// fetch runs the linked route and returns the metafile response body. It +// records every request in receipt as it is made. +func (session *metafileFetchSession) fetch(ctx context.Context, ref domain.TorrentRef, limits site.MetafileFetchLimits, receipt *site.MetafileFetchReceipt) ([]byte, *fetchStop) { + started := false + observe := func(response httpguard.StrictResponse) { + if !started && !response.ObservedAtStart.IsZero() { + receipt.ObservedAtStart = response.ObservedAtStart + started = true + } + if !response.ObservedAtEnd.IsZero() { + receipt.ObservedAtEnd = response.ObservedAtEnd + } else { + receipt.ObservedAtEnd = time.Now().UTC() + } + } + + response, err := session.api.PostReadOnce(ctx, tokenPath, emptyFormMediaType, formBody("id", ref.RemoteID), apiAccept, maxRequestBytes, maxTokenBytes, limits.MaxResponseHeaderBytes) + receipt.Used.LinkRequestsAttempted = session.api.RequestsMade() + observe(response) + if stop := requestStop(ctx, err, receipt.Used.LinkRequestsAttempted, response); stop != nil { + return nil, stop + } + link, stop := classifyTokenResponse(response, ref) + if stop != nil { + return nil, stop + } + + // The token request and the link GET reach the same API, so keep the + // interval the site asks for between them. + if err := session.pause(ctx, minRequestInterval); err != nil { + return nil, stopWith("context_done", "M-Team metafile request stopped: %w", err) + } + response, next, stop := session.get(ctx, link, limits, approvedRedirect) + if stop != nil { + receipt.Used.RequestsAttempted = 1 + observe(response) + return nil, stop + } + observe(response) + if response.StatusCode >= 300 && response.StatusCode <= 399 && !next.IsZero() { + receipt.Used.LinkRequestsAttempted++ + response, _, stop = session.get(ctx, next, limits, nil) + observe(response) + if stop != nil { + receipt.Used.RequestsAttempted = 1 + return nil, stop + } + } + receipt.Used.RequestsAttempted = 1 + receipt.Used.ResponseBytesRead = response.ResponseBytesRead + receipt.Used.ResponseBytesKnown = response.ResponseBytesKnown + if stop := classifyMetafileResponse(response); stop != nil { + return nil, stop + } + return response.Body, nil +} + +// get performs one GET of link on a fresh credential-free client bound to the +// link's own host. +func (session *metafileFetchSession) get(ctx context.Context, link httpguard.SecretLink, limits site.MetafileFetchLimits, approve func(*url.URL) bool) (httpguard.StrictResponse, httpguard.SecretLink, *fetchStop) { + target := link.URL() + if target == nil || !siteHost(target.Host) { + return httpguard.StrictResponse{}, httpguard.SecretLink{}, stopWith("redirect_rejected", "M-Team download link host was rejected") + } + client, err := session.newLink("https://" + target.Host + "/") + if err != nil || client == nil { + return httpguard.StrictResponse{}, httpguard.SecretLink{}, stopWith("site_request_failed", "open M-Team download link client failed") + } + session.mu.Lock() + session.links = append(session.links, client) + session.mu.Unlock() + response, next, err := client.GetLinkOnce(ctx, link, metafileAccept, limits.MaxResponseBytes, limits.MaxResponseHeaderBytes, approve) + if stop := requestStop(ctx, err, client.RequestsMade(), response); stop != nil { + return response, httpguard.SecretLink{}, stop + } + return response, next, nil +} + +// requestStop checks one request's error and accounting. +func requestStop(ctx context.Context, err error, requests int, response httpguard.StrictResponse) *fetchStop { + if err != nil { + if errors.Is(err, context.Canceled) || errors.Is(ctx.Err(), context.Canceled) { + return stopWith("context_done", "M-Team metafile request stopped: %w", context.Canceled) + } + if errors.Is(err, context.DeadlineExceeded) || errors.Is(ctx.Err(), context.DeadlineExceeded) { + return stopWith("context_done", "M-Team metafile request stopped: %w", context.DeadlineExceeded) + } + if requests != 1 { + return stopWith("request_accounting_invalid", "M-Team metafile request accounting is invalid") + } + if errors.Is(err, httpguard.ErrBlockedAddress) { + return stopWith("site_request_failed", "M-Team metafile request failed: %w", site.ErrAddressBlocked) + } + return stopWith("site_request_failed", "M-Team metafile request failed") + } + if requests != 1 { + return stopWith("request_accounting_invalid", "M-Team metafile request accounting is invalid") + } + if !response.ResponseBytesKnown || response.ResponseBytesRead != int64(len(response.Body)) || + response.ObservedAtStart.IsZero() || response.ObservedAtEnd.IsZero() || response.ObservedAtEnd.Before(response.ObservedAtStart) { + return stopWith("response_accounting_invalid", "M-Team metafile response accounting is invalid") + } + return nil +} + +// classifyTokenResponse maps the genDlToken answer to the signed link it +// carries. The link is a secret: it is never returned in an error. +func classifyTokenResponse(response httpguard.StrictResponse, ref domain.TorrentRef) (httpguard.SecretLink, *fetchStop) { + code, message, data, stop := decodeAPIAnswer(response) + if stop != nil { + return httpguard.SecretLink{}, stop + } + switch code { + case "0": + var raw string + if json.Unmarshal(data, &raw) != nil { + break + } + link, err := httpguard.NewSecretLink(raw) + if err != nil || !validSignedLink(link.URL(), ref) { + break + } + return link, nil + case "401": + return httpguard.SecretLink{}, stopWith("authentication_required", "M-Team API rejected the request: %w", site.ErrCredentialRejected) + case "4": + return httpguard.SecretLink{}, stopWith("rate_limited", "M-Team API refused the request: %w", site.ErrRateLimited) + case "1": + if notFoundRefusal(message, data) { + return httpguard.SecretLink{}, stopWith("not_found", "M-Team torrent was not found") + } + if limitRefusal(message) { + return httpguard.SecretLink{}, stopWith("rate_limited", "M-Team refused the download: %w", site.ErrRateLimited) + } + } + return httpguard.SecretLink{}, stopWith("unrecognized_response", "M-Team download token response was not recognized") +} + +// classifyMetafileResponse accepts a bencoded body and maps the API's JSON +// refusals, which answer with HTTP 200, to stop reasons. The token request +// signs a link for any ID, so an unknown torrent is only reported here. +func classifyMetafileResponse(response httpguard.StrictResponse) *fetchStop { + switch { + case response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusForbidden: + return stopWith("authentication_required", "M-Team rejected the download link") + case response.StatusCode == http.StatusTooManyRequests: + return stopWith("rate_limited", "M-Team refused the download: %w", site.ErrRateLimited) + case response.StatusCode >= 300 && response.StatusCode <= 399: + return stopWith("redirect_rejected", "M-Team download redirect was rejected") + case response.StatusCode != http.StatusOK: + return stopWith("http_status_rejected", "M-Team metafile response status was rejected") + case len(response.Body) == 0: + return stopWith("empty_response", "M-Team metafile response was empty") + } + if response.Body[0] == 'd' { + switch response.MediaType { + case "", "application/x-bittorrent", "application/octet-stream", "application/download", "application/force-download", "binary/octet-stream": + return nil + } + return stopWith("content_type_rejected", "M-Team metafile content type was rejected") + } + if code, message, data, stop := decodeAPIAnswer(response); stop == nil { + switch { + case code == "401": + return stopWith("authentication_required", "M-Team rejected the download link") + case code == "1" && notFoundRefusal(message, data): + return stopWith("not_found", "M-Team torrent was not found") + case code == "4", code == "1" && limitRefusal(message): + return stopWith("rate_limited", "M-Team refused the download: %w", site.ErrRateLimited) + } + } + return stopWith("unrecognized_response", "M-Team metafile response was not recognized") +} + +// decodeAPIAnswer reads one API envelope. The message is returned only for +// comparison against known refusals. +func decodeAPIAnswer(response httpguard.StrictResponse) (string, *string, json.RawMessage, *fetchStop) { + switch { + case response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusForbidden: + return "", nil, nil, stopWith("authentication_required", "M-Team API rejected the request: %w", site.ErrCredentialRejected) + case response.StatusCode == http.StatusTooManyRequests: + return "", nil, nil, stopWith("rate_limited", "M-Team API refused the request: %w", site.ErrRateLimited) + case response.StatusCode >= 300 && response.StatusCode <= 399: + return "", nil, nil, stopWith("redirect_rejected", "M-Team API redirect was rejected") + case response.StatusCode != http.StatusOK: + return "", nil, nil, stopWith("http_status_rejected", "M-Team API response status was rejected") + case len(response.Body) == 0: + return "", nil, nil, stopWith("empty_response", "M-Team API response was empty") + case !utf8.Valid(response.Body): + return "", nil, nil, stopWith("unrecognized_response", "M-Team API response text was invalid") + } + switch response.MediaType { + case "application/json", "text/plain", "": + default: + return "", nil, nil, stopWith("content_type_rejected", "M-Team API response was not JSON") + } + var envelope struct { + Code flexText `json:"code"` + Message *string `json:"message"` + Data json.RawMessage `json:"data"` + } + if err := json.Unmarshal(response.Body, &envelope); err != nil || !envelope.Code.set { + return "", nil, nil, stopWith("unrecognized_response", "M-Team API response was not recognized") + } + return envelope.Code.value, envelope.Message, envelope.Data, nil +} + +func emptyData(data json.RawMessage) bool { + trimmed := strings.TrimSpace(string(data)) + return trimmed == "" || trimmed == "null" +} + +// notFoundRefusal reports the exact code "1" answer for a torrent that does not +// exist: a known message and no data, the same pair torrent detail reads. +func notFoundRefusal(message *string, data json.RawMessage) bool { + if message == nil || !emptyData(data) { + return false + } + _, ok := detailNotFoundMessages[strings.TrimSpace(*message)] + return ok +} + +func limitRefusal(message *string) bool { + if message == nil { + return false + } + for _, marker := range metafileLimitMarkers { + if strings.Contains(*message, marker) { + return true + } + } + return false +} + +// validSignedLink accepts only the RSS download endpoint on an M-Team host, +// signed for exactly the requested torrent. +func validSignedLink(link *url.URL, ref domain.TorrentRef) bool { + if link == nil || !siteHost(link.Host) || link.Path != signedLinkPath { + return false + } + query, err := url.ParseQuery(link.RawQuery) + if err != nil { + return false + } + tid, sign := query["tid"], query["sign"] + return len(tid) == 1 && tid[0] == ref.RemoteID && len(sign) == 1 && sign[0] != "" +} + +// approvedRedirect lets the link GET report a redirect target only on an +// M-Team host over HTTPS on the default port. +func approvedRedirect(target *url.URL) bool { + return target != nil && target.Scheme == "https" && siteHost(target.Host) +} + +// siteHost reports whether host, which must carry no port, is one of +// siteDomains or a subdomain of one. +func siteHost(host string) bool { + if host == "" || host != strings.ToLower(host) || strings.HasSuffix(host, ".") { + return false + } + for _, domain := range siteDomains { + if host == domain || strings.HasSuffix(host, "."+domain) { + return true + } + } + return false +} + +func (session *metafileFetchSession) RequestsMade() int { + if session == nil { + return 0 + } + session.mu.Lock() + defer session.mu.Unlock() + total := 0 + if session.api != nil { + total += session.api.RequestsMade() + } + for _, client := range session.links { + total += client.RequestsMade() + } + return total +} + +func (session *metafileFetchSession) Close() error { + if session == nil { + return nil + } + session.mu.Lock() + if session.closed { + session.mu.Unlock() + return nil + } + session.closed = true + clients := append([]linkClient(nil), session.links...) + api := session.api + session.mu.Unlock() + failed := false + if api != nil && api.Close() != nil { + failed = true + } + for _, client := range clients { + if client.Close() != nil { + failed = true + } + } + if failed { + return fmt.Errorf("close M-Team metafile fetch session failed") + } + return nil +} diff --git a/internal/site/mteam/metafile_test.go b/internal/site/mteam/metafile_test.go new file mode 100644 index 0000000..c9a1793 --- /dev/null +++ b/internal/site/mteam/metafile_test.go @@ -0,0 +1,370 @@ +package mteam + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/site" + "github.com/tonycoder-hub/ptctl/internal/site/httpguard" +) + +// The signed links below are synthetic; a real one is a credential. +const ( + signedLinkFixture = "https://api2.m-team.cc/api/rss/dlv2?sign=SIGN-CANARY&t=1760000000&tid=900001&uid=100001" + tokenFixture = `{"code":"0","message":"SUCCESS","data":"` + signedLinkFixture + `"}` + metafileFixture = "d8:announce30:https://tracker.invalid/CANARY4:infod4:name6:canary7:privatei1eee" +) + +type fakeLinkClient struct { + baseURL string + response httpguard.StrictResponse + next string + err error + links []string + approve []bool + closed bool +} + +func (f *fakeLinkClient) GetLinkOnce(_ context.Context, link httpguard.SecretLink, accept string, _, _ int64, approve func(*url.URL) bool) (httpguard.StrictResponse, httpguard.SecretLink, error) { + if accept != metafileAccept { + return httpguard.StrictResponse{}, httpguard.SecretLink{}, fmt.Errorf("unexpected accept") + } + f.links = append(f.links, link.URL().String()) + f.approve = append(f.approve, approve != nil) + var next httpguard.SecretLink + if parsed, err := httpguard.NewSecretLink(f.next); err == nil && approve != nil && approve(parsed.URL()) { + next = parsed + } + return f.response, next, f.err +} + +func (f *fakeLinkClient) RequestsMade() int { return len(f.links) } + +func (f *fakeLinkClient) Close() error { + f.closed = true + return nil +} + +type linkRecord struct { + opened []string + pauses []time.Duration +} + +func observedBody(status int, mediaType, body string) httpguard.StrictResponse { + response := observedJSON(body) + response.StatusCode, response.MediaType = status, mediaType + return response +} + +func torrentBody() httpguard.StrictResponse { + return observedBody(http.StatusOK, "application/x-bittorrent", metafileFixture) +} + +func redirectTo() httpguard.StrictResponse { + return observedBody(http.StatusFound, "text/html", "") +} + +// openMetafile opens a session whose link clients come from links, keyed by +// base URL. A base URL with no entry fails the test when it is opened. +func openMetafile(t *testing.T, api *fakeClient, links map[string]*fakeLinkClient) (site.MetafileFetchSession, *linkRecord) { + t.Helper() + adapter, apiRecord := fakeAdapter(api) + record := &linkRecord{} + adapter.newLinkClient = func(baseURL string) (linkClient, error) { + record.opened = append(record.opened, baseURL) + client, ok := links[baseURL] + if !ok { + t.Fatalf("unexpected link host opened") + } + client.baseURL = baseURL + return client, nil + } + adapter.pause = func(ctx context.Context, wait time.Duration) error { + record.pauses = append(record.pauses, wait) + return ctx.Err() + } + session, err := adapter.OpenMetafileFetchSession(context.Background(), apiKey(t)) + if err != nil { + t.Fatal(err) + } + if apiRecord.opened != 1 || apiRecord.baseURL != DefaultBaseURL || apiRecord.apiKey != testAPIKey || apiRecord.interval != minRequestInterval { + t.Fatalf("api factory=%#v", apiRecord) + } + return session, record +} + +func metafileLimits(t *testing.T) site.MetafileFetchLimits { + t.Helper() + config, err := New().MetafileFetchConfig() + if err != nil { + t.Fatal(err) + } + return config.DefaultLimits() +} + +func assertNoSecret(t *testing.T, values ...any) { + t.Helper() + for _, value := range values { + encoded, _ := json.Marshal(value) + text := fmt.Sprintf("%v %+v %s", value, value, encoded) + for _, secret := range []string{"CANARY", "sign=", "dlv2", "種子", "种子", "最多", "请求太多"} { + if strings.Contains(text, secret) { + t.Fatalf("secret or server text %q leaked: %s", secret, text) + } + } + } +} + +func TestMetafileConfigIsPinned(t *testing.T) { + config, err := New().MetafileFetchConfig() + if err != nil || config.Origin != "https://api2.m-team.cc" || config.RouteID != "mteam.download_by_token.v1" || config.LinkRequests != 2 { + t.Fatalf("config=%#v err=%v", config, err) + } + if limits := config.DefaultLimits(); limits.MaxRequests != 1 || limits.MaxLinkRequests != 2 || limits.Validate() != nil { + t.Fatalf("limits=%#v", limits) + } + if err := New().ValidateMetafileRef(detailRef("900001")); err != nil { + t.Fatal(err) + } + for _, id := range []string{"", "0", "01", "-1", "1a", "900001 "} { + if err := New().ValidateMetafileRef(detailRef(id)); err == nil { + t.Fatalf("ref %q accepted", id) + } + } +} + +func TestMetafileFetchesASignedLinkDirectly(t *testing.T) { + api := &fakeClient{response: observedJSON(tokenFixture)} + link := &fakeLinkClient{response: torrentBody()} + session, record := openMetafile(t, api, map[string]*fakeLinkClient{"https://api2.m-team.cc/": link}) + fetched, receipt, err := session.FetchMetafile(context.Background(), detailRef("900001"), metafileLimits(t)) + if err != nil || fetched == nil || !receipt.Complete || receipt.StopReason != "" { + t.Fatalf("receipt=%+v err=%v", receipt, err) + } + if len(api.calls) != 1 || api.calls[0].path != "api/torrent/genDlToken" || api.calls[0].contentType != emptyFormMediaType || + api.calls[0].body != string(formBody("id", "900001")) || api.calls[0].maxBody != maxTokenBytes { + t.Fatalf("token calls=%#v", api.calls) + } + if len(link.links) != 1 || link.links[0] != signedLinkFixture || !link.approve[0] { + t.Fatalf("link was not requested exactly once as issued") + } + if len(record.pauses) != 1 || record.pauses[0] != minRequestInterval { + t.Fatalf("pauses=%v", record.pauses) + } + want := site.MetafileFetchUsage{RequestsAttempted: 1, LinkRequestsAttempted: 1, ResponseBytesRead: int64(len(metafileFixture)), ResponseBytesKnown: true} + if receipt.Used != want || session.RequestsMade() != 2 || !fetched.MatchesReceipt(receipt) { + t.Fatalf("used=%+v requests=%d", receipt.Used, session.RequestsMade()) + } + if receipt.Origin != MetafileOrigin || receipt.RouteID != MetafileRouteID || receipt.Ref != detailRef("900001") { + t.Fatalf("receipt identity=%+v", receipt) + } + assertNoSecret(t, receipt, err) + if err := session.Close(); err != nil || !api.closed || !link.closed { + t.Fatalf("close err=%v api=%v link=%v", err, api.closed, link.closed) + } +} + +func TestMetafileFollowsOneRedirectToAnMTeamHost(t *testing.T) { + const target = "https://cdn.m-team.cc/torrents/900001.torrent?k=CANARY" + api := &fakeClient{response: observedJSON(tokenFixture)} + link := &fakeLinkClient{response: redirectTo(), next: target} + final := &fakeLinkClient{response: torrentBody(), next: "https://cdn.m-team.cc/again?k=CANARY"} + session, record := openMetafile(t, api, map[string]*fakeLinkClient{"https://api2.m-team.cc/": link, "https://cdn.m-team.cc/": final}) + fetched, receipt, err := session.FetchMetafile(context.Background(), detailRef("900001"), metafileLimits(t)) + if err != nil || fetched == nil || !receipt.Complete { + t.Fatalf("receipt=%+v err=%v", receipt, err) + } + if strings.Join(record.opened, " ") != "https://api2.m-team.cc/ https://cdn.m-team.cc/" { + t.Fatalf("opened %d link clients", len(record.opened)) + } + if len(final.links) != 1 || final.links[0] != target || final.approve[0] { + t.Fatalf("final hop was not one exact GET without further redirects") + } + want := site.MetafileFetchUsage{RequestsAttempted: 1, LinkRequestsAttempted: 2, ResponseBytesRead: int64(len(metafileFixture)), ResponseBytesKnown: true} + if receipt.Used != want || session.RequestsMade() != 3 || !fetched.MatchesReceipt(receipt) { + t.Fatalf("used=%+v requests=%d", receipt.Used, session.RequestsMade()) + } + assertNoSecret(t, receipt) + if err := session.Close(); err != nil || !final.closed || !link.closed { + t.Fatalf("close err=%v", err) + } +} + +func TestMetafileNeverContactsAnotherHost(t *testing.T) { + for _, test := range []struct { + name, next string + final *fakeLinkClient + wantLinks int + }{ + {name: "other host", next: "https://www.google.com/?q=CANARY", wantLinks: 1}, + {name: "lookalike host", next: "https://m-team.cc.example/x?k=CANARY", wantLinks: 1}, + {name: "other port", next: "https://cdn.m-team.cc:8443/x?k=CANARY", wantLinks: 1}, + {name: "plain http", next: "http://cdn.m-team.cc/x?k=CANARY", wantLinks: 1}, + {name: "magnet", next: "magnet:?xt=urn:btih:CANARY", wantLinks: 1}, + {name: "no location", wantLinks: 1}, + {name: "second redirect", next: "https://cdn.m-team.io/x?k=CANARY", final: &fakeLinkClient{response: redirectTo(), next: "https://cdn.m-team.io/y"}, wantLinks: 2}, + } { + t.Run(test.name, func(t *testing.T) { + links := map[string]*fakeLinkClient{"https://api2.m-team.cc/": {response: redirectTo(), next: test.next}} + if test.final != nil { + links["https://cdn.m-team.io/"] = test.final + } + session, record := openMetafile(t, &fakeClient{response: observedJSON(tokenFixture)}, links) + fetched, receipt, err := session.FetchMetafile(context.Background(), detailRef("900001"), metafileLimits(t)) + if err == nil || fetched != nil || receipt.Complete || receipt.StopReason != "redirect_rejected" { + t.Fatalf("receipt=%+v err=%v", receipt, err) + } + if len(record.opened) != test.wantLinks || receipt.Used.LinkRequestsAttempted != test.wantLinks || receipt.Used.RequestsAttempted != 1 || session.RequestsMade() != test.wantLinks+1 { + t.Fatalf("opened=%d used=%+v", len(record.opened), receipt.Used) + } + assertNoSecret(t, receipt, err) + }) + } +} + +func TestMetafileTokenRefusalsStopBeforeTheLink(t *testing.T) { + link := func(raw string) httpguard.StrictResponse { + return observedJSON(`{"code":"0","message":"SUCCESS","data":"` + raw + `"}`) + } + for _, test := range []struct { + name string + response httpguard.StrictResponse + stop string + cause error + }{ + {name: "not found", response: observedJSON(`{"code":"1","message":"種子未找到","data":null}`), stop: "not_found"}, + {name: "not found simplified", response: observedJSON(`{"code":1,"message":"种子未找到"}`), stop: "not_found"}, + {name: "daily limit", response: observedJSON(`{"code":"1","message":"相同種子當天最多下載10次","data":null}`), stop: "rate_limited", cause: site.ErrRateLimited}, + {name: "burst", response: observedJSON(`{"code":"1","message":"当前请求太多,请10秒后重试","data":null}`), stop: "rate_limited", cause: site.ErrRateLimited}, + {name: "other refusal", response: observedJSON(`{"code":"1","message":"CANARY refusal","data":null}`), stop: "unrecognized_response"}, + {name: "api code 401", response: observedJSON(`{"code":"401","message":"CANARY","data":null}`), stop: "authentication_required", cause: site.ErrCredentialRejected}, + {name: "http 401", response: observedBody(http.StatusUnauthorized, "application/json", `{}`), stop: "authentication_required", cause: site.ErrCredentialRejected}, + {name: "api code 4", response: observedJSON(`{"code":"4","message":"CANARY","data":null}`), stop: "rate_limited", cause: site.ErrRateLimited}, + {name: "http 429", response: observedBody(http.StatusTooManyRequests, "application/json", `{}`), stop: "rate_limited", cause: site.ErrRateLimited}, + {name: "redirect", response: observedBody(http.StatusFound, "text/html", ""), stop: "redirect_rejected"}, + {name: "server error", response: observedBody(http.StatusInternalServerError, "text/html", "CANARY"), stop: "http_status_rejected"}, + {name: "html", response: observedBody(http.StatusOK, "text/html", "CANARY"), stop: "content_type_rejected"}, + {name: "not json", response: observedJSON("CANARY"), stop: "unrecognized_response"}, + {name: "object data", response: observedJSON(`{"code":"0","data":{"url":"` + signedLinkFixture + `"}}`), stop: "unrecognized_response"}, + {name: "other host", response: link("https://api.example.invalid/api/rss/dlv2?sign=SIGN-CANARY&tid=900001"), stop: "unrecognized_response"}, + {name: "plain http", response: link("http://api.m-team.cc/api/rss/dlv2?sign=SIGN-CANARY&tid=900001"), stop: "unrecognized_response"}, + {name: "port", response: link("https://api.m-team.cc:8443/api/rss/dlv2?sign=SIGN-CANARY&tid=900001"), stop: "unrecognized_response"}, + {name: "other path", response: link("https://api.m-team.cc/api/rss/other?sign=SIGN-CANARY&tid=900001"), stop: "unrecognized_response"}, + {name: "other torrent", response: link("https://api.m-team.cc/api/rss/dlv2?sign=SIGN-CANARY&tid=900002"), stop: "unrecognized_response"}, + {name: "two torrents", response: link("https://api.m-team.cc/api/rss/dlv2?sign=SIGN-CANARY&tid=900001&tid=900002"), stop: "unrecognized_response"}, + {name: "unsigned", response: link("https://api.m-team.cc/api/rss/dlv2?tid=900001"), stop: "unrecognized_response"}, + {name: "user info", response: link("https://u:CANARY@api.m-team.cc/api/rss/dlv2?sign=SIGN-CANARY&tid=900001"), stop: "unrecognized_response"}, + } { + t.Run(test.name, func(t *testing.T) { + session, record := openMetafile(t, &fakeClient{response: test.response}, nil) + fetched, receipt, err := session.FetchMetafile(context.Background(), detailRef("900001"), metafileLimits(t)) + if err == nil || fetched != nil || receipt.StopReason != test.stop || (test.cause != nil && !errors.Is(err, test.cause)) { + t.Fatalf("stop=%q err=%v", receipt.StopReason, err) + } + if len(record.opened) != 0 || len(record.pauses) != 0 || receipt.Used.LinkRequestsAttempted != 1 || receipt.Used.RequestsAttempted != 0 || session.RequestsMade() != 1 { + t.Fatalf("opened=%d pauses=%d used=%+v", len(record.opened), len(record.pauses), receipt.Used) + } + assertNoSecret(t, receipt, err) + }) + } +} + +func TestMetafileLinkRefusals(t *testing.T) { + for _, test := range []struct { + name string + response httpguard.StrictResponse + err error + stop string + }{ + // The token request signs a link for any ID; the link answers for an + // unknown torrent with this exact shape, observed live on 2026-10-16. + {name: "not found", response: observedJSON(`{"code":"1","message":"種子未找到","data":null}`), stop: "not_found"}, + {name: "not found simplified", response: observedJSON(`{"code":"1","message":"种子未找到"}`), stop: "not_found"}, + {name: "not found with data", response: observedJSON(`{"code":"1","message":"種子未找到","data":{"x":"CANARY"}}`), stop: "unrecognized_response"}, + {name: "daily limit", response: observedJSON(`{"code":"1","message":"相同種子當天最多下載10次","data":null}`), stop: "rate_limited"}, + {name: "burst", response: observedJSON(`{"code":1,"message":"当前请求太多,请10秒后重试"}`), stop: "rate_limited"}, + {name: "other json", response: observedJSON(`{"code":"1","message":"CANARY","data":null}`), stop: "unrecognized_response"}, + {name: "html", response: observedBody(http.StatusOK, "text/html", "CANARY"), stop: "unrecognized_response"}, + {name: "bencoded as html", response: observedBody(http.StatusOK, "text/html", metafileFixture), stop: "content_type_rejected"}, + {name: "empty", response: observedBody(http.StatusOK, "application/x-bittorrent", ""), stop: "empty_response"}, + {name: "forbidden", response: observedBody(http.StatusForbidden, "text/html", ""), stop: "authentication_required"}, + {name: "too many", response: observedBody(http.StatusTooManyRequests, "text/html", ""), stop: "rate_limited"}, + {name: "server error", response: observedBody(http.StatusBadGateway, "text/html", ""), stop: "http_status_rejected"}, + {name: "request failed", err: fmt.Errorf("site request failed"), stop: "site_request_failed"}, + {name: "blocked address", err: fmt.Errorf("wrapped: %w", httpguard.ErrBlockedAddress), stop: "site_request_failed"}, + } { + t.Run(test.name, func(t *testing.T) { + link := &fakeLinkClient{response: test.response, err: test.err} + session, _ := openMetafile(t, &fakeClient{response: observedJSON(tokenFixture)}, map[string]*fakeLinkClient{"https://api2.m-team.cc/": link}) + fetched, receipt, err := session.FetchMetafile(context.Background(), detailRef("900001"), metafileLimits(t)) + if err == nil || fetched != nil || receipt.Complete || receipt.StopReason != test.stop { + t.Fatalf("stop=%q err=%v", receipt.StopReason, err) + } + if receipt.Used.LinkRequestsAttempted != 1 || receipt.Used.RequestsAttempted != 1 || session.RequestsMade() != 2 { + t.Fatalf("used=%+v requests=%d", receipt.Used, session.RequestsMade()) + } + assertNoSecret(t, receipt, err) + }) + } +} + +func TestMetafileSessionBudgetsAndCredential(t *testing.T) { + api := &fakeClient{response: observedJSON(tokenFixture)} + session, _ := openMetafile(t, api, map[string]*fakeLinkClient{"https://api2.m-team.cc/": {response: torrentBody()}}) + direct := site.DefaultMetafileFetchLimits() + if _, receipt, err := session.FetchMetafile(context.Background(), detailRef("900001"), direct); err == nil || receipt.StopReason != "invalid_limits" || session.RequestsMade() != 0 { + t.Fatalf("direct-route limits accepted: stop=%q", receipt.StopReason) + } + if _, _, err := session.FetchMetafile(context.Background(), detailRef("900001"), metafileLimits(t)); err != nil { + t.Fatal(err) + } + _, receipt, err := session.FetchMetafile(context.Background(), detailRef("900001"), metafileLimits(t)) + if err == nil || receipt.StopReason != "request_budget_exhausted" || receipt.Used.RequestsAttempted != 1 || receipt.Used.LinkRequestsAttempted != 1 || len(api.calls) != 1 { + t.Fatalf("second fetch: stop=%q used=%+v", receipt.StopReason, receipt.Used) + } + + canceled, record := openMetafile(t, &fakeClient{response: observedJSON(tokenFixture)}, nil) + ctx, cancel := context.WithCancel(context.Background()) + adapterPause := func(context.Context, time.Duration) error { cancel(); return context.Canceled } + canceled.(*metafileFetchSession).pause = adapterPause + if _, receipt, err := canceled.FetchMetafile(ctx, detailRef("900001"), metafileLimits(t)); !errors.Is(err, context.Canceled) || receipt.StopReason != "context_done" || len(record.opened) != 0 { + t.Fatalf("canceled pause: stop=%q err=%v", receipt.StopReason, err) + } + + cookie, err := site.NewCookieCredential("c_secure_pass=CANARY") + if err != nil { + t.Fatal(err) + } + if _, err := New().OpenMetafileFetchSession(context.Background(), cookie); err == nil { + t.Fatal("cookie credential accepted") + } + malformed, err := site.NewAPIKeyCredential("MTEAM KEY CANARY") + if err == nil { + if _, err := New().OpenMetafileFetchSession(context.Background(), malformed); !errors.Is(err, site.ErrCredentialMalformed) { + t.Fatalf("malformed key: %v", err) + } + } +} + +func TestSiteHostAllowsOnlyMTeamDomains(t *testing.T) { + for host, want := range map[string]bool{ + "m-team.cc": true, "api.m-team.cc": true, "api2.m-team.cc": true, "cdn.m-team.io": true, + "API.m-team.cc": false, "m-team.cc.": false, "api.m-team.cc:443": false, "evil-m-team.cc": false, + "m-team.cc.example": false, "m-team.com": false, "": false, + } { + if got := siteHost(host); got != want { + t.Fatalf("siteHost(%q)=%v", host, got) + } + } + if validSignedLink(nil, domain.TorrentRef{}) || approvedRedirect(nil) { + t.Fatal("nil URL accepted") + } +} diff --git a/internal/site/sitetest/sitetest.go b/internal/site/sitetest/sitetest.go index 149f25a..01ca977 100644 --- a/internal/site/sitetest/sitetest.go +++ b/internal/site/sitetest/sitetest.go @@ -287,7 +287,11 @@ func configuredPorts(adapter site.Adapter, descriptor domain.SiteDescriptor, sam } return &portSession{ read: func(ctx context.Context, valid bool) readResult { - _, receipt, err := session.FetchMetafile(ctx, ref(valid), site.DefaultMetafileFetchLimits()) + config, err := port.MetafileFetchConfig() + if err != nil { + return readResult{err: err} + } + _, receipt, err := session.FetchMetafile(ctx, ref(valid), config.DefaultLimits()) return readResult{receipt.StopReason, receipt.Origin, receipt.RouteID, err} }, requests: session.RequestsMade, diff --git a/internal/sitebinding/repository_test.go b/internal/sitebinding/repository_test.go index 44c584a..e690558 100644 --- a/internal/sitebinding/repository_test.go +++ b/internal/sitebinding/repository_test.go @@ -411,3 +411,89 @@ func bindingTestBencode(value any) []byte { encode(value) return output.Bytes() } + +func TestDirectRouteRecordBytesOmitLinkRequests(t *testing.T) { + fixture := newBindingFixture(t, true) + raw, err := EncodeRecord(recordFromObservation(fixture.observed.PublicCopy(), fixture.fetch, fixture.artifact), DefaultLimits()) + if err != nil { + t.Fatal(err) + } + wantLimits := `"fetch_limits":{"max_requests":1,"max_response_bytes":8388608,"max_response_header_bytes":65536}` + wantUsage := `"fetch_usage":{"requests_attempted":1,"automatic_retries":0,"redirects_followed":0,"response_bytes_read":` + strconv.Itoa(len(fixture.raw)) + `,"response_bytes_known":true}}` + if !bytes.Contains(raw, []byte(wantLimits)) || !bytes.Contains(raw, []byte(wantUsage)) || bytes.Contains(raw, []byte("link_request")) { + t.Fatalf("direct-route record bytes drifted: %s", raw) + } + claimed := fixture.fetch + claimed.Limits.MaxLinkRequests = 1 + claimed.Used.LinkRequestsAttempted = 1 + if fixture.observed.MatchesReceipt(claimed) { + t.Fatal("direct-route binding accepted a receipt with a link request") + } +} + +func TestLinkedRouteRecordAccountsForLinkRequests(t *testing.T) { + store := newStore(t) + repository, err := NewRepository(store, DefaultLimits()) + if err != nil { + t.Fatal(err) + } + raw := bindingTestMetafile(true) + _, artifact, imported, err := store.Import(context.Background(), bytes.NewReader(raw), metastore.DefaultLimits()) + if err != nil { + t.Fatal(err) + } + ref := domain.TorrentRef{SiteID: "mteam", RemoteID: "12345"} + start := time.Date(2026, 10, 16, 2, 3, 4, 0, time.UTC) + end := start.Add(time.Second) + fetched, err := site.NewLinkedFetchedMetafile(ref, "https://api2.m-team.cc", "mteam.download_by_token.v1", start, end, 2, raw) + if err != nil { + t.Fatal(err) + } + config, err := site.NewLinkedMetafileFetchConfig("https://api2.m-team.cc", "mteam.download_by_token.v1", 2) + if err != nil { + t.Fatal(err) + } + fetch := site.MetafileFetchReceipt{ + Effect: site.MetafileFetchEffect, Ref: ref, Origin: config.Origin, RouteID: config.RouteID, + ObservedAtStart: start, ObservedAtEnd: end, Complete: true, Limits: config.DefaultLimits(), + Used: site.MetafileFetchUsage{RequestsAttempted: 1, ResponseBytesRead: int64(len(raw)), ResponseBytesKnown: true, LinkRequestsAttempted: 2}, + } + if !fetched.MatchesReceipt(fetch) { + t.Fatal("linked fetch did not match its receipt") + } + observed, err := fetched.BindImported(artifact.MetafileVariantID, imported.BytesConsumed) + if err != nil || !observed.MatchesReceipt(fetch) { + t.Fatalf("linked binding: err=%v", err) + } + for name, mutate := range map[string]func(*site.MetafileFetchReceipt){ + "fewer link requests": func(r *site.MetafileFetchReceipt) { r.Used.LinkRequestsAttempted = 1 }, + "no link requests": func(r *site.MetafileFetchReceipt) { r.Used.LinkRequestsAttempted = 0 }, + "smaller budget": func(r *site.MetafileFetchReceipt) { r.Limits.MaxLinkRequests = 1 }, + "budget too large": func(r *site.MetafileFetchReceipt) { r.Limits.MaxLinkRequests = 3; r.Used.LinkRequestsAttempted = 3 }, + } { + changed := fetch + mutate(&changed) + if fetched.MatchesReceipt(changed) || observed.MatchesReceipt(changed) { + t.Fatalf("%s: receipt accepted", name) + } + } + record := recordFromObservation(observed.PublicCopy(), fetch, artifact) + encoded, err := EncodeRecord(record, DefaultLimits()) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(encoded, []byte(`"max_link_requests":2`)) || !bytes.Contains(encoded, []byte(`"link_requests_attempted":2`)) { + t.Fatalf("linked record lost its link accounting: %s", encoded) + } + if decoded, err := DecodeRecord(bytes.NewReader(encoded), DefaultLimits()); err != nil || decoded != record { + t.Fatalf("DecodeRecord: err=%v", err) + } + invalid := record + invalid.FetchUsage.LinkRequestsAttempted = 3 + if _, err := EncodeRecord(invalid, DefaultLimits()); !errors.Is(err, ErrInvalidBinding) { + t.Fatalf("over-budget record encoded: %v", err) + } + if recordRef, sealed, err := repository.Seal(context.Background(), observed, fetch, artifact); err != nil || recordRef.ID == "" || sealed.WritesPerformed != 1 { + t.Fatalf("Seal: ref=%+v receipt=%+v err=%v", recordRef, sealed, err) + } +} diff --git a/internal/sitebinding/types.go b/internal/sitebinding/types.go index e8ed385..199d84f 100644 --- a/internal/sitebinding/types.go +++ b/internal/sitebinding/types.go @@ -130,6 +130,7 @@ func (record Record) Validate() error { if record.FetchEffect != site.MetafileFetchEffect || !record.FetchComplete || record.FetchStopReason != "" || record.FetchUsage.RequestsAttempted != 1 || record.FetchUsage.AutomaticRetries != 0 || record.FetchUsage.RedirectsFollowed != 0 || !record.FetchUsage.ResponseBytesKnown || + record.FetchUsage.LinkRequestsAttempted < 0 || record.FetchUsage.LinkRequestsAttempted > record.FetchLimits.MaxLinkRequests || record.FetchUsage.ResponseBytesRead != record.ResponseBytes || record.ResponseBytes > record.FetchLimits.MaxResponseBytes { return fmt.Errorf("%w: fetch account is invalid", ErrInvalidBinding)