From f5a49df18d10a089bb8c81623e630617202889a8 Mon Sep 17 00:00:00 2001 From: "jinzheng.architect" Date: Fri, 16 Oct 2026 18:12:34 +0800 Subject: [PATCH] Let reconcile observe API-key sites and use the saved site credential reconcile report read live site detail only with a piped cookie, so --site-ref mteam/ID was refused. It now takes: - --site-live: the credential 'ptctl site login' saved for the site, read after every credential-free gate; with a downloader, stdin then carries only the --password-stdin downloader password - --site-api-key-stdin: a piped API key for API-key sites - site_api_key in the --credential-bundle-stdin bundle, in place of site_cookie (exactly one of the two) A site credential of a method the site does not accept is a usage error before any request. Co-Authored-By: Claude Opus 5.5 --- docs/ADDING_A_SITE.md | 6 +- docs/ARCHITECTURE.md | 12 +- docs/AUTOMATION.md | 9 +- docs/MTEAM_ADAPTER.md | 21 +- docs/THREAT_MODEL.md | 3 +- docs/TJUPT_ADAPTER.md | 6 +- docs/guide/reconcile.md | 23 +- internal/cli/reconcile.go | 60 +++- internal/cli/reconcile_credentials.go | 17 +- .../cli/reconcile_site_credentials_test.go | 274 ++++++++++++++++++ 10 files changed, 392 insertions(+), 39 deletions(-) create mode 100644 internal/cli/reconcile_site_credentials_test.go diff --git a/docs/ADDING_A_SITE.md b/docs/ADDING_A_SITE.md index d15f73e..7e00cd3 100644 --- a/docs/ADDING_A_SITE.md +++ b/docs/ADDING_A_SITE.md @@ -262,7 +262,7 @@ 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, 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. | +| M-Team | Status, account, search, detail, the signed-link metafile download, and live-site reconciliation are implemented in `internal/site/mteam` over the JSON API with an API key. | Bonus commands: the open gaps below. | ## Gaps for API-token sites @@ -274,8 +274,8 @@ 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` 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`. | +| 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`; `reconcile` takes `--site-api-key-stdin`, `--site-live`, and the bundle's `site_api_key` | Bonus commands still take cookies only. | +| The CLI gated on cookies | Partly done | `siteRead` in `internal/cli/site.go`, `site detail`, `site metafile fetch`, and `reconcile` check the method the caller chose | Two `SupportsAuth(domain.AuthMethodCookieHeader)` checks remain, in `site_bonus.go` and `site_bonus_exchange.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. | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ccdf1f0..0fd9545 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -280,11 +280,13 @@ requests and never selected by ref, time, or enumeration. A valid historical binding does not upgrade any storage/client/path axis and does not change the downloader raw-metafile relation; a mismatch conflicts, while unavailable or corrupt authority prevents overall consistency. A bare `--site-ref` remains a -non-gating declaration. Explicit `--site-cookie-stdin` makes the live detail -axis gating: failure is incomplete, while success adds only a current site -claim. With a downloader in the same invocation, one strict bounded -`--credential-bundle-stdin` object supplies both secrets so stdin is consumed -exactly once; all credential-free gates run first. +non-gating declaration. Explicit `--site-live`, `--site-cookie-stdin`, or +`--site-api-key-stdin` makes the live detail axis gating: failure is +incomplete, while success adds only a current site claim. `--site-live` reads +the credential `site login` saved, so with a downloader stdin carries only the +downloader password. Otherwise, with a downloader in the same invocation, one +strict bounded `--credential-bundle-stdin` object supplies both secrets so +stdin is consumed exactly once; all credential-free gates run first. qBittorrent's generic `hash` is an opaque job key. The adapter derives typed claims only from strictly bounded magnet `xt` values: BTIH is 20 bytes and diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 61f7f72..3a69988 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -101,7 +101,9 @@ Every later `site` command for that site, including `site metafile fetch` and `site bonus exchange submit`, then uses the saved credential without a flag. An agent saves one without a terminal by piping it, `site login --cookie-stdin SITE` or `site login --api-key-stdin SITE`, and -`ptctl site logout SITE` deletes it. An explicit stdin flag below always takes +`ptctl site logout SITE` deletes it. `reconcile report` uses the saved +credential when given `--site-live`, and then reads only the downloader +password from stdin. An explicit stdin flag below always takes precedence over the saved credential, and a saved credential never stands in for an acknowledgement flag. @@ -110,8 +112,9 @@ for an acknowledgement flag. | `--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":"..."}` | +| `--site-cookie-stdin` | `reconcile report` with a live site observation and no downloader, on a cookie site (TJUPT) | The complete `Cookie` header value | +| `--site-api-key-stdin` | `reconcile report` with a live site observation and no downloader, on an API-key site (M-Team) | The site-issued API key | +| `--credential-bundle-stdin` | `reconcile report` with both a live site observation and a downloader | `{"schema":"ptctl.credentials/v1","site_cookie":"...","downloader_password":"..."}`, or `site_api_key` in place of `site_cookie` | | `--credential-bundle-stdin` | `site bonus exchange submit` for sites that confirm with the account password (TJUPT) | `{"schema":"ptctl.credentials/v1","site_cookie":"...","site_password":"..."}` | | `--credential-bundle-stdin` | `site login` | `{"schema":"ptctl.credentials/v1","site_username":"...","site_password":"...","site_totp":"123456"}`; `site_totp` is optional | | `--cookie-stdin`, `--api-key-stdin` | `site login` | The credential to save; one status read checks it first and nothing is saved when it fails | diff --git a/docs/MTEAM_ADAPTER.md b/docs/MTEAM_ADAPTER.md index 246a014..d50a142 100644 --- a/docs/MTEAM_ADAPTER.md +++ b/docs/MTEAM_ADAPTER.md @@ -138,8 +138,8 @@ requested ID. `DOWNLOAD REFERENCE` is always `false`, because the API answer has no download link to observe. An ID with no visible torrent stops as `not_found`; the API reports it as code `1` with a fixed message, and only that exact pair is read as not found, because the API uses code `1` for other -refusals too. Live-site reconciliation still reads site detail only with a -cookie, so it does not support M-Team yet. +refusals too. Live-site reconciliation reads the same detail, as described +in [Reconciliation](#reconciliation). **Times.** The API returns times without a zone, such as `2026-10-14 09:30:00`. ptctl reads them as UTC+8, the site's time zone, and reports them in @@ -248,13 +248,20 @@ private store instead. The file contains your passkey, so keep it private: ptctl metafile store import --store "$PTCTL_STORE" release.torrent ``` -## Not supported yet +## Reconciliation + +`reconcile report --site-ref mteam/ID --site-live` adds the live detail read +to a reconciliation report with the saved API key, and reads nothing from +stdin. With a downloader in the same command, add `--password-stdin` and pipe +only the downloader password. A script that keeps the key itself pipes it with +`--site-api-key-stdin`, or, with a downloader, uses `--credential-bundle-stdin` +with `site_api_key` in place of `site_cookie`. The read is the one +`/api/torrent/detail` request above; it never asks for a signed download link. +See [Reconciliation](guide/reconcile.md). -**Reconciliation.** `reconcile` reads live site detail with a cookie only, so -`--site-ref mteam/ID` is refused. `site detail` works on its own. +## Not supported yet -**Everything else.** Bonus exchange, RSS, seeding lists, and messages are not -implemented. +Bonus exchange, RSS, seeding lists, and messages are not implemented. ## Fixtures diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 5baab1e..bfe6adb 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -160,7 +160,8 @@ user config directory, a plaintext file of mode `0600` in a `0700` directory, written through an owner-only temporary file and renamed into place. Every `site` command for that site, including metafile fetch and bonus exchange submit, reads it when no stdin credential flag is given; an explicit flag -always wins. This is a deliberate trade: anyone who can read the file as the +always wins. `reconcile report` reads it only with an explicit `--site-live`, +after every credential-free gate has passed. This is a deliberate trade: anyone who can read the file as the user, or any process the user runs, can act as the user on that site until the session expires or the key is revoked. An M-Team API key does not expire on its own, so its file is worth more than a TJUPT session cookie. diff --git a/docs/TJUPT_ADAPTER.md b/docs/TJUPT_ADAPTER.md index 7977c15..653a2f1 100644 --- a/docs/TJUPT_ADAPTER.md +++ b/docs/TJUPT_ADAPTER.md @@ -370,7 +370,7 @@ may include promotion decoration; names, peer counts, size, snatches, and links are site claims. It is not a metafile identity, proof of the site's current private variant, a site signature, or storage-content proof, and it is not persisted. The typed port returns opaque process-local authority. An explicitly -requested `reconcile report --site-ref tjupt/ID --site-cookie-stdin` may consume +requested `reconcile report --site-ref tjupt/ID --site-live` (or `--site-cookie-stdin`) may consume that authority in the same invocation, but only to record that the selected remote-ID page was observed; JSON replay cannot recreate it and it never proves which private `.torrent` variant the site currently serves. @@ -464,7 +464,9 @@ only and cannot upgrade incomplete storage/client/path axes or make the downloader's raw private metafile observable. When live site detail and a read-only downloader are requested together, -reconciliation requires `--credential-bundle-stdin` and accepts exactly: +`--site-live --password-stdin` uses the saved cookie and pipes only the +downloader password. Without a saved cookie, reconciliation requires +`--credential-bundle-stdin` and accepts exactly: ```json {"schema":"ptctl.credentials/v1","site_cookie":"SID=...","downloader_password":"..."} diff --git a/docs/guide/reconcile.md b/docs/guide/reconcile.md index e9eb7e8..e7f5dcf 100644 --- a/docs/guide/reconcile.md +++ b/docs/guide/reconcile.md @@ -338,17 +338,28 @@ metafile binding. Neither read adapter exposes the raw private metafile through its ledger, so `metafile_variant_relation` remains `unobservable` even when typed infohashes agree. -To observe that remote ID live without a downloader, add -`--site-cookie-stdin`. To observe both the site and a downloader in one command, -use `--credential-bundle-stdin` instead of the two single-secret flags and pipe -one bounded strict JSON object: +To observe that remote ID live without a downloader, add `--site-live`. It +uses the credential `ptctl site login SITE` saved for the site, so nothing is +read from stdin; this is the simplest form, and the one M-Team uses with its +saved API key. A script that keeps the secret itself pipes it instead, with +`--site-cookie-stdin` for a cookie site (TJUPT) or `--site-api-key-stdin` for +an API-key site (M-Team). + +To observe both the site and a downloader in one command, add `--site-live` +next to `--password-stdin`: the saved site credential leaves stdin to the +downloader password. Without a saved credential, use +`--credential-bundle-stdin` instead of the two single-secret flags and pipe +one bounded strict JSON object with either `site_cookie` or `site_api_key`: ```json {"schema":"ptctl.credentials/v1","site_cookie":"SID=...","downloader_password":"..."} +{"schema":"ptctl.credentials/v1","site_api_key":"...","downloader_password":"..."} ``` -Unknown, duplicate, missing, trailing, oversized, invalid-UTF-8, and unpaired -surrogate input is rejected. All adapter capability/origin/ref, metafile, +The four site sources are mutually exclusive. A bundle with both site fields +or neither, and unknown, duplicate, missing, trailing, oversized, +invalid-UTF-8, and unpaired surrogate input, is rejected. A site credential +of a method the site does not accept is a usage error before any request. All adapter capability/origin/ref, metafile, store, storage-profile, mapping, endpoint, and budget checks finish before this stdin is read. The site detail request runs first. Its opaque same-invocation authority adds only a current remote-ID site claim to `site_metafile`; the diff --git a/internal/cli/reconcile.go b/internal/cli/reconcile.go index 9a891df..f742c24 100644 --- a/internal/cli/reconcile.go +++ b/internal/cli/reconcile.go @@ -72,7 +72,7 @@ func (a *app) reconcileReportMode(args []string, refreshIndex bool) error { fmt.Fprintln(fs.Output(), "The report can observe one live site detail page before bracketing optional downloader reads around an explicitly selected exact-layout source or bounded storage discovery. It performs zero writes. Exact --source proves only that selected layout, not filesystem-wide uniqueness. The materialize selector requires one explicit operation and reviewed plan ID, then proves its current exact final namespace before immediately repeating ordinary exact-source verification; these are sequential non-atomic observations. Optional adoption selectors read one canonical terminal client-adoption journal or retained tombstone—whether created by stopped add or observation-only existing-job adoption—and bind its historical completion to the already requested current exact typed job claim without another client request; downloader job incarnation remains unobservable. Optional activation selectors similarly bind one canonical terminal activation journal to the current bracket and, when adoption is also selected, must share that adoption lineage. Optional stop selectors require that activation lineage, read one canonical attributed terminal stop journal or complete retention tombstone before credentials, and bind it to a current exact stopped job in the same bracket without another request; an unknown stop response remains causality-unproven. Optional removal selectors instead require activation, read one canonical terminal keep-data removal journal or retained tombstone, and bind its attributed completion to typed job absence in the existing two-read client bracket. Optional retirement selectors read one canonical terminal source-retirement journal and twice reobserve its exact retired names absent under explicit source roots. Optional parent-cleanup selectors additionally require that retirement proof, read one canonical terminal cleanup journal, and twice reobserve the exact removed parent names absent; a retained cleanup tombstone is historical only and cannot restore path authority. Adoption and removal are mutually exclusive because their current-job predicates conflict; stop and removal are mutually exclusive because their predicates require current presence versus absence; removal and source-retirement terminal modes are also mutually exclusive in this slice. A live detail page is only a current site claim for the remote ID; it cannot expose or prove the private metafile variant, and host/client path comparison remains lexical only.") fmt.Fprintln(fs.Output(), "With --client-file-layout=auto, an eligible multi-file torrent adds at most two bounded file-list reads for one unique exact downloader job. The reads bracket storage proof, share the command timeout, and are never retried.") fmt.Fprintln(fs.Output(), "") - fmt.Fprintln(fs.Output(), "Client-only reads use --driver qbittorrent|transmission --url URL --username USER --password-stdin. Exact stopped adoption and reviewed existing-job recheck/start support both built-in drivers; Transmission mutation authority is v1-only. Site-detail-only reads use --site-ref SITE/REMOTE_ID --site-cookie-stdin. When both are requested, replace both secret flags with --credential-bundle-stdin and pipe strict JSON containing schema, site_cookie, and downloader_password.") + fmt.Fprintln(fs.Output(), "Client-only reads use --driver qbittorrent|transmission --url URL --username USER --password-stdin. Exact stopped adoption and reviewed existing-job recheck/start support both built-in drivers; Transmission mutation authority is v1-only. Site-detail-only reads use --site-ref SITE/REMOTE_ID with --site-live, which uses the credential 'ptctl site login' saved for the site, or with --site-cookie-stdin or --site-api-key-stdin. When both are requested, add --site-live to the client group, or replace both secret flags with --credential-bundle-stdin and pipe strict JSON containing schema, site_cookie or site_api_key, and downloader_password.") fmt.Fprintln(fs.Output(), "") fmt.Fprintln(fs.Output(), "Flags:") fs.PrintDefaults() @@ -113,7 +113,9 @@ func (a *app) reconcileReportMode(args []string, refreshIndex bool) error { username := fs.String("username", "", "downloader username; part of the optional client group") passwordStdin := fs.Bool("password-stdin", false, "read downloader password from stdin; part of the optional client group") siteCookieStdin := fs.Bool("site-cookie-stdin", false, "read a site Cookie header from stdin and observe --site-ref live") - credentialBundleStdin := fs.Bool("credential-bundle-stdin", false, "read strict JSON containing site_cookie and downloader_password when live site and client reads are both requested") + siteAPIKeyStdin := fs.Bool("site-api-key-stdin", false, "read a site API key from stdin and observe --site-ref live") + siteLive := fs.Bool("site-live", false, "observe --site-ref live with the credential 'ptctl site login' saved for the site") + credentialBundleStdin := fs.Bool("credential-bundle-stdin", false, "read strict JSON containing site_cookie or site_api_key, and downloader_password, when live site and client reads are both requested") clientFileLayout := fs.String("client-file-layout", "auto", "multi-file downloader layout reads: auto or off; requires the client group when explicit") clientFileDefaults := downloader.DefaultJobFileLedgerLimits() maxClientFiles := fs.Int("max-client-files", clientFileDefaults.MaxFiles, "maximum downloader files read for the one exact job; requires the client group when explicit") @@ -382,13 +384,19 @@ func (a *app) reconcileReportMode(args []string, refreshIndex bool) error { for _, name := range append(append([]string{}, clientConnectionFlagNames...), "password-stdin", "credential-bundle-stdin") { clientRequested = clientRequested || explicit[name] } - siteDetailRequested := explicit["site-cookie-stdin"] || explicit["credential-bundle-stdin"] - if explicit["password-stdin"] && !*passwordStdin || explicit["site-cookie-stdin"] && !*siteCookieStdin || explicit["credential-bundle-stdin"] && !*credentialBundleStdin { + siteDetailRequested := explicit["site-cookie-stdin"] || explicit["site-api-key-stdin"] || explicit["site-live"] || explicit["credential-bundle-stdin"] + if explicit["password-stdin"] && !*passwordStdin || explicit["site-cookie-stdin"] && !*siteCookieStdin || explicit["site-api-key-stdin"] && !*siteAPIKeyStdin || explicit["credential-bundle-stdin"] && !*credentialBundleStdin { return usageError("secret stdin flags cannot be explicitly disabled") } + if explicit["site-live"] && !*siteLive { + return usageError("--site-live cannot be explicitly disabled") + } if explicit["credential-bundle-stdin"] && (explicit["password-stdin"] || explicit["site-cookie-stdin"]) { return usageError("--credential-bundle-stdin is mutually exclusive with --password-stdin and --site-cookie-stdin") } + if countTrue(explicit["site-cookie-stdin"], explicit["site-api-key-stdin"], explicit["site-live"], explicit["credential-bundle-stdin"]) > 1 { + return usageError("--site-cookie-stdin, --site-api-key-stdin, --site-live, and --credential-bundle-stdin are mutually exclusive") + } if clientRequested { missing := make([]string, 0, len(clientConnectionFlagNames)) for _, name := range clientConnectionFlagNames { @@ -406,15 +414,18 @@ func (a *app) reconcileReportMode(args []string, refreshIndex bool) error { return usageError("the optional client group requires non-empty --url and --username") } if siteDetailRequested { - if !explicit["credential-bundle-stdin"] { - return usageError("combined live site and downloader reads require --credential-bundle-stdin") + if !explicit["credential-bundle-stdin"] && !explicit["site-live"] { + return usageError("combined live site and downloader reads require --credential-bundle-stdin, or --site-live with --password-stdin") + } + if explicit["site-live"] && !explicit["password-stdin"] { + return usageError("combined --site-live and downloader reads require --password-stdin") } } else if !explicit["password-stdin"] { return usageError("client-only reconciliation requires --password-stdin") } } - if siteDetailRequested && !clientRequested && !explicit["site-cookie-stdin"] { - return usageError("site-detail-only reconciliation requires --site-cookie-stdin") + if siteDetailRequested && !clientRequested && !explicit["site-cookie-stdin"] && !explicit["site-api-key-stdin"] && !explicit["site-live"] { + return usageError("site-detail-only reconciliation requires --site-cookie-stdin, --site-api-key-stdin, or --site-live") } clientFileFlagNames := []string{"client-file-layout", "max-client-files", "max-client-file-path-bytes", "max-client-file-response-bytes"} for _, name := range clientFileFlagNames { @@ -545,15 +556,31 @@ func (a *app) reconcileReportMode(args []string, refreshIndex bool) error { } var siteDetailReader site.TorrentDetailReader var siteDetailConfig site.TorrentDetailConfig + var siteDetailDescriptor domain.SiteDescriptor + var siteSource siteCredentialSource if siteDetailRequested { adapter, ok := a.registry.Get(siteRef.SiteID) if !ok { return usageError("live site detail adapter is unavailable") } descriptor := adapter.Descriptor() - if !descriptor.Supports(domain.CapabilityDetail) || !descriptor.SupportsAuth(domain.AuthMethodCookieHeader) { + siteDetailDescriptor = descriptor + // The bundle names its credential kind inside stdin, so it needs only + // one kind the site accepts here and the exact kind after the read. + bundleAuth := descriptor.SupportsAuth(domain.AuthMethodCookieHeader) || descriptor.SupportsAuth(domain.AuthMethodAPIKeyHeader) + if !descriptor.Supports(domain.CapabilityDetail) || explicit["site-cookie-stdin"] && !descriptor.SupportsAuth(domain.AuthMethodCookieHeader) || explicit["credential-bundle-stdin"] && !bundleAuth { return usageError("site %q does not support authenticated torrent detail reads", descriptor.ID) } + siteSource = siteCredentialSource{method: domain.AuthMethodCookieHeader} + switch { + case explicit["site-api-key-stdin"]: + siteSource.method = domain.AuthMethodAPIKeyHeader + case explicit["site-live"]: + siteSource = siteCredentialSource{method: defaultSiteAuthMethod(descriptor), saved: true} + } + if !explicit["credential-bundle-stdin"] && !descriptor.SupportsAuth(siteSource.method) { + return usageError("site %q does not support %s authentication", descriptor.ID, siteSource.method) + } siteDetailReader, ok = adapter.(site.TorrentDetailReader) if !ok { return usageError("site %q does not implement its declared torrent detail capability", descriptor.ID) @@ -565,6 +592,9 @@ func (a *app) reconcileReportMode(args []string, refreshIndex bool) error { if err := siteDetailReader.ValidateTorrentDetailRef(*siteRef); err != nil { return usageError("live site detail reference is invalid") } + if err := siteSource.locateSaved(descriptor.ID); err != nil { + return err + } } meta, err := loadMetafileInput(context.Background(), input) if err != nil { @@ -908,10 +938,20 @@ func (a *app) reconcileReportMode(args []string, refreshIndex bool) error { var clientCredential downloader.Credential if prerequisiteGatesPassed { switch { + case siteDetailRequested && clientRequested && siteSource.saved: + // The saved site credential leaves stdin to the downloader password. + if siteCredential, err = a.readSiteCredential(siteSource, nil); err == nil { + clientCredential, err = readDownloaderCredential(a.stdin, *username) + } case siteDetailRequested && clientRequested: siteCredential, clientCredential, err = readReconciliationCredentialBundle(a.stdin, *username) + if err == nil && !siteDetailDescriptor.SupportsAuth(siteCredential.Method()) { + err = usageError("site %q does not support %s authentication", siteDetailDescriptor.ID, siteCredential.Method()) + } + case siteDetailRequested && siteSource.method == domain.AuthMethodAPIKeyHeader: + siteCredential, err = a.readSiteCredential(siteSource, readAPIKeyCredential) case siteDetailRequested: - siteCredential, err = readCredential(a.stdin) + siteCredential, err = a.readSiteCredential(siteSource, readCredential) case clientRequested: clientCredential, err = readDownloaderCredential(a.stdin, *username) } diff --git a/internal/cli/reconcile_credentials.go b/internal/cli/reconcile_credentials.go index c8495ea..af12bef 100644 --- a/internal/cli/reconcile_credentials.go +++ b/internal/cli/reconcile_credentials.go @@ -34,7 +34,17 @@ func readReconciliationCredentialBundle(reader io.Reader, username string) (site if values["schema"] != reconciliationCredentialSchema { return site.Credential{}, downloader.Credential{}, fmt.Errorf("reconciliation credential bundle schema is unsupported") } - siteCredential, err := site.NewCookieCredential(values["site_cookie"]) + cookie, hasCookie := values["site_cookie"] + apiKey, hasAPIKey := values["site_api_key"] + if hasCookie == hasAPIKey { + return site.Credential{}, downloader.Credential{}, fmt.Errorf("reconciliation credential bundle is invalid") + } + var siteCredential site.Credential + if hasCookie { + siteCredential, err = site.NewCookieCredential(cookie) + } else { + siteCredential, err = canonicalAPIKeyCredential([]byte(apiKey)) + } if err != nil { return site.Credential{}, downloader.Credential{}, fmt.Errorf("reconciliation site credential is invalid") } @@ -77,8 +87,11 @@ func readBonusExchangeCredentialBundle(reader io.Reader) (site.Credential, site. return siteCredential, password, nil } +// decodeReconciliationCredentialBundle decodes the bundle of a live site and +// downloader reconciliation. The site credential is site_cookie or +// site_api_key; the caller requires exactly one. func decodeReconciliationCredentialBundle(raw []byte) (map[string]string, error) { - return decodeCredentialBundle(raw, "schema", "site_cookie", "downloader_password") + return decodeCredentialBundleOptional(raw, []string{"schema", "downloader_password"}, []string{"site_cookie", "site_api_key"}) } // decodeCredentialBundle strictly decodes one JSON object whose keys are diff --git a/internal/cli/reconcile_site_credentials_test.go b/internal/cli/reconcile_site_credentials_test.go new file mode 100644 index 0000000..e6287fb --- /dev/null +++ b/internal/cli/reconcile_site_credentials_test.go @@ -0,0 +1,274 @@ +package cli + +import ( + "bytes" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "runtime" + "strings" + "sync/atomic" + "testing" + + "github.com/tonycoder-hub/ptctl/internal/domain" + "github.com/tonycoder-hub/ptctl/internal/reconcile" + "github.com/tonycoder-hub/ptctl/internal/site" +) + +const reconcileDownloaderPasswordCanary = "RECONCILE-DOWNLOADER-PASSWORD-CANARY" + +// fakeReconcileQBittorrent serves one finished torrent for the fixture of +// writeReconciliationFixture and counts logins. +func fakeReconcileQBittorrent(t *testing.T, infoHash string, logins *atomic.Int32) *httptest.Server { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v2/auth/login": + logins.Add(1) + if err := r.ParseForm(); err != nil || r.Form.Get("username") != "user" || r.Form.Get("password") != reconcileDownloaderPasswordCanary { + t.Errorf("unexpected downloader credential") + } + http.SetCookie(w, &http.Cookie{Name: "SID", Value: "ok", Path: "/"}) + _, _ = w.Write([]byte("Ok.")) + case "/api/v2/torrents/info": + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode([]map[string]any{{ + "hash": "opaque", "magnet_uri": "magnet:?xt=urn:btih:" + infoHash, + "name": "PTCTL-CLIENT-PATH-CANARY.bin", "size": int64(len("content")), "progress": 1.0, + "state": "uploading", "save_path": "/downloads", "content_path": "/downloads/PTCTL-CLIENT-PATH-CANARY.bin", + "downloaded": int64(len("content")), "uploaded": int64(10), + }}) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(server.Close) + return server +} + +func decodeReconcileReport(t *testing.T, encoded []byte) reconcile.Report { + t.Helper() + var response struct { + Data reconcile.Report `json:"data"` + } + if err := json.Unmarshal(encoded, &response); err != nil { + t.Fatalf("decode report: %v stdout=%s", err, encoded) + } + return response.Data +} + +func TestReconcileObservesAPIKeySiteFromStdin(t *testing.T) { + torrentPath, searchRoot, _ := writeReconciliationFixture(t) + adapter := successfulFakeTorrentDetail(t) + adapter.authMethod = domain.AuthMethodAPIKeyHeader + var out bytes.Buffer + a := &app{stdin: strings.NewReader(apiKeyCanary + "\n"), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + if err := a.reconcileReport([]string{ + "--torrent", torrentPath, "--search-root", searchRoot, "--site-ref", "fakept/42", "--site-api-key-stdin", "--output", "json", + }); err != nil { + t.Fatalf("API-key site-only reconciliation: %v stdout=%s", err, out.String()) + } + report := decodeReconcileReport(t, out.Bytes()) + if report.Ledgers.Site.Detail.Status != "observed_current_ref" || report.Ledgers.Downloader.Status != "not_requested" || + adapter.opened != 1 || adapter.credential != apiKeyCanary { + t.Fatalf("API key did not reach the site detail read: %s", out.String()) + } + assertJSONStringsExclude(t, out.Bytes(), apiKeyCanary, torrentPath, searchRoot) +} + +func TestReconcileSiteLiveUsesSavedCredentialWithoutReadingStdin(t *testing.T) { + useTempConfigDir(t) + torrentPath, searchRoot, _ := writeReconciliationFixture(t) + for _, test := range []struct { + name string + method domain.AuthMethod + content string + want string + }{ + {name: "cookie", method: domain.AuthMethodCookieHeader, content: savedCookieCanary + "\n", want: savedCookieCanary}, + {name: "api key", method: domain.AuthMethodAPIKeyHeader, content: savedAPIKeyCanary + "\n", want: savedAPIKeyCanary}, + } { + t.Run(test.name, func(t *testing.T) { + writeSavedCredential(t, "fakept", test.method, test.content) + adapter := successfulFakeTorrentDetail(t) + adapter.authMethod = test.method + reader := &trackingReader{} + var out bytes.Buffer + a := &app{stdin: reader, stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + if err := a.reconcileReport([]string{ + "--torrent", torrentPath, "--search-root", searchRoot, "--site-ref", "fakept/42", "--site-live", "--output", "json", + }); err != nil { + t.Fatalf("saved-credential reconciliation: %v stdout=%s", err, out.String()) + } + report := decodeReconcileReport(t, out.Bytes()) + if reader.read || report.Ledgers.Site.Detail.Status != "observed_current_ref" || adapter.opened != 1 || adapter.credential != test.want { + t.Fatalf("saved credential was not used alone: read=%t stdout=%s", reader.read, out.String()) + } + assertJSONStringsExclude(t, out.Bytes(), test.want, torrentPath, searchRoot) + }) + } +} + +func TestReconcileSiteLiveLeavesStdinToTheDownloaderPassword(t *testing.T) { + useTempConfigDir(t) + writeSavedCredential(t, "fakept", domain.AuthMethodAPIKeyHeader, savedAPIKeyCanary) + torrentPath, searchRoot, meta := writeReconciliationFixture(t) + var logins atomic.Int32 + server := fakeReconcileQBittorrent(t, meta.InfoHashV1, &logins) + adapter := successfulFakeTorrentDetail(t) + adapter.authMethod = domain.AuthMethodAPIKeyHeader + var out bytes.Buffer + a := &app{stdin: strings.NewReader(reconcileDownloaderPasswordCanary + "\n"), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + if err := a.reconcileReport([]string{ + "--torrent", torrentPath, "--search-root", searchRoot, "--site-ref", "fakept/42", "--site-live", + "--driver", "qbittorrent", "--url", server.URL, "--username", "user", "--password-stdin", + "--host-root", searchRoot, "--client-root", "/downloads", "--client-style", "posix", "--output", "json", + }); err != nil { + t.Fatalf("saved site credential with downloader: %v stdout=%s", err, out.String()) + } + report := decodeReconcileReport(t, out.Bytes()) + if report.Outcome != "consistent" || report.Ledgers.Site.Detail.Status != "observed_current_ref" || + adapter.credential != savedAPIKeyCanary || logins.Load() != 1 { + t.Fatalf("saved site credential and downloader password were not kept apart: %s", out.String()) + } + assertJSONStringsExclude(t, out.Bytes(), savedAPIKeyCanary, reconcileDownloaderPasswordCanary, server.URL, torrentPath, searchRoot) +} + +func TestReconcileCredentialBundleCarriesSiteAPIKey(t *testing.T) { + torrentPath, searchRoot, meta := writeReconciliationFixture(t) + var logins atomic.Int32 + server := fakeReconcileQBittorrent(t, meta.InfoHashV1, &logins) + args := []string{ + "--torrent", torrentPath, "--search-root", searchRoot, "--site-ref", "fakept/42", "--credential-bundle-stdin", + "--driver", "qbittorrent", "--url", server.URL, "--username", "user", + "--host-root", searchRoot, "--client-root", "/downloads", "--client-style", "posix", "--output", "json", + } + bundle := func(t *testing.T, fields map[string]string) []byte { + t.Helper() + values := map[string]string{"schema": reconciliationCredentialSchema, "downloader_password": reconcileDownloaderPasswordCanary} + for key, value := range fields { + values[key] = value + } + encoded, err := json.Marshal(values) + if err != nil { + t.Fatal(err) + } + return encoded + } + + adapter := successfulFakeTorrentDetail(t) + adapter.authMethod = domain.AuthMethodAPIKeyHeader + var out bytes.Buffer + a := &app{stdin: bytes.NewReader(bundle(t, map[string]string{"site_api_key": apiKeyCanary})), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + if err := a.reconcileReport(args); err != nil { + t.Fatalf("API-key bundle: %v stdout=%s", err, out.String()) + } + if report := decodeReconcileReport(t, out.Bytes()); report.Outcome != "consistent" || adapter.credential != apiKeyCanary || logins.Load() != 1 { + t.Fatalf("bundled API key was not used: %s", out.String()) + } + assertJSONStringsExclude(t, out.Bytes(), apiKeyCanary, reconcileDownloaderPasswordCanary) + + for _, test := range []struct { + name string + fields map[string]string + want string + }{ + {name: "both site credentials", fields: map[string]string{"site_cookie": "sid=BUNDLE-COOKIE-CANARY", "site_api_key": apiKeyCanary}, want: "reconciliation credential bundle is invalid"}, + {name: "no site credential", fields: nil, want: "reconciliation credential bundle is invalid"}, + {name: "invalid API key", fields: map[string]string{"site_api_key": "bad key"}, want: "reconciliation site credential is invalid"}, + {name: "cookie for an API-key site", fields: map[string]string{"site_cookie": "sid=BUNDLE-COOKIE-CANARY"}, want: `site "fakept" does not support cookie_header authentication`}, + } { + t.Run(test.name, func(t *testing.T) { + adapter := successfulFakeTorrentDetail(t) + adapter.authMethod = domain.AuthMethodAPIKeyHeader + before := logins.Load() + var out bytes.Buffer + a := &app{stdin: bytes.NewReader(bundle(t, test.fields)), stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + err := a.reconcileReport(args) + if err == nil || err.Error() != test.want || out.Len() != 0 || adapter.opened != 0 || logins.Load() != before { + t.Fatalf("bundle was not refused before any request: err=%v opened=%d stdout=%q", err, adapter.opened, out.String()) + } + for _, secret := range []string{apiKeyCanary, "BUNDLE-COOKIE-CANARY", reconcileDownloaderPasswordCanary} { + if strings.Contains(err.Error(), secret) { + t.Fatalf("error disclosed a secret: %v", err) + } + } + }) + } +} + +func TestReconcileSiteCredentialModesRejectBeforeStdin(t *testing.T) { + torrentPath, searchRoot, _ := writeReconciliationFixture(t) + base := []string{"--torrent", torrentPath, "--search-root", searchRoot, "--site-ref", "fakept/42", "--output", "json"} + client := []string{"--driver", "qbittorrent", "--url", "http://127.0.0.1:1", "--username", "user"} + with := func(parts ...[]string) []string { + args := append([]string{}, base...) + for _, part := range parts { + args = append(args, part...) + } + return args + } + for _, test := range []struct { + name string + method domain.AuthMethod + saved bool + args []string + want string + }{ + {name: "two site sources", args: with([]string{"--site-cookie-stdin", "--site-api-key-stdin"}), + want: "--site-cookie-stdin, --site-api-key-stdin, --site-live, and --credential-bundle-stdin are mutually exclusive"}, + {name: "site live and bundle", saved: true, args: with([]string{"--site-live", "--credential-bundle-stdin"}, client), + want: "--site-cookie-stdin, --site-api-key-stdin, --site-live, and --credential-bundle-stdin are mutually exclusive"}, + {name: "site live disabled", args: with([]string{"--site-live=false"}), want: "--site-live cannot be explicitly disabled"}, + {name: "API key on a cookie site", args: with([]string{"--site-api-key-stdin"}), want: `site "fakept" does not support api_key_header authentication`}, + {name: "cookie on an API-key site", method: domain.AuthMethodAPIKeyHeader, args: with([]string{"--site-cookie-stdin"}), + want: `site "fakept" does not support authenticated torrent detail reads`}, + {name: "site live without a saved credential", args: with([]string{"--site-live"}), + want: `no saved session cookie for site "fakept"; run 'ptctl site login fakept' first, or pipe one with --cookie-stdin`}, + {name: "site live with a client but no password flag", saved: true, args: with([]string{"--site-live"}, client), + want: "combined --site-live and downloader reads require --password-stdin"}, + {name: "stdin site credential with a client", args: with([]string{"--site-api-key-stdin", "--password-stdin"}, client), + want: "combined live site and downloader reads require --credential-bundle-stdin, or --site-live with --password-stdin"}, + } { + t.Run(test.name, func(t *testing.T) { + useTempConfigDir(t) + adapter := successfulFakeTorrentDetail(t) + adapter.authMethod = test.method + if test.saved { + writeSavedCredential(t, "fakept", adapter.method(), savedCookieCanary) + } + reader := &trackingReader{} + var out bytes.Buffer + a := &app{stdin: reader, stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + err := a.reconcileReport(test.args) + var usage *usageErr + if !errors.As(err, &usage) || err.Error() != test.want || reader.read || out.Len() != 0 || adapter.opened != 0 { + t.Fatalf("err=%v read=%t opened=%d stdout=%q", err, reader.read, adapter.opened, out.String()) + } + }) + } +} + +func TestReconcileSiteLiveRefusesAnUnsafeSavedCredential(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Unix permission bits") + } + useTempConfigDir(t) + path := writeSavedCredential(t, "fakept", domain.AuthMethodCookieHeader, savedCookieCanary) + if err := os.Chmod(path, 0o644); err != nil { + t.Fatal(err) + } + torrentPath, searchRoot, _ := writeReconciliationFixture(t) + adapter := successfulFakeTorrentDetail(t) + var out bytes.Buffer + a := &app{stdin: &trackingReader{}, stdout: &out, stderr: ioDiscard{}, registry: site.NewRegistry(adapter)} + err := a.reconcileReport([]string{ + "--torrent", torrentPath, "--search-root", searchRoot, "--site-ref", "fakept/42", "--site-live", "--output", "json", + }) + if err == nil || !strings.Contains(err.Error(), "because other users can access it") || strings.Contains(err.Error(), savedCookieCanary) || + out.Len() != 0 || adapter.opened != 0 { + t.Fatalf("unsafe saved credential was not refused: err=%v opened=%d stdout=%q", err, adapter.opened, out.String()) + } +}