diff --git a/CHANGELOG.md b/CHANGELOG.md index 406b1dd..a425f6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,76 @@ All notable changes to PostParse are documented here. The format follows ## [Unreleased] +### Added + +- **`postparse check instagram --import-session`**: imports the session of + the user's logged-in browser without a password. The `sessionid` cookie is + read from a hidden terminal prompt (`csrftoken` optional, generated when + empty; a `:`-decoded copy is normalized to `%3A`), verified with exactly one + request (with `feed_api = "web"` the first saved-feed page, see below) and + saved only when Instagram confirms the session (`InstagramCollector.import_session`). Needs an + interactive terminal; cannot be combined with `--login`. The value is never + shown or logged. Messages that tell how to log in now recommend it first and + `--login` as the alternative. See docs/operations.md. + +### Changed + +- **Session check over the web API, with the saved feed's first page**: with + `instagram.feed_api = "web"` (the default) the session check requests the + first page of the saved feed (`https://www.instagram.com/api/v1/feed/saved/posts/`), + exactly as the feed walk does and as the Instagram web app does when the + saved page is opened (same web client and headers, saved page as + `Referer`, single attempt), instead of `i.instagram.com` with instaloader's + iPad headers: one client identity per run, and a browser session is never + sent with iPad headers to `i.instagram.com`. An intermediate version asked + `www.instagram.com/api/v1/users//info/`, which the web app does not + normally call; Instagram answered a fresh `--import-session` there with 429. + The checked page is reused as the walk's first page, so `extract instagram + --limit 1 --stop-after-known 1` with a valid session makes exactly one + request (an import makes one as well). A 200 answer with `"status": "fail"` + to that page raises `InstagramFeedUnavailable` (not "logged out"); nothing is + saved. The feed does not name the viewer, so in web mode the account is the + one the `sessionid` belongs to; `feed_api = "iphone"` keeps the user-info + check with the username comparison. + +- **No automatic Instagram password login**: `extract instagram` (also with + `--transcribe`), `transcribe run` re-fetches and all API jobs never log in + with `INSTAGRAM_PASSWORD`. Without a usable session (no session file, + unreadable file, session logged out) they raise `InstagramAuthRequired` + (exit code 2, `error_code: auth_required`) that names the reason and says to + run `postparse check instagram --login` in a terminal; the session file is + not touched. `InstagramCollector` has a new `allow_password_login` argument + (default `False`) that only `check instagram --login` sets; it prints a + warning before the password login. A scripted password login after a + session check had made Instagram flag the account (confirmation request / + login redirect on the first feed page). + ### Fixed +- **`check instagram --login` saved an unusable session**: instaloader reports + a password login as successful as soon as Instagram answers + `authenticated: true`, even when no `sessionid` cookie came back, and keeps + its empty placeholder cookies in the jar (instaloader issue #2487). The + placeholders are now removed, a login without `sessionid` / `ds_user_id` + stops with `InstagramAuthRequired` ("Instagram accepted the password but + returned no session cookie ...; nothing was saved") and a new session is + verified with one session check before it is saved (also after a 2FA code). + Nothing is saved on any failure; the existing session file stays untouched. + A throttled check of a new session says "did not confirm the session after + the password login" (still `InstagramSessionCheckFailed`, exit code 3). +- **Cookie values in messages**: `"sessionid": "..."` (JSON) and bare + `sessionid` values are redacted as well. +- **Instagram's reason in messages**: logged-out sessions, confirmations, + feed refusals and rate limits quote Instagram's sanitized short reason + (`message "..."`, e.g. `checkpoint_required`, or a login redirect as + `scheme://host/path`); query strings, cookies, tokens and response bodies + are never included (at most 200 characters). A failed session check no + longer quotes the request URL. +- **No false "429" rate limits**: rate-limit markers are no longer matched + inside URLs or request paths (cursor and user ids such as `max_id=...3429...`); + an HTTP 429 / `TooManyRequestsException` is still a rate limit. A feed + refusal with such a cursor is reported as `feed_unavailable`. + - **Instagram session check**: the saved session is no longer verified with instaloader's `test_login()` (legacy GraphQL `query_hash` d6f4427…, which Instagram answers with 401 "Please wait a few minutes", and which reported @@ -16,8 +84,8 @@ All notable changes to PostParse are documented here. The format follows connection attempt). A throttled or failed check raises the new `InstagramSessionCheckFailed` (a subclass of `InstagramRateLimited`, exit code 3) and **never falls back to a password login**; the session file is - left untouched. The password login is only used when the session is - positively logged out. + left untouched. A password login (now only `check instagram --login`, see + above) is only used when the session is positively logged out. - **Instagram saved feed**: collected through the private API (`api/v1/feed/saved/posts/`, paginated with `max_id`) instead of `Profile.own_profile().get_saved_posts()`, which use legacy GraphQL @@ -25,6 +93,25 @@ All notable changes to PostParse are documented here. The format follows (with durations) are read from the private API media structs. - `AbortDownloadException` (checkpoint, login redirect) during a run is mapped to `InstagramAuthRequired`. +- **Instagram saved feed via the web REST API**: with a web session the + private-API feed on `i.instagram.com` (iPad headers) was answered with 200 + `"fail"` "We're sorry, but something went wrong" (and retried three times). + The feed is now requested like the Instagram web app does it: + `https://www.instagram.com/api/v1/feed/saved/posts/` with `X-IG-App-ID`, + `X-CSRFToken` (from the `csrftoken` cookie), `X-Requested-With`, + `X-ASBD-ID`, `X-IG-WWW-Claim` and the saved page as `Referer`, through + instaloader's session (cookies, rate controller). New option + `instagram.feed_api = "web" | "iphone"` (default `"web"`; invalid values are + reported by `config validate` and fail the run with a clear message). +- **Instagram feed refusals are not retried**: feed pages get one attempt + (network errors are still retried up to `max_connection_attempts`). A + `"fail"` answer raises the new `InstagramFeedUnavailable` (a `RateLimited` + subclass): CLI exit code 3 with a message that the session is fine, nothing + was lost and which `instagram.feed_api` to try; report `stopped_reason` and + job `error_code` `feed_unavailable`. +- **Instagram session outcome is shown**: `extract instagram` prints + "Instagram session verified (no password login)"; API jobs get the same + progress message. ## [0.2.0] - 2026-10-26 diff --git a/README.md b/README.md index 4fd0709..c4d8496 100644 --- a/README.md +++ b/README.md @@ -62,8 +62,11 @@ uv run postparse classify run --taxonomy topics # LLM labels for pending items uv run postparse search items pasta --label topics:recipe ``` -The first `extract` asks for the Telegram login code (and 2FA password) and, if -needed, an Instagram 2FA code; later runs reuse the saved sessions. +The first `extract` asks for the Telegram login code (and 2FA password); later +runs reuse the saved session. Instagram never logs in from `extract`: import the +session of your logged-in browser once with `postparse check instagram +--import-session` (hidden prompt for the `sessionid` cookie, no password; see +[Operations](docs/operations.md)). Every step only processes what is pending and can be re-run at any time. `classify run` uses the **default scope**: items collected after the taxonomy was diff --git a/config/config.example.toml b/config/config.example.toml index 8f3af81..7ab958a 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -192,8 +192,12 @@ default_max_delay = 15.0 # ... jittered between min and max refresh_min_delay = 5.0 # pause between `--refresh-dates` fetches; default: the refresh_max_delay = 15.0 # default_min/max_delay values request_timeout = 30.0 # instaloader request timeout (seconds) -max_connection_attempts = 3 # instaloader connection attempts -# user_agent = "..." # custom user agent; unset = instaloader default +max_connection_attempts = 3 # instaloader connection attempts (feed pages: network errors only) +feed_api = "web" # saved feed: "web" (www.instagram.com, like the web app; fits a + # browser/web session) or "iphone" (private API, i.instagram.com) +# user_agent = "..." # custom user agent; unset = instaloader default. After + # `check instagram --import-session` set it to the User-Agent + # of that browser (same browser identity as the session) # --------------------------------------------------------------------------- # REST API (`postparse serve`) diff --git a/docs/api-reference.md b/docs/api-reference.md index 6213433..41913f8 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -54,7 +54,7 @@ with `[...]`. |---|---|---| | POST | `/api/v1/telegram/extract` | Start a `telegram_extract` job. Body: `api_id`, `api_hash`, `phone` (override the env variables), `limit` (100), `force_update`. Never interactive: log in once with `postparse extract telegram`; the session in `sessions_dir` is reused. | | GET | `/api/v1/telegram/messages`, `/api/v1/telegram/messages/{message_id}` | Saved Telegram messages | -| POST | `/api/v1/instagram/extract` | Start an `instagram_extract` job. Body: `username`, `password` (optional with a valid session), `limit` (50), `force_update`, `stop_after_known` (20), `refresh_dates`. `use_api=true` is not supported (400). | +| POST | `/api/v1/instagram/extract` | Start an `instagram_extract` job. Body: `username`, `password` (accepted, but jobs never log in with it: they use the saved session; import the browser session with `postparse check instagram --import-session` or log in with `postparse check instagram --login`), `limit` (50), `force_update`, `stop_after_known` (20), `refresh_dates`. `use_api=true` is not supported (400). | | GET | `/api/v1/instagram/posts`, `/api/v1/instagram/posts/{shortcode}` | Saved Instagram posts (`offset` deprecated, use `cursor`) | ### Processing jobs @@ -131,6 +131,7 @@ service raises or its report stops for a hard reason: | `credentials_missing` | `TELEGRAM_*` / `INSTAGRAM_*` not set and not in the request | | `auth_required` | session invalid, login code / 2FA needed (log in once via the CLI) | | `rate_limited` | Telegram FloodWait above the threshold, Instagram 429 | +| `feed_unavailable` | Instagram refused the saved feed with a `"fail"` status ("something went wrong"); the session is fine, see `instagram.feed_api` | | `suspected_block` | transcription stopped by the soft-block circuit breaker | | `backend_unavailable` | ASR backend not installed or unreachable | | `llm_error` | classification / summarization failed at the LLM | diff --git a/docs/cli-reference.md b/docs/cli-reference.md index c46eeb1..4aea809 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -34,7 +34,7 @@ Running `postparse` without a command shows a welcome banner. | `0` | success | | `1` | error (also: a failed check in `config validate` / `check` / `db check`, ASR backend unavailable) | | `2` | login required (`extract`, `transcribe run`: Telegram/Instagram session invalid or 2FA needed in non-interactive mode); also click usage errors | -| `3` | rate limited (Telegram FloodWait above the threshold, Instagram 429) or suspected Instagram soft block (`transcribe run`) | +| `3` | rate limited (Telegram FloodWait above the threshold, Instagram 429), Instagram refused the saved feed (`"fail"` status; see `instagram.feed_api`) or suspected Instagram soft block (`transcribe run`) | | `130` | interrupted (Ctrl-C) | `extract all` returns the most severe code of the platforms (3 > 2 > 1). @@ -47,14 +47,14 @@ Usage: postparse check [OPTIONS] [COMMAND] [ARGS]... Health checks (database, transcription, sessions, LLM providers). -Without a subcommand this runs `check all`. Only `--login` and `check llm` -talk to external services. +Without a subcommand this runs `check all`. Only `--login`, +`check instagram --import-session` and `check llm` talk to external services. | Subcommand | Description | |---|---| | [`all`](#postparse-check-all) | Run all checks (no Telegram/Instagram network calls without --login). | | [`db`](#postparse-check-db) | Database integrity, schema version and search index (= `db check`). | -| [`instagram`](#postparse-check-instagram) | Instagram session file and credentials (`--login` verifies online). | +| [`instagram`](#postparse-check-instagram) | Instagram session file and credentials (`--login` / `--import-session` go online). | | [`llm`](#postparse-check-llm) | LLM providers: model list, discovered model, chat ping and latency. | | [`telegram`](#postparse-check-telegram) | Telegram session file and credentials (`--login` verifies online). | | [`transcription`](#postparse-check-transcription) | Transcription backend: faster-whisper / CUDA, or API endpoint reachability. | @@ -101,12 +101,16 @@ Database integrity, schema version and search index (= `db check`). Usage: postparse check instagram [OPTIONS] ``` -Instagram session file and credentials (`--login` verifies online). +Instagram session file and credentials (`--login` / `--import-session` go online). + +`--import-session` is the recommended way to log in: it takes the session +of your logged-in browser (no password login). **Examples:** ```bash postparse check instagram +postparse check instagram --import-session postparse check instagram --login ``` @@ -114,7 +118,18 @@ postparse check instagram --login |---|---|---|---| | `--username` | TEXT | | Instagram username (default: INSTAGRAM_USERNAME) | | `--session` | TEXT | | Session file (default: <sessions_dir>/instagram_<username>) | -| `--login` | flag | | Load the session or log in to Instagram (may prompt for a 2FA code) | +| `--login` | flag | | Verify the saved session; without a usable one log in with INSTAGRAM_PASSWORD (may prompt for a 2FA code). The only command that uses the password. | +| `--import-session` | flag | | Import the sessionid cookie of your logged-in browser (hidden prompt, no password), verify it with one request and save it. Needs a terminal. | + +`--import-session` and `--login` cannot be combined (usage error, exit code +2). The import asks for the `sessionid` cookie (hidden input) and optionally +the `csrftoken` cookie (Enter generates one), makes exactly one request (the +session check: with `instagram.feed_api = "web"`, the default, the first page +of the saved feed, as the web app requests it when the saved page is opened; +with `"iphone"` the user info on `i.instagram.com`) and saves the session file +only when Instagram confirms the session; otherwise nothing is saved (exit +code 1). +See [Operations](operations.md#instagram-logging-in-checkpoint-2fa-soft-block). ### `postparse check llm` @@ -634,8 +649,13 @@ Usage: postparse extract instagram [OPTIONS] Collect saved Instagram posts (newest first, stops at known posts). -Credentials: INSTAGRAM_USERNAME and INSTAGRAM_PASSWORD from the environment -or config/.env (the password is only needed when the session is invalid). +Uses the saved session of INSTAGRAM_USERNAME (environment or config/.env) +and never logs in with the password: without a usable session it stops +with exit code 2. Import the session of your logged-in browser with +`postparse check instagram --import-session` in a terminal (no password), +or log in with `postparse check instagram --login` (the only command that +uses INSTAGRAM_PASSWORD; it may not yield a usable session, instaloader +#2487), then retry. **Examples:** @@ -651,7 +671,8 @@ postparse extract instagram --transcribe ```text New posts are throttled (several seconds each). If Instagram asks for a -confirmation, confirm the login in the Instagram app and retry. +confirmation, confirm the login in the Instagram app, run +`postparse check instagram --import-session` (or `--login`) and retry. ``` | Option | Type | Default | Description | diff --git a/docs/configuration.md b/docs/configuration.md index af2f335..19eaafb 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -46,7 +46,7 @@ below `./data`, no LLM providers, no taxonomies). | `[summarization]` | `SummarizationService` | `provider`, `max_input_chars`, `output_retries` | | `[enrichment]` | `EnrichmentService` | see [Enrichment](enrichment.md) | | `[telegram]` | Telegram collector | batch size, FloodWait threshold, media download limits and pauses, Telethon retry settings | -| `[instagram]` | Instagram collector | pauses between posts (`default_min_delay` / `default_max_delay`) and date refreshes, instaloader timeout / attempts, `user_agent` | +| `[instagram]` | Instagram collector | pauses between posts (`default_min_delay` / `default_max_delay`) and date refreshes, instaloader timeout / attempts, `user_agent`, `feed_api` (`"web"`: saved feed like the web app on `www.instagram.com`, default; `"iphone"`: private API on `i.instagram.com`) | | `[api]` and `[api.auth]`, `[api.cors]`, `[api.rate_limiting]`, `[api.cache]`, `[api.jobs]` | `serve`, FastAPI app | see [API reference](api-reference.md) | ### LLM provider example (llama.cpp) @@ -79,7 +79,7 @@ provider only. | Variable | Purpose | |---|---| | `TELEGRAM_API_ID`, `TELEGRAM_API_HASH`, `TELEGRAM_PHONE` | Telegram API credentials (phone optional, used for the first login) | -| `INSTAGRAM_USERNAME`, `INSTAGRAM_PASSWORD` | Instagram login (password optional while the session file is valid) | +| `INSTAGRAM_USERNAME`, `INSTAGRAM_PASSWORD` | Instagram account; the password is only used by `postparse check instagram --login`; extract and API jobs use the saved session (recommended: `postparse check instagram --import-session` imports the browser session, no password) | | `OPENAI_API_KEY`, `ANTHROPIC_API_KEY` | LLM providers; the transcription API backend reads the variable named by `transcription.api.api_key_env` (default `OPENAI_API_KEY`) | | `JWT_SECRET_KEY` | API authentication secret (fallback when `api.auth.secret_key` is not set) | | `POSTPARSE_DATA_DIR`, `POSTPARSE_DB_PATH`, `POSTPARSE_SESSIONS_DIR`, `POSTPARSE_DOWNLOADS_DIR`, `POSTPARSE_TMP_DIR` | override the corresponding `[paths]` / `[database]` values | diff --git a/docs/operations.md b/docs/operations.md index 982388b..4d920f7 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -177,25 +177,117 @@ postparse db reindex * Exit code 3 / FloodWait: Telegram asked to wait longer than `telegram.flood_sleep_threshold`; retry later. -### Instagram: checkpoint, 2FA, soft block - -* **2FA**: interactive runs prompt for the code; non-interactive runs exit with - code 2. Run `postparse extract instagram` in a terminal. +### Instagram: logging in, checkpoint, 2FA, soft block + +* **Logging in (recommended): import the browser session** with + `postparse check instagram --import-session` in a terminal. No password is + used: + 1. Log in to Instagram in your browser (the account of + `INSTAGRAM_USERNAME`). + 2. Open the developer tools (F12). Chrome / Edge: **Application** → + **Cookies** → `https://www.instagram.com`; Firefox: **Storage** → + **Cookies** → `https://www.instagram.com`. + 3. Copy the value of the `sessionid` cookie (it looks like + `%3A...`; a copy with `:` instead of `%3A` is accepted too) and + paste it into the hidden prompt. The `csrftoken` prompt is optional + (Enter generates one). + 4. postparse makes exactly **one** request (the session check: with + `instagram.feed_api = "web"`, the default, the first page of the saved + feed, `www.instagram.com/api/v1/feed/saved/posts/`, the request the web + app itself makes when the saved page is opened) and saves the session + file (`data/sessions/instagram_`, or `--session`) only when + Instagram confirms the session; a logged-out session, a confirmation + request, a throttled check or a refused feed saves nothing and leaves an + existing session file alone. The feed does not name the viewer, so in + web mode the account is the one the `sessionid` belongs to (its leading + number is the `ds_user_id`): copy the cookie of the `INSTAGRAM_USERNAME` + account. With `feed_api = "iphone"` the check asks the user info on + `i.instagram.com` and rejects a session of another account. + 5. Set `[instagram] user_agent` in `config/config.toml` to the User-Agent of + that browser (e.g. from `navigator.userAgent` in the browser console), so + the session is used with the same browser identity. + 6. Do not log out of Instagram in that browser: logging out ends this + session too (closing the browser is fine). + + The prompt needs an interactive terminal; the cookie is never read from + arguments, pipes or the environment and is never shown or logged. +* **Password login (alternative)**: `postparse check instagram --login` + verifies the saved session and, only if there is none or Instagram says it + is logged out, logs in with `INSTAGRAM_PASSWORD`. It prints a warning before + that password login and may ask for a 2FA code or a confirmation in the + Instagram app. It is the **only** command that ever uses the password. The + new session is verified (one request) before it is saved: instaloader may + report a successful login although Instagram set no `sessionid` cookie + (instaloader issue #2487); then `--login` stops with "Instagram accepted the + password but returned no session cookie ...; nothing was saved" instead of + saving an unusable session. Use `--import-session` in that case. +* **Extract never uses the password**: `extract instagram` (also with + `--transcribe`), `transcribe run` re-fetches and all API jobs only use the + saved session. Without a usable one (no session file, unreadable file, + session logged out) they stop with exit code 2 / `error_code: + auth_required` and a message like "No password login was attempted + (session logged out: login_required); automatic password logins are + disabled because they trigger Instagram checkpoints. Instagram login + required: import the session of your logged-in browser with `postparse + check instagram --import-session` in a terminal (no password), or run + `postparse check instagram --login` ..., then retry." Repeated scripted password logins are what makes Instagram ask for + checkpoints, so there is no switch to turn them back on. +* **Instagram's reason**: logged-out sessions, confirmations, feed refusals + and rate limits quote Instagram's own short reason, e.g. `(Instagram: + checkpoint_required)`, `login_required`, `challenge_required`, + `feedback_required`, or for a login redirect the target as + `https://host/path`. Query strings, cookies, tokens and response bodies are + never shown (at most 200 characters). +* **2FA**: `check instagram --login` prompts for the code in the terminal. * **Checkpoint / "confirm it was you"**: confirm the login in the Instagram app, - then retry. If the saved session keeps failing, delete - `data/sessions/instagram_` and log in again (needs - `INSTAGRAM_PASSWORD`). + then run `postparse check instagram --import-session` (or `--login`) and + retry the extract. Do not + delete the session file just because a run failed. * **"Instagram did not confirm the saved session"**: exit code 3. The session - check (one request to `i.instagram.com/api/v1/users//info/`, a single - attempt) was throttled (401 "Please wait a few minutes", 429) or Instagram - was unreachable. This says nothing about the session itself, so **no password + check (one request, a single attempt; with `instagram.feed_api = "web"`, the + default, the first page of the saved feed on `www.instagram.com`, exactly as + the feed walk and the web app request it, with the saved page as `Referer`; + with `"iphone"` `api/v1/users//info/` on `i.instagram.com`, so a run + uses one client identity and a browser session is never sent with iPad + headers to `i.instagram.com`) was throttled (401 "Please wait a few + minutes", 429) or Instagram was unreachable. This says nothing about the session itself, so **no password login is attempted** and the session file is left untouched; nothing was - collected or lost. Wait a few hours and retry. A password login (with - `INSTAGRAM_PASSWORD`) only happens when the check positively says the session - is logged out (login redirect, `login_required`, session of another account, - no `sessionid` cookie) or when there is no session file. Repeated scripted - password logins are what triggers checkpoints, so do not delete a session + collected or lost. Wait a few hours and retry. Even `check instagram + --login` only logs in with the password when the check positively says the + session is logged out (login redirect, `login_required`, with `"iphone"` a + session of another account, no `sessionid` cookie) or when there is no + session file; a + throttled check never leads to a password login. Do not delete a session file just because of this message. +* **Session outcome on the console**: every `extract instagram` run prints + "Instagram session verified (no password login)" or stops with exit code 2 + and the reason. `check instagram --login` prints the warning "No usable + Instagram session (); logging in with the password now ..." before + a password login, so it is never silent. +* **Request count in web mode**: the page the session check fetched is the + first page of the saved-feed walk (it is not requested again; later pages + follow with `max_id`). `extract instagram --limit 1 --stop-after-known 1` + with a valid session therefore makes exactly **one** request; an import + makes one; a `transcribe run` re-fetch makes the check (one feed page) plus + one request per post. +* **"Instagram refused the saved feed ... something went wrong"**: exit code 3 + (`stopped_reason` / job `error_code` `feed_unavailable`). No password login + is attempted; Instagram answered the feed request + (`api/v1/feed/saved/posts/`) with HTTP 200 and `"status": "fail"`, which is + not a statement about the session (in web mode this can already be the + session check's page: then nothing is saved and nothing collected). + Everything committed before is kept. Feed pages get a + single attempt (only network errors such as timeouts are retried, up to + `instagram.max_connection_attempts`), so a refusal costs one request. The + answer depends on how the feed is requested, so the API is configurable: + `instagram.feed_api = "web"` (default) requests + `https://www.instagram.com/api/v1/feed/saved/posts/` with the web app's + headers (`X-IG-App-ID`, `X-CSRFToken` from the session cookie, + `X-Requested-With`, `X-ASBD-ID`, `X-IG-WWW-Claim`, the saved page as + `Referer`), which fits a session created on the website; `"iphone"` uses + the private API on `i.instagram.com` with instaloader's iPad headers. If one + keeps failing, switch to the other in `config/config.toml` and retry once; + if both fail, wait a few hours. * **Rate limit (429) / soft block**: exit code 3. Instagram sometimes answers a soft-blocked session with errors that look like deleted posts; the transcription circuit breaker stops after diff --git a/src/postparse/api/jobs/runner.py b/src/postparse/api/jobs/runner.py index 32495ba..6ae73b7 100644 --- a/src/postparse/api/jobs/runner.py +++ b/src/postparse/api/jobs/runner.py @@ -15,7 +15,8 @@ * Errors become failed jobs with an ``error_code``: typed collector errors (:class:`AuthRequired`, :class:`RateLimited`), reports whose ``stopped_reason`` signals a hard stop (``auth_required``, - ``rate_limited``, ``suspected_block``, ``backend_unavailable``) and any + ``rate_limited``, ``feed_unavailable``, ``suspected_block``, + ``backend_unavailable``) and any other exception (``internal_error``). * The response cache is invalidated after every job, because even a partial run may have committed data. @@ -69,7 +70,7 @@ #: Report ``stopped_reason`` values that turn a returned report into a failed job. FAILURE_STOP_REASONS: frozenset[str] = frozenset( - {"auth_required", "rate_limited", "suspected_block", "backend_unavailable"} + {"auth_required", "rate_limited", "feed_unavailable", "suspected_block", "backend_unavailable"} ) _PROCESSED_KEYS = ("processed", "handled", "classified", "summarized") @@ -77,12 +78,19 @@ def error_code_for(exc: BaseException) -> str: """Map an exception raised by a service to a job ``error_code``.""" - from postparse.collectors.base import AuthRequired, CredentialsMissing, RateLimited + from postparse.collectors.base import ( + AuthRequired, + CredentialsMissing, + InstagramFeedUnavailable, + RateLimited, + ) if isinstance(exc, CredentialsMissing): return "credentials_missing" if isinstance(exc, AuthRequired): return "auth_required" + if isinstance(exc, InstagramFeedUnavailable): + return "feed_unavailable" if isinstance(exc, RateLimited): return "rate_limited" name = type(exc).__name__ diff --git a/src/postparse/api/routers/instagram.py b/src/postparse/api/routers/instagram.py index 043c3ca..7e5afaf 100644 --- a/src/postparse/api/routers/instagram.py +++ b/src/postparse/api/routers/instagram.py @@ -70,7 +70,9 @@ otherwise the run stops after `stop_after_known` consecutive known posts. A missing or expired login fails the job with `error_code=auth_required` (log in once with `postparse extract instagram` in a terminal); rate limits - fail it with `rate_limited`. Counts of partial runs are kept in `result`. + fail it with `rate_limited`; a saved feed that Instagram refuses with a "fail" + status ("something went wrong") fails it with `feed_unavailable` (see + `instagram.feed_api`). Counts of partial runs are kept in `result`. """, ) async def extract_posts( diff --git a/src/postparse/api/routers/jobs.py b/src/postparse/api/routers/jobs.py index b7afbc7..a159858 100644 --- a/src/postparse/api/routers/jobs.py +++ b/src/postparse/api/routers/jobs.py @@ -54,7 +54,8 @@ def list_jobs( summary="Check job status", description=""" Status of any background job. Failed jobs carry an `error_code` - (`auth_required`, `credentials_missing`, `rate_limited`, `suspected_block`, + (`auth_required`, `credentials_missing`, `rate_limited`, `feed_unavailable`, + `suspected_block`, `backend_unavailable`, `llm_error`, `invalid_request`, `cancelled`, `internal_error`); finished jobs carry the service report in `result`. """, diff --git a/src/postparse/api/schemas/instagram.py b/src/postparse/api/schemas/instagram.py index 0d8a718..28adcb4 100644 --- a/src/postparse/api/schemas/instagram.py +++ b/src/postparse/api/schemas/instagram.py @@ -21,8 +21,10 @@ class InstagramExtractRequest(BaseModel): Attributes: username: Instagram account username. - password: Account password (optional when a valid session file exists; - falls back to ``INSTAGRAM_PASSWORD``). + password: Accepted for compatibility but never used for a login: jobs + only use the saved session (import the browser session with + ``postparse check instagram --import-session``, or log in with + ``postparse check instagram --login``). access_token: API access token (for Platform API method). limit: Maximum number of posts to extract. force_update: Walk the whole saved feed and update known posts. diff --git a/src/postparse/api/schemas/telegram.py b/src/postparse/api/schemas/telegram.py index 3bc582e..6d896f2 100644 --- a/src/postparse/api/schemas/telegram.py +++ b/src/postparse/api/schemas/telegram.py @@ -269,7 +269,8 @@ class JobStatusResponse(BaseModel): error_code: str | None = Field( default=None, description="Machine-readable failure reason (auth_required, credentials_missing, " - "rate_limited, suspected_block, backend_unavailable, llm_error, invalid_request, " + "rate_limited, feed_unavailable, suspected_block, backend_unavailable, llm_error, " + "invalid_request, " "cancelled, internal_error)", ) result: dict[str, Any] | None = Field( diff --git a/src/postparse/cli/check.py b/src/postparse/cli/check.py index cc166c1..6d0f369 100644 --- a/src/postparse/cli/check.py +++ b/src/postparse/cli/check.py @@ -3,8 +3,9 @@ - ``db``: same as ``postparse db check`` - ``transcription``: ASR backend availability (no model download unless ``--load-model``) - ``telegram`` / ``instagram``: which session file would be used and whether - credentials are set (names only). Only ``--login`` contacts the service - (interactive prompts are allowed); the default makes no network call. + credentials are set (names only). Only ``--login`` (and Instagram's + ``--import-session``) contacts the service (interactive prompts are + allowed); the default makes no network call. - ``llm``: list models, discovered model, chat ping and latency per provider - ``all``: everything above (``--login`` passes through); also the default @@ -13,6 +14,7 @@ Example: $ postparse check $ postparse check telegram --login + $ postparse check instagram --import-session $ postparse check transcription --load-model $ postparse check llm --provider llama_cpp """ @@ -24,7 +26,8 @@ import os import shutil import subprocess -from collections.abc import Mapping +import sys +from collections.abc import Callable, Mapping from dataclasses import dataclass, field from datetime import datetime from pathlib import Path @@ -38,6 +41,7 @@ config_path_from_ctx, get_console, print_error, + print_info, print_success, print_warning, resolve_db_path, @@ -248,6 +252,13 @@ async def connect() -> None: return result +#: How to create an Instagram session (recommended way first). +_IMPORT_HINT = ( + "Import the session of your logged-in browser: `postparse check instagram " + "--import-session` (in a terminal, no password)" +) + + def instagram_status( settings: Settings, env: Mapping[str, str] | None = None, @@ -293,21 +304,51 @@ def instagram_status( result.hints.append("Verify the login with `postparse check instagram --login`") elif has_password: result.worsen("warn") - result.summary = "no session file; the next extract logs in with the password" + result.summary = "no session file; extract never logs in with the password" + result.hints.append(_IMPORT_HINT) + result.hints.append( + "Alternative: `postparse check instagram --login` (password login; may not " + "yield a usable session, instaloader #2487)" + ) else: result.worsen("fail") result.summary = "no session file and INSTAGRAM_PASSWORD not set" + result.hints.append(_IMPORT_HINT) result.hints.append( - "Set INSTAGRAM_PASSWORD once and run `postparse check instagram " - "--login` to create the session" + "Alternative: set INSTAGRAM_PASSWORD and run `postparse check instagram --login` " + "(may not yield a usable session, instaloader #2487)" ) return result +def _print_session_event(event: Any) -> None: + """Print the session outcome of ``--login`` (a password login as a warning).""" + if event.phase == "login": + print_warning( + escape( + f"{event.message}. This is the only command that logs in with the password; " + "Instagram may ask for a 2FA code or a confirmation in the Instagram app." + ) + ) + elif event.phase == "session" and event.message: + print_info(escape(event.message)) + + def _make_instagram_collector( - settings: Settings, credentials: Any, config: Any, session: str | None + settings: Settings, + credentials: Any, + config: Any, + session: str | None, + *, + allow_password_login: bool = True, ) -> Any: - """Create the Instagram collector used by ``--login`` (tests replace this).""" + """Create the Instagram collector used by ``--login`` / ``--import-session``. + + Tests replace this. ``--login`` creates the only collector with + ``allow_password_login=True``: an interactive, explicitly requested login. + ``--import-session``, extract runs, transcription re-fetches and API jobs + never log in with the password. + """ from postparse.collectors.instagram import InstagramCollector, InstagramOptions from postparse.core.db import Database @@ -319,13 +360,20 @@ def _make_instagram_collector( InstagramOptions.from_config(config), interactive=True, session=session, + allow_password_login=allow_password_login, + progress=_print_session_event, ) def instagram_login( settings: Settings, config: Any, username: str | None, session: str | None ) -> CheckResult: - """Load the Instagram session (or log in) and save it.""" + """Verify the saved Instagram session, or log in with the password, and save it. + + The password login (with a 2FA prompt if needed) only happens here, and + only when there is no usable session; a throttled session check never + leads to one. + """ from postparse.collectors import CollectorError, instagram_credentials result = CheckResult("instagram login") @@ -343,6 +391,93 @@ def instagram_login( return result +#: Reads one secret from the terminal (hidden input); tests replace it. +SecretPrompt = Callable[[str, bool], str] + + +def _stdin_is_tty() -> bool: + """True if stdin is an interactive terminal (tests replace this).""" + try: + return sys.stdin.isatty() + except (AttributeError, ValueError): + return False + + +def _prompt_secret(text: str, optional: bool) -> str: + """Prompt with hidden input (``optional``: Enter returns ``""``).""" + value: str = click.prompt( + text, hide_input=True, default="" if optional else None, show_default=False + ) + return value + + +def instagram_import( + settings: Settings, + config: Any, + username: str | None, + session: str | None, + prompt: SecretPrompt | None = None, +) -> CheckResult: + """Import the ``sessionid`` cookie of the user's logged-in browser and save it. + + The cookie is read from a hidden prompt (never from arguments or the + environment, never shown or logged), verified with one request + (:meth:`InstagramCollector.import_session`) and saved only when Instagram + confirms it. The password is never used. + + Args: + settings: Application settings. + config: ``ConfigManager`` or ``None``. + username: ``--username`` override of ``INSTAGRAM_USERNAME``. + session: ``--session`` override (file path). + prompt: ``(text, optional) -> value`` (default: hidden terminal prompt). + + Returns: + ``ok`` with the saved session file, ``fail`` with the reason. + """ + from postparse.collectors import CollectorError, instagram_credentials + from postparse.collectors.instagram import InvalidSessionCookie + + result = CheckResult("instagram import") + if prompt is None: + if not _stdin_is_tty(): + result.worsen("fail") + result.summary = ( + "--import-session needs an interactive terminal: the sessionid cookie is " + "read from a hidden prompt (never from arguments, pipes or the environment)" + ) + return result + prompt = _prompt_secret + try: + credentials = instagram_credentials(username=username) + collector = _make_instagram_collector( + settings, credentials, config, session, allow_password_login=False + ) + print_info( + "Copy the value of the `sessionid` cookie of https://www.instagram.com from your " + "logged-in browser (developer tools, F12). One request verifies it." + ) + sessionid = prompt("Instagram sessionid cookie from your browser (input hidden)", False) + csrftoken = prompt( + "Instagram csrftoken cookie (optional, input hidden; Enter to generate one)", True + ) + collector.import_session(sessionid, csrftoken or None) + except (CollectorError, InvalidSessionCookie) as exc: + result.worsen("fail") + result.summary = str(exc) + return result + result.summary = "browser session imported and verified" + result.rows.append(("Session file", _file_row(Path(collector.save_path)))) + result.hints.append( + "Set `[instagram] user_agent` in config/config.toml to the User-Agent of that " + "browser, so the session is used with the same browser identity" + ) + result.hints.append( + "Do not log out of Instagram in that browser: logging out ends this session too" + ) + return result + + # --------------------------------------------------------------------------- # Transcription # --------------------------------------------------------------------------- @@ -586,8 +721,8 @@ def llm_status( def check(ctx: click.Context) -> None: """🔍 Health checks (database, transcription, sessions, LLM providers). - Without a subcommand this runs `check all`. Only `--login` and `check llm` - talk to external services. + Without a subcommand this runs `check all`. Only `--login`, + `check instagram --import-session` and `check llm` talk to external services. """ if ctx.invoked_subcommand is None: ctx.invoke(all_checks) @@ -634,20 +769,49 @@ def telegram(ctx: click.Context, session: str | None, login: bool) -> None: @click.option( "--login", is_flag=True, - help="Load the session or log in to Instagram (may prompt for a 2FA code)", + help=( + "Verify the saved session; without a usable one log in with INSTAGRAM_PASSWORD " + "(may prompt for a 2FA code). The only command that uses the password." + ), +) +@click.option( + "--import-session", + "import_session", + is_flag=True, + help=( + "Import the sessionid cookie of your logged-in browser (hidden prompt, no " + "password), verify it with one request and save it. Needs a terminal." + ), ) @click.pass_context -def instagram(ctx: click.Context, username: str | None, session: str | None, login: bool) -> None: - """📸 Instagram session file and credentials (`--login` verifies online). +def instagram( + ctx: click.Context, + username: str | None, + session: str | None, + login: bool, + import_session: bool, +) -> None: + """📸 Instagram session file and credentials (`--login` / `--import-session` go online). + + `--import-session` is the recommended way to log in: it takes the session + of your logged-in browser (no password login). Examples: postparse check instagram + postparse check instagram --import-session postparse check instagram --login """ + if login and import_session: + raise click.UsageError("--login and --import-session cannot be combined.") settings = _settings(ctx) results = [instagram_status(settings, username=username, session=session)] print_result(results[0]) - if login and results[0].status != "fail": + if import_session: + # The import replaces a missing session; its own result decides the exit code. + if (username or "").strip() or (os.environ.get("INSTAGRAM_USERNAME") or "").strip(): + results = [instagram_import(settings, _config(ctx), username, session)] + print_result(results[0]) + elif login and results[0].status != "fail": results.append(instagram_login(settings, _config(ctx), username, session)) print_result(results[-1]) _finish(ctx, results) diff --git a/src/postparse/cli/config.py b/src/postparse/cli/config.py index 9adc6ae..49d0c6e 100644 --- a/src/postparse/cli/config.py +++ b/src/postparse/cli/config.py @@ -338,6 +338,7 @@ def _validate_features(manager: Any, results: list[dict[str, str]], providers: s import importlib.util from postparse.classification.taxonomy import load_taxonomies + from postparse.collectors.instagram import InstagramOptions from postparse.enrichment.options import EnrichmentOptions from postparse.media.options import TranscriptionOptions @@ -385,6 +386,12 @@ def _validate_features(manager: Any, results: list[dict[str, str]], providers: s except ValueError as exc: _add(results, "Enrichment", "fail", str(exc)) + try: + instagram = InstagramOptions.from_config(manager) + _add(results, "Instagram", "pass", f"feed_api {instagram.feed_api}") + except ValueError as exc: + _add(results, "Instagram", "fail", str(exc)) + @config.command() @click.option("--fix", is_flag=True, help="Create missing data directories") diff --git a/src/postparse/cli/extract.py b/src/postparse/cli/extract.py index e30be69..61065d9 100644 --- a/src/postparse/cli/extract.py +++ b/src/postparse/cli/extract.py @@ -3,9 +3,12 @@ Thin adapters over :class:`postparse.services.extraction.ExtractionService`. Credentials come from the environment (``config/.env`` is loaded by the CLI): ``TELEGRAM_API_ID``, ``TELEGRAM_API_HASH``, ``TELEGRAM_PHONE`` and -``INSTAGRAM_USERNAME``, ``INSTAGRAM_PASSWORD``. +``INSTAGRAM_USERNAME`` (Instagram uses the saved session, created by +``postparse check instagram --import-session`` from the browser or by +``postparse check instagram --login``, the only user of the password). -Exit codes: 0 success, 1 unexpected error, 2 login required, 3 rate limited. +Exit codes: 0 success, 1 unexpected error, 2 login required, 3 rate limited +or Instagram refused the saved feed (retry later; nothing stored is lost). Example: $ postparse extract telegram # new messages only @@ -27,6 +30,7 @@ import rich_click as click from click.exceptions import Exit as ClickExit +from rich.markup import escape from rich.progress import Progress, SpinnerColumn, TextColumn, TimeElapsedColumn from rich.table import Table @@ -91,6 +95,16 @@ def __init__(self, label: str) -> None: self.task: Any = None def __call__(self, event: ProgressEvent) -> None: + if event.phase in _SESSION_PHASES: + # Session outcome: one visible line. Extract runs never log in with the + # password; a "login" event (only possible with allow_password_login) + # would still show as a warning. + self.stop() + if event.phase == "login": + print_warning(event.message or "Logging in to Instagram with the password") + else: + print_info(event.message or "Instagram session verified") + return if self.progress is None: self.progress = Progress( SpinnerColumn(), @@ -117,12 +131,16 @@ def stop(self) -> None: self.progress = None +#: Progress phases that report the Instagram session outcome (printed as a line). +_SESSION_PHASES = ("session", "login") + _REASONS = { "end_of_feed": "reached the end", "early_stop": "stopped at known posts", "limit": "limit reached", "rate_limited": "rate limited", "auth_required": "login required", + "feed_unavailable": "feed refused by Instagram", } @@ -157,12 +175,16 @@ def _print_report(report: ExtractionReport, title: str) -> None: def _exit_code(report: ExtractionReport) -> int: """Map a report to the command's exit code (and print the reason).""" if report.stopped_reason == "auth_required": - print_error(report.error or "Login required.") + print_error(escape(report.error or "Login required.")) return EXIT_AUTH if report.stopped_reason == "rate_limited": - print_warning(report.error or "Rate limited; retry later.") + print_warning(escape(report.error or "Rate limited; retry later.")) print_info("Everything committed before the limit was hit has been kept.") return EXIT_RATE_LIMITED + if report.stopped_reason == "feed_unavailable": + print_warning(escape(report.error or "Instagram refused the saved feed; retry later.")) + print_info("Everything committed before the feed was refused has been kept.") + return EXIT_RATE_LIMITED print_success(f"{report.source.capitalize()} extraction completed.") return EXIT_OK @@ -444,8 +466,13 @@ def instagram( ) -> None: """Collect saved Instagram posts (newest first, stops at known posts). - Credentials: INSTAGRAM_USERNAME and INSTAGRAM_PASSWORD from the environment - or config/.env (the password is only needed when the session is invalid). + Uses the saved session of INSTAGRAM_USERNAME (environment or config/.env) + and never logs in with the password: without a usable session it stops + with exit code 2. Import the session of your logged-in browser with + `postparse check instagram --import-session` in a terminal (no password), + or log in with `postparse check instagram --login` (the only command that + uses INSTAGRAM_PASSWORD; it may not yield a usable session, instaloader + #2487), then retry. Examples: postparse extract instagram @@ -456,7 +483,8 @@ def instagram( Note: New posts are throttled (several seconds each). If Instagram asks for a - confirmation, confirm the login in the Instagram app and retry. + confirmation, confirm the login in the Instagram app, run + `postparse check instagram --import-session` (or `--login`) and retry. """ code = _instagram( ctx, @@ -531,7 +559,10 @@ def all_platforms( interactive=interactive, ) else: - print_warning("Skipping Instagram (set INSTAGRAM_USERNAME and INSTAGRAM_PASSWORD).") + print_warning( + "Skipping Instagram (set INSTAGRAM_USERNAME and import your browser session " + "once with `postparse check instagram --import-session`)." + ) console.print() if not codes: print_warning("No platform configured; nothing extracted.") diff --git a/src/postparse/collectors/__init__.py b/src/postparse/collectors/__init__.py index 0f2c26a..87e166e 100644 --- a/src/postparse/collectors/__init__.py +++ b/src/postparse/collectors/__init__.py @@ -10,6 +10,7 @@ CollectStats, CredentialsMissing, InstagramAuthRequired, + InstagramFeedUnavailable, InstagramRateLimited, InstagramSessionCheckFailed, ProgressCallback, @@ -32,6 +33,7 @@ "CredentialsMissing", "InstagramAuthRequired", "InstagramCredentials", + "InstagramFeedUnavailable", "InstagramRateLimited", "InstagramSessionCheckFailed", "ProgressCallback", diff --git a/src/postparse/collectors/base.py b/src/postparse/collectors/base.py index a7555f5..1bbb612 100644 --- a/src/postparse/collectors/base.py +++ b/src/postparse/collectors/base.py @@ -26,6 +26,7 @@ "CollectorError", "CredentialsMissing", "InstagramAuthRequired", + "InstagramFeedUnavailable", "InstagramRateLimited", "InstagramSessionCheckFailed", "ProgressCallback", @@ -40,7 +41,9 @@ logger = logging.getLogger(__name__) -StopReason = Literal["early_stop", "limit", "end_of_feed", "rate_limited", "auth_required"] +StopReason = Literal[ + "early_stop", "limit", "end_of_feed", "rate_limited", "auth_required", "feed_unavailable" +] # --------------------------------------------------------------------------- @@ -82,12 +85,20 @@ def __init__(self, detail: str | None = None) -> None: class InstagramAuthRequired(AuthRequired): - """Instagram session is invalid and no automatic login was possible.""" + """Instagram session is invalid and no automatic login was possible. + + Collection never logs in with the password; the message points to the + interactive ``postparse check instagram --import-session`` (the session of + the logged-in browser, no password) and ``postparse check instagram --login``. + """ def __init__(self, detail: str | None = None) -> None: message = ( - "Instagram login required. If Instagram asks for a confirmation, confirm the " - "login in the Instagram app, then retry `postparse extract instagram` in a terminal." + "Instagram login required: import the session of your logged-in browser with " + "`postparse check instagram --import-session` in a terminal (no password), or " + "run `postparse check instagram --login` (it may ask for a 2FA code or a " + "confirmation in the Instagram app, and may not yield a usable session: " + "instaloader issue #2487), then retry." ) super().__init__(f"{detail} {message}" if detail else message) @@ -119,15 +130,62 @@ class InstagramSessionCheckFailed(InstagramRateLimited): session check with a throttle ("please wait a few minutes", 401/429) or did not answer at all, which says nothing about the session itself. Repeated scripted password logins are what triggers checkpoints, so none is tried. + + Attributes: + detail: Instagram's sanitized reason. + after: What created the checked session (``password login``, + ``session import``); ``None`` for the saved session. """ - def __init__(self, detail: str | None = None, retry_after: float | None = None) -> None: + def __init__( + self, + detail: str | None = None, + retry_after: float | None = None, + *, + after: str | None = None, + ) -> None: + self.detail = detail + self.after = after + if after is None: + message = ( + "Instagram did not confirm the saved session (throttled or unreachable). " + "No password login was attempted, the session file was kept and nothing " + "was lost; wait a while (ideally hours) before retrying." + ) + else: + message = ( + f"Instagram did not confirm the session after the {after} (throttled or " + "unreachable). Nothing was saved, the session file was kept and nothing " + "was lost; wait a while (ideally hours) before retrying." + ) + RateLimited.__init__(self, f"{message} ({detail})" if detail else message, retry_after) + + +class InstagramFeedUnavailable(RateLimited): + """Instagram refused the saved-feed request with a ``"fail"`` status. + + The answer (typically "We're sorry, but something went wrong") is about the + way the feed was requested, not about the login, so no password login is + attempted. With ``instagram.feed_api = "web"`` the session check itself is + the feed's first page, so it can also be raised by the check (then nothing + is saved). The page is not retried. A + :class:`RateLimited` subclass: like a throttle it means "stop now, retry + later", and everything committed so far is kept. + + Attributes: + feed_api: The ``instagram.feed_api`` that was used (``web``/``iphone``). + """ + + def __init__(self, feed_api: str, detail: str | None = None) -> None: + self.feed_api = feed_api + other = "iphone" if feed_api == "web" else "web" message = ( - "Instagram did not confirm the saved session (throttled or unreachable). " - "No password login was attempted, the session file was kept and nothing " - "was lost; wait a while (ideally hours) before retrying." + f"Instagram refused the saved feed ({feed_api} API)" + + (f': "{detail}"' if detail else "") + + ". The session is fine (no password login was attempted) and nothing stored " + f'was lost. Retry later, or set instagram.feed_api = "{other}" in the config.' ) - RateLimited.__init__(self, f"{message} ({detail})" if detail else message, retry_after) + super().__init__(message) class TelegramRateLimited(RateLimited): diff --git a/src/postparse/collectors/instagram/__init__.py b/src/postparse/collectors/instagram/__init__.py index e3696b9..fcf3bb9 100644 --- a/src/postparse/collectors/instagram/__init__.py +++ b/src/postparse/collectors/instagram/__init__.py @@ -3,7 +3,15 @@ from postparse.collectors.instagram.collector import ( InstagramCollector, InstagramOptions, + InvalidSessionCookie, + parse_sessionid, resolve_session_path, ) -__all__ = ["InstagramCollector", "InstagramOptions", "resolve_session_path"] +__all__ = [ + "InstagramCollector", + "InstagramOptions", + "InvalidSessionCookie", + "parse_sessionid", + "resolve_session_path", +] diff --git a/src/postparse/collectors/instagram/collector.py b/src/postparse/collectors/instagram/collector.py index fa166e0..a642a4c 100644 --- a/src/postparse/collectors/instagram/collector.py +++ b/src/postparse/collectors/instagram/collector.py @@ -1,7 +1,10 @@ """Incremental collector for the Instagram saved feed (instaloader). -The saved feed (private API ``api/v1/feed/saved/posts/``) is newest-first, -paginated with ``max_id``. The collector walks it and stops after +The saved feed (``api/v1/feed/saved/posts/``) is newest-first, paginated +with ``max_id``. It is requested the way the Instagram web app does it +(``www.instagram.com`` with web headers, ``instagram.feed_api = "web"``, +default) or through the private iPhone API (``i.instagram.com``, +``"iphone"``). The collector walks it and stops after ``stop_after_known`` consecutive posts that are already stored, so a routine run costs only a page or two of feed requests. New posts are mapped from the feed node itself (no per-post request), throttled with a jittered pause and @@ -11,10 +14,23 @@ pending-transcription media row is created (with the video URL only when the feed item already carries it). -The saved session is verified with a single request to the private user-info -endpoint (no legacy GraphQL ``query_hash``). Only a definitive "not logged in" -answer falls back to the password login; a throttled or failed check raises -:class:`InstagramSessionCheckFailed` and leaves the session file alone. +The saved session is verified with a single request (no legacy GraphQL +``query_hash``), over the same API as the feed: with ``feed_api = "web"`` the +first page of the saved feed, the request the web app itself makes when the +saved page is opened (the walk then starts with that page instead of asking for +it again, so a run whose first page is enough costs exactly one request); with +``"iphone"`` the user-info endpoint (``api/v1/users//info/``). +There is no automatic password login: without a usable session +:class:`InstagramAuthRequired` names the reason and points to the interactive +``postparse check instagram --import-session`` (the session of the user's +logged-in browser, :meth:`InstagramCollector.import_session`) or +``postparse check instagram --login`` (the only caller that sets +``allow_password_login``). A session is only saved after the check confirmed +it, also after a password login (instaloader may report a login without a +session cookie, instaloader issue #2487). A throttled or failed check raises +:class:`InstagramSessionCheckFailed` and leaves the session file alone. A feed +page that Instagram answers with a ``"fail"`` status is not retried: it raises +:class:`InstagramFeedUnavailable` (only network errors are retried). Example: >>> with InstagramCollector(db, settings, creds) as collector: @@ -24,12 +40,17 @@ from __future__ import annotations import logging +import re +import secrets +import string import time from collections.abc import Callable, Iterable, Iterator from dataclasses import dataclass from datetime import UTC, datetime +from functools import partial from pathlib import Path -from typing import Any +from typing import Any, Literal, cast +from urllib.parse import urlsplit from postparse.collectors.base import ( AuthRequired, @@ -37,6 +58,7 @@ CollectorError, CollectStats, InstagramAuthRequired, + InstagramFeedUnavailable, InstagramRateLimited, InstagramSessionCheckFailed, ProgressCallback, @@ -51,11 +73,15 @@ from postparse.core.text import extract_hashtags, extract_mentions __all__ = [ + "FEED_APIS", "LEGACY_SESSION_FILE", + "FeedApi", "InstagramCollector", "InstagramOptions", + "InvalidSessionCookie", "iter_saved_feed", "map_post", + "parse_sessionid", "post_from_iphone_media", "resolve_session_path", ] @@ -70,11 +96,27 @@ PostFromShortcode = Callable[[Any, str], Any] PromptFn = Callable[[str], str] -#: Private API (``i.instagram.com``) user info; also used by instaloader itself. +#: User info (session check with ``feed_api = "iphone"``, on ``i.instagram.com``). USER_INFO_PATH = "api/v1/users/{user_id}/info/" -#: Private API saved feed (all saved posts, newest saved first). +#: Saved feed (all saved posts, newest saved first); same path on both hosts. SAVED_FEED_PATH = "api/v1/feed/saved/posts/" +#: How the saved feed is requested: web REST API or private iPhone API. +FeedApi = Literal["web", "iphone"] +FEED_APIS: tuple[FeedApi, ...] = ("web", "iphone") + +WEB_HOST = "www.instagram.com" +#: Default ``Referer`` of web requests (the web app's start page). +WEB_REFERER = f"https://{WEB_HOST}/" +#: App id of the Instagram web app (``X-IG-App-ID``; instaloader sends the same). +WEB_APP_ID = "936619743392459" +#: ``X-ASBD-ID`` the web app sends (value as used by gallery-dl's REST client). +WEB_ASBD_ID = "129477" +#: Posts per web feed page (as gallery-dl requests the saved feed). +WEB_PAGE_SIZE = "50" +#: instaloader www default headers that the web app's REST calls do not send. +_WEB_DROP_HEADERS = ("X-Instagram-AJAX", "Content-Length") + #: ``media_type`` of private API media -> GraphQL ``__typename`` (as instaloader maps it). _IPHONE_MEDIA_TYPES: dict[int, str] = {1: "GraphImage", 2: "GraphVideo", 8: "GraphSidecar"} @@ -103,8 +145,15 @@ class InstagramOptions: refresh_min_delay: Lower bound of the pause between date refreshes. refresh_max_delay: Upper bound of the pause between date refreshes. request_timeout: instaloader request timeout (seconds). - max_connection_attempts: instaloader connection attempts. + max_connection_attempts: instaloader connection attempts (the session + check and feed pages use one attempt; feed pages retry only + network errors, up to this many attempts). user_agent: Custom user agent (``None``: instaloader default). + feed_api: ``"web"`` (``www.instagram.com`` REST API, like the web + app) or ``"iphone"`` (private API on ``i.instagram.com``). + + Raises: + ValueError: ``feed_api`` is not one of :data:`FEED_APIS`. """ min_delay: float = 5.0 @@ -114,6 +163,14 @@ class InstagramOptions: request_timeout: float = 30.0 max_connection_attempts: int = 3 user_agent: str | None = None + feed_api: FeedApi = "web" + + def __post_init__(self) -> None: + if self.feed_api not in FEED_APIS: + raise ValueError( + f"instagram.feed_api must be one of {', '.join(map(repr, FEED_APIS))} " + f"(got {self.feed_api!r})" + ) @classmethod def from_config(cls, config: Any) -> InstagramOptions: @@ -131,6 +188,9 @@ def from_config(cls, config: Any) -> InstagramOptions: _cfg(config, "instagram.max_connection_attempts", d.max_connection_attempts) ), user_agent=_cfg(config, "instagram.user_agent", None), + feed_api=cast( + FeedApi, str(_cfg(config, "instagram.feed_api", d.feed_api)).strip().lower() + ), ) @@ -186,33 +246,107 @@ def _default_loader_factory(options: InstagramOptions) -> Any: return instaloader.Instaloader(**kwargs) -def _default_saved_posts(loader: Any) -> Iterable[Any]: - """Iterate the logged-in user's saved posts (newest saved first).""" - return iter_saved_feed(loader.context) +def iter_saved_feed( + context: Any, + feed_api: FeedApi = "web", + username: str | None = None, + web: _WebClient | None = None, + first_page: dict[str, Any] | None = None, +) -> Iterator[Any]: + """Iterate the saved feed (newest saved first). + Pages of ``api/v1/feed/saved/posts/`` are requested lazily (``max_id`` = + previous ``next_max_id``), so a consumer that stops early costs no further + page request. instaloader's ``Profile.get_saved_posts()`` (4.15.5) still + uses a legacy GraphQL ``query_hash`` and needs ``Profile.own_profile()``, + which uses another one; Instagram answers that endpoint family with 401 + "Please wait a few minutes". -def iter_saved_feed(context: Any) -> Iterator[Any]: - """Iterate the saved feed through the private API (newest saved first). - - Pages of ``api/v1/feed/saved/posts/`` are requested lazily via - ``context.get_iphone_json`` (``max_id`` = previous ``next_max_id``), so a - consumer that stops early costs no further page request. instaloader's - ``Profile.get_saved_posts()`` (4.15.5) still uses a legacy GraphQL - ``query_hash`` and needs ``Profile.own_profile()``, which uses another one; - Instagram answers that endpoint family with 401 "Please wait a few minutes". + Each page gets one attempt (see :func:`_feed_page`). Args: - context: Logged-in ``InstaloaderContext`` (``user_id`` set). + context: Logged-in ``InstaloaderContext`` (``user_id`` set for ``iphone``). + feed_api: ``"web"``: ``www.instagram.com`` with the web app's REST + headers (see :class:`_WebClient`), with a web session the endpoint + Instagram's own web app uses; ``"iphone"``: ``i.instagram.com`` + through ``context.get_iphone_json`` (iPad headers). + username: Logged-in username (``Referer`` of web requests). + web: Web client to use (the collector's, shared with the session + check); ``None`` creates one for this walk. + first_page: Answer of the first page that was already requested + (the web session check's); the walk starts with it and requests + only the following pages (``max_id``). Yields: - instaloader ``Post`` objects built from the private API media structs. + instaloader ``Post`` objects built from the media structs (both APIs + answer ``items[].media`` with the same private-API media struct). + + Raises: + InstagramFeedUnavailable: Instagram answered a page with a ``"fail"`` + status (e.g. "something went wrong"). + InstagramRateLimited: Instagram throttled a page. + InstagramAuthRequired: The session was logged out or needs a confirmation. + ValueError: Unknown ``feed_api``. + """ + if feed_api not in FEED_APIS: + raise ValueError(f"unknown feed_api {feed_api!r}") + if feed_api == "iphone": + yield from _iter_feed_posts( + context, + feed_api, + lambda params: context.get_iphone_json(SAVED_FEED_PATH, params), + first_page, + ) + return + client = web if web is not None else _WebClient(context) + referer = _saved_page_referer(username) + try: + yield from _iter_feed_posts( + context, + feed_api, + lambda params: client.get(SAVED_FEED_PATH, params, referer=referer), + first_page, + ) + finally: + if web is None: + client.close() + + +def _saved_page_referer(username: str | None) -> str: + """``Referer`` of saved-feed requests: the user's saved page (web app URL).""" + return f"https://{WEB_HOST}/{username}/saved/all-posts/" if username else WEB_REFERER + + +def _feed_params(feed_api: FeedApi, max_id: str | None = None) -> dict[str, Any]: + """Query parameters of a saved-feed page (``max_id``: cursor of a later page).""" + params: dict[str, Any] = ( + {"count": WEB_PAGE_SIZE} if feed_api == "web" else {"include_igtv_preview": "false"} + ) + if max_id: + params["max_id"] = max_id + return params + + +def _iter_feed_posts( + context: Any, + feed_api: FeedApi, + fetch: Callable[[dict[str, Any]], Any], + first_page: dict[str, Any] | None = None, +) -> Iterator[Any]: + """Walk the feed pages (``fetch(params) -> page``) and yield posts. + + ``first_page`` (already requested) replaces the request of page 1. """ max_id: str | None = None + pending = first_page while True: - params: dict[str, Any] = {"include_igtv_preview": "false"} - if max_id: - params["max_id"] = max_id - data = context.get_iphone_json(SAVED_FEED_PATH, params) + if pending is not None: + data: Any = pending + pending = None + else: + data = _feed_page(context, feed_api, partial(fetch, _feed_params(feed_api, max_id))) + if not isinstance(data, dict): + return items = data.get("items") or [] for item in items: media = item.get("media", item) if isinstance(item, dict) else None @@ -227,6 +361,243 @@ def iter_saved_feed(context: Any) -> Iterator[Any]: max_id = str(next_max_id) +def _feed_page(context: Any, feed_api: FeedApi, call: Callable[[], Any]) -> Any: + """Request one feed page with instaloader's own retries disabled. + + instaloader retries every failed JSON query ``max_connection_attempts`` + times, including a 200 answer with ``"status": "fail"`` that will not + change on a retry. Here a page gets one attempt; only network errors + (timeouts, connection resets) are retried, up to the configured attempts. + Instagram's answers are translated: throttle -> :class:`InstagramRateLimited`, + logout/checkpoint -> :class:`InstagramAuthRequired`, any other ``"fail"`` + status -> :class:`InstagramFeedUnavailable`; other errors are re-raised. + """ + configured = context.max_connection_attempts + attempts = max(1, int(configured or 1)) + context.max_connection_attempts = 1 + try: + attempt = 1 + while True: + try: + return call() + except Exception as exc: + if attempt < attempts and _is_network_error(exc): + attempt += 1 + logger.warning( + "Instagram saved feed: network error (%s); attempt %d/%d", + type(exc).__name__, + attempt, + attempts, + ) + continue + translated = _feed_error(exc, feed_api) + if translated is exc: + raise + raise translated from exc + finally: + context.max_connection_attempts = configured + + +def _is_network_error(exc: BaseException) -> bool: + """True if ``exc`` is (or wraps) a ``requests`` transport error.""" + import requests + + seen: BaseException | None = exc + for _ in range(5): + if seen is None: + return False + if isinstance(seen, requests.exceptions.RequestException): + return True + seen = seen.__cause__ + return False + + +#: Feed answers that are a refusal (checked after throttle/logout markers). +_FEED_FAIL_MARKERS = ('"fail" status', "something went wrong") + + +def _feed_error(exc: BaseException, feed_api: FeedApi) -> BaseException: + """Translate a failed feed page request (see :func:`_feed_page`).""" + translated = translate_error(exc) + if translated is not exc: + return translated + text = _marker_text(str(exc)) + if type(exc).__name__ == "ConnectionException" and any(m in text for m in _FEED_FAIL_MARKERS): + return InstagramFeedUnavailable(feed_api, _instagram_message(str(exc))) + return exc + + +#: Longest Instagram reason quoted in messages (characters). +MAX_REASON_LENGTH = 200 +_URL_RE = re.compile(r"https?://[^\s\"'<>]+", re.IGNORECASE) +#: instaloader's request prefix (``JSON Query to : ``); the path carries ids. +_QUERY_PREFIX_RE = re.compile(r"^\s*JSON Query to \S+:\s*", re.IGNORECASE) +#: ``message "..."`` (instaloader) or ``"message": "..."`` (JSON body of a fatal status). +_MESSAGE_RES = ( + re.compile(r'message "([^"]*)"'), + re.compile(r'"message"\s*:\s*"([^"]*)"'), +) +_REDIRECT_RE = re.compile(r"redirect(?:ed)? to (https?://[^\s\"'<>]+)", re.IGNORECASE) +#: ``name=value`` / ``"name": "value"`` pairs that must never be shown (cookies, +#: tokens, passwords). +_SECRET_RE = re.compile( + r"(?i)\b(sessionid|csrftoken|ds_user_id|mid|ig_did|rur|shbid|shbts|" + r"[\w-]*token[\w-]*|[\w-]*passw\w*|enc_password|cookie|authorization)[\"']?\s*[=:]\s*" + r"[\"']?[^\s;,&\"']+" +) +#: A bare ``sessionid`` value (``%3A...``, also URL-decoded with ``:``). +_SESSIONID_VALUE_RE = re.compile(r"(?i)\b\d+(?:%3A|:)[A-Za-z0-9%:_-]{8,}") +#: HTTP status 429 as a word (applied to the text without URLs and request paths). +_HTTP_429_RE = re.compile(r"(? str: + """``scheme://host/path`` of ``url`` (query string and fragment removed).""" + parts = urlsplit(url) + return f"{parts.scheme}://{parts.netloc}{parts.path}" + + +def _error_head(text: str) -> str: + """The error text before instaloader's `` when accessing `` tail.""" + return text.split(" when accessing ", 1)[0] + + +def _marker_text(text: str) -> str: + """Lower-case error text for marker checks. + + The request URL (`` when accessing ...``) is dropped and other URLs are + reduced to ``scheme://host/path``, so cursor ids, user ids and query + parameters cannot match a marker. + """ + return _URL_RE.sub(lambda m: _strip_url(m.group(0)), _error_head(text)).lower() + + +def _is_http_429(text: str) -> bool: + """True if the error text reports HTTP 429 (never matched inside URLs or paths).""" + head = _QUERY_PREFIX_RE.sub("", _URL_RE.sub(" ", _error_head(text))) + return bool(_HTTP_429_RE.search(head)) + + +def _instagram_message(text: str) -> str: + """Instagram's short reason from an instaloader error text (sanitized). + + Returns the ``message "..."`` part (e.g. ``checkpoint_required``, + ``login_required``), for a login redirect the redirect target as + ``scheme://host/path``, otherwise the error text without the request URL. + Query strings, fragments and ``name=value`` secrets (cookies, tokens, + passwords) are removed; the result is at most :data:`MAX_REASON_LENGTH` + characters. + """ + reason: str | None = None + for pattern in _MESSAGE_RES: + match = pattern.search(text) + if match and match.group(1).strip(): + reason = match.group(1).strip() + break + if reason is None: + redirect = _REDIRECT_RE.search(text) + if redirect: + reason = f"redirect to {_strip_url(redirect.group(1))}" + elif "redirected to login page" in text.lower(): + reason = "redirected to login page" + else: + head = _error_head(text) + head = head.split(": {", 1)[0] # no JSON response body + reason = _QUERY_PREFIX_RE.sub("", head).strip() + reason = _URL_RE.sub(lambda m: _strip_url(m.group(0)), reason) + reason = _SECRET_RE.sub(lambda m: f"{m.group(1)}=", reason) + reason = _SESSIONID_VALUE_RE.sub("", reason) + reason = " ".join(reason.split()) + if len(reason) > MAX_REASON_LENGTH: + reason = reason[: MAX_REASON_LENGTH - 1].rstrip() + "…" + return reason + + +class _WebClient: + """Requests to ``www.instagram.com`` as the Instagram web app makes them. + + Used for the saved feed and for the session check (``feed_api = "web"``, + the feed's first page), so a run talks to Instagram with one client + identity, and a browser session is never sent with iPad headers to + ``i.instagram.com``. + + Uses a temporary copy of instaloader's session (``copy_session``, as + ``get_iphone_json`` does), so the loaded cookies, instaloader's www + defaults (``User-Agent``, ``Origin``, ``Accept-Language``) and its rate + controller and error handling (``context.get_json``) stay in use; the main + session is not changed. The copy follows the context: when instaloader + replaces its session (password login, imported session), a new copy is + made. On top, the web app's REST headers are sent (``X-IG-App-ID``, + ``X-ASBD-ID``, ``X-Requested-With``, ``Sec-Fetch-*``, a ``Referer``). Each + request takes ``X-CSRFToken`` from the current ``csrftoken`` cookie and + sends the last ``x-ig-set-www-claim`` the server handed out as + ``X-IG-WWW-Claim`` (``"0"`` before), like the web app and gallery-dl's REST + client do. + + Args: + context: instaloader context (its ``_session`` holds the cookies). + referer: Default ``Referer`` (the web app's start page). + """ + + def __init__(self, context: Any, referer: str = WEB_REFERER) -> None: + self.context = context + self.referer = referer + self.www_claim = "0" + self.session: Any = None + self._source: Any = None + + def _session(self) -> Any: + source = self.context._session + if self.session is None or self._source is not source: + from instaloader.instaloadercontext import copy_session + + self.close() + session = copy_session(source, self.context.request_timeout) + for header in _WEB_DROP_HEADERS: + session.headers.pop(header, None) + session.headers.update( + { + "Accept": "*/*", + "Origin": f"https://{WEB_HOST}", + "X-ASBD-ID": WEB_ASBD_ID, + "X-IG-App-ID": WEB_APP_ID, + "X-Requested-With": "XMLHttpRequest", + "Sec-Fetch-Dest": "empty", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Site": "same-origin", + } + ) + self.session = session + self._source = source + self.www_claim = "0" # the claim belongs to the session + return self.session + + def get(self, path: str, params: dict[str, Any], *, referer: str | None = None) -> Any: + """GET ``https://www.instagram.com/`` (JSON) with the web headers.""" + session = self._session() + session.headers["Referer"] = referer or self.referer + session.headers["X-CSRFToken"] = str(session.cookies.get_dict().get("csrftoken") or "") + session.headers["X-IG-WWW-Claim"] = self.www_claim + response_headers: dict[str, Any] = {} + data = self.context.get_json( + path, + params, + host=WEB_HOST, + session=session, + response_headers=response_headers, + ) + for key, value in response_headers.items(): + if key.lower() == "x-ig-set-www-claim" and value: + self.www_claim = str(value) + return data + + def close(self) -> None: + if self.session is not None: + self.session.close() + self.session = None + self._source = None + + def post_from_iphone_media(context: Any, media: dict[str, Any]) -> Any: """Build an instaloader ``Post`` from a private API media struct. @@ -449,27 +820,42 @@ def _video_media(position: int, node: dict[str, Any]) -> MediaInput: "feedback_required", "login_required", "redirected to login page", + "instagram.com/accounts/login", ) -_RATE_MARKERS = ("429", "too many requests", "please wait a few minutes", "rate limit") -#: Session-check answers that are throttles (checked first; no bare "429": URLs carry ids). +#: Throttle answers (an HTTP 429 status is detected separately, see :func:`_is_http_429`). +_RATE_MARKERS = ("too many requests", "please wait a few minutes", "rate limit") +#: Session-check answers that are throttles (checked first; markers never match URL text). _THROTTLE_MARKERS = ("too many requests", "please wait a few minutes", "rate limit", "401 ") #: Session-check answers that positively mean "this session is not logged in". -_LOGGED_OUT_MARKERS = ("login_required", "redirected to login page", "require_login") +_LOGGED_OUT_MARKERS = ( + "login_required", + "redirected to login page", + "require_login", + "instagram.com/accounts/login", +) #: Session-check answers that need the user (a password login would not help). _USER_ACTION_MARKERS = ("checkpoint", "challenge", "feedback_required") def translate_error(exc: BaseException) -> BaseException: - """Map instaloader exceptions to collector errors (others are returned as-is).""" + """Map instaloader exceptions to collector errors (others are returned as-is). + + Markers are matched only against the error text without the request URL + (see :func:`_marker_text`), so ids in URLs (``max_id=...3429...``) cannot + turn a refusal into a rate limit. The collector errors carry Instagram's + sanitized reason (:func:`_instagram_message`). + """ if isinstance(exc, CollectorError): return exc name = type(exc).__name__ - text = str(exc).lower() + raw = str(exc) + text = _marker_text(raw) + reason = _instagram_message(raw) if raw else None if name == "TooManyRequestsException" or ( name in ("ConnectionException", "QueryReturnedBadRequestException") - and any(marker in text for marker in _RATE_MARKERS) + and (_is_http_429(raw) or any(marker in text for marker in _RATE_MARKERS)) ): - return InstagramRateLimited(str(exc) or None) + return InstagramRateLimited(reason) if name == "TwoFactorAuthRequiredException": return InstagramAuthRequired("Two-factor code required.") if name == "BadCredentialsException": @@ -484,7 +870,10 @@ def translate_error(exc: BaseException) -> BaseException: ) and any(marker in text for marker in _CHALLENGE_MARKERS) ): - return InstagramAuthRequired("Instagram requires a confirmation or a new login.") + return InstagramAuthRequired( + "Instagram requires a confirmation or a new login" + + (f" (Instagram: {reason})." if reason else ".") + ) return exc @@ -498,8 +887,12 @@ def _session_check_verdict(exc: BaseException) -> str: name = type(exc).__name__ if name == "LoginRequiredException": return "logged_out" - text = str(exc).lower() - if name == "TooManyRequestsException" or any(m in text for m in _THROTTLE_MARKERS): + text = _marker_text(str(exc)) + if ( + name == "TooManyRequestsException" + or _is_http_429(str(exc)) + or any(m in text for m in _THROTTLE_MARKERS) + ): return "failed" if any(marker in text for marker in _USER_ACTION_MARKERS): return "user_action" @@ -517,6 +910,85 @@ def _session_cookies(loader: Any) -> dict[str, Any]: return cookies if isinstance(cookies, dict) else {} +def _has_login_cookies(cookies: dict[str, Any]) -> bool: + """True if ``cookies`` carry a ``sessionid`` and a numeric ``ds_user_id``.""" + return bool(cookies.get("sessionid")) and str(cookies.get("ds_user_id") or "").isdigit() + + +def _drop_placeholder_cookies(jar: Any) -> int: + """Remove instaloader's empty placeholder cookies from ``jar``. + + ``InstaloaderContext.login`` puts ``sessionid``, ``mid``, ``csrftoken``, + ``s_network`` and ``ds_user_id`` with empty values (and no domain) into a + fresh jar before logging in. Cookies Instagram sets carry a domain, so a + cookie with an empty value and no domain is such a placeholder; it would + hide a missing (or shadow a real) login cookie. Everything else (also + ``ig_pr="1"`` and the like) is kept. + + Returns: + Number of removed cookies. + """ + placeholders = [c for c in list(jar) if not c.value and not c.domain] + for cookie in placeholders: + jar.clear(cookie.domain, cookie.path, cookie.name) + return len(placeholders) + + +class InvalidSessionCookie(ValueError): + """A pasted cookie value does not have the expected shape (the value is never shown).""" + + +#: ``sessionid`` cookie as the browser stores it: ``%3A``. +_SESSIONID_RE = re.compile(r"^(\d+)%3A[^\s;,\"']+$", re.IGNORECASE) +_CSRFTOKEN_RE = re.compile(r"^[A-Za-z0-9_-]+$") +#: Length of a generated ``csrftoken`` (as Instagram's). +CSRFTOKEN_LENGTH = 32 + + +def _strip_cookie_value(value: str) -> str: + """``value`` without surrounding whitespace and quotes.""" + return value.strip().strip("\"'").strip() + + +def parse_sessionid(value: str) -> tuple[str, str]: + """Normalize a ``sessionid`` cookie copied from the browser. + + Whitespace and surrounding quotes are removed and ``:`` is encoded as + ``%3A`` (the browser's developer tools show the URL-encoded value; a + decoded copy is accepted as well). + + Args: + value: Pasted cookie value. + + Returns: + ``(sessionid, ds_user_id)``; the user id is the leading number. + + Raises: + InvalidSessionCookie: Not shaped like ``%3A...`` (the message + never contains the value). + """ + sessionid = _strip_cookie_value(value).replace(":", "%3A") + match = _SESSIONID_RE.match(sessionid) + if match is None: + raise InvalidSessionCookie( + "The value does not look like an Instagram sessionid cookie (expected %3A…)." + ) + return sessionid, match.group(1) + + +def _csrftoken(value: str | None) -> str: + """The pasted ``csrftoken`` (normalized), or a newly generated one when empty.""" + token = _strip_cookie_value(value or "") + if not token: + alphabet = string.ascii_letters + string.digits + return "".join(secrets.choice(alphabet) for _ in range(CSRFTOKEN_LENGTH)) + if not _CSRFTOKEN_RE.match(token): + raise InvalidSessionCookie( + "The value does not look like an Instagram csrftoken cookie (letters and digits)." + ) + return token + + # --------------------------------------------------------------------------- # Collector # --------------------------------------------------------------------------- @@ -525,8 +997,16 @@ def _session_cookies(loader: Any) -> dict[str, Any]: class InstagramCollector: """Collect saved Instagram posts into the schema v2 database. - Use as a context manager: entering loads/validates the session (logging in - if needed), leaving saves the session. + Use as a context manager: entering loads/validates the session, leaving + saves the session. + + A password login is never automatic: scripted password logins are what + makes Instagram ask for checkpoints. Without a usable session the collector + raises :class:`InstagramAuthRequired` unless ``allow_password_login`` is set, + which only the interactive ``postparse check instagram --login`` does. The + recommended way to create a session is :meth:`import_session` (the browser's + ``sessionid`` cookie, ``postparse check instagram --import-session``). New + sessions are saved only after the session check confirmed them. Args: db: Target database. @@ -536,11 +1016,19 @@ class InstagramCollector: interactive: Allow prompting for a two-factor code; otherwise a 2FA challenge raises :class:`InstagramAuthRequired`. session: ``--session`` override (file path). + allow_password_login: Fall back to the password login when there is + no usable session (only for the interactive + ``postparse check instagram --login``; default ``False``). loader_factory: Creates the instaloader instance (tests pass a fake). - saved_posts: Returns the saved-post iterator for a loader. + saved_posts: Returns the saved-post iterator for a loader (default: + :func:`iter_saved_feed` with ``options.feed_api``). post_from_shortcode: Fetches one post (``refresh_dates``). prompt: Reads the 2FA code in interactive mode (default ``input``). sleep: Sleep function (tests pass a no-op). + progress: Receives the session outcome while logging in (phase + ``session``: saved session verified; phase ``login``: password + login about to start, only with ``allow_password_login``); no + secrets in the messages. """ def __init__( @@ -552,135 +1040,272 @@ def __init__( *, interactive: bool = True, session: str | Path | None = None, + allow_password_login: bool = False, loader_factory: LoaderFactory | None = None, saved_posts: SavedPostsFn | None = None, post_from_shortcode: PostFromShortcode | None = None, prompt: PromptFn | None = None, sleep: Callable[[float], Any] = time.sleep, + progress: ProgressCallback | None = None, ) -> None: self.db = db self.settings = settings self.credentials = credentials self.options = options or InstagramOptions() self.interactive = interactive + self.allow_password_login = allow_password_login self.load_path, self.save_path = resolve_session_path( settings, credentials.username, session ) self._loader_factory = loader_factory or _default_loader_factory - self._saved_posts = saved_posts or _default_saved_posts + self._saved_posts = saved_posts or self._default_saved_posts self._post_from_shortcode = post_from_shortcode or _default_post_from_shortcode self._prompt = prompt or input self._sleep = sleep + self._progress = progress self.loader: Any = None self.logged_in = False self.stats = CollectStats(source="instagram") + self._web: _WebClient | None = None + #: ``(context session, page)``: first saved-feed page of the web session check. + self._first_feed_page: tuple[Any, dict[str, Any]] | None = None + + def _default_saved_posts(self, loader: Any) -> Iterable[Any]: + """The saved feed through the configured ``feed_api``. + + The walk of :attr:`loader` starts with the first page the web session + check already fetched (see :meth:`_take_first_feed_page`). + """ + own = loader is self.loader + return iter_saved_feed( + loader.context, + self.options.feed_api, + self.credentials.username, + web=self._web_client() if own else None, + first_page=self._take_first_feed_page() if own else None, + ) + + def _take_first_feed_page(self) -> dict[str, Any] | None: + """Hand out (once) the first feed page of the current session's check. + + The page belongs to the session it was fetched with: when the loader's + session was replaced since (password login, imported session), it is + dropped and the walk requests page 1 itself. + """ + cached, self._first_feed_page = self._first_feed_page, None + if cached is None or self.loader is None: + return None + source, page = cached + if getattr(self.loader.context, "_session", None) is not source: + return None + return page + + def _web_client(self) -> _WebClient: + """The web client of this collector (session check and feed share it).""" + context = self.loader.context + if self._web is None or self._web.context is not context: + self._close_web() + self._web = _WebClient(context) + return self._web + + def _close_web(self) -> None: + if self._web is not None: + self._web.close() + self._web = None # -- session --------------------------------------------------------- + def _session_event(self, phase: str, message: str) -> None: + """Report the session outcome (``session`` / ``login``) to the progress callback.""" + emit(self._progress, self.stats, phase=phase, seen=0, message=message) + def __enter__(self) -> InstagramCollector: self.login() return self def __exit__(self, *exc_info: object) -> None: - self.save_session() + try: + self.save_session() + finally: + self._first_feed_page = None + self._close_web() def login(self) -> None: - """Load the saved session or log in. + """Load and verify the saved session. - The password login (when ``INSTAGRAM_PASSWORD`` is set) is only tried - when there is no session file or the session check positively shows - that the session is not logged in (see :meth:`_check_session`). + Without a usable session (no file, unreadable file, or the session + check positively shows that it is not logged in) a password login is + only tried when ``allow_password_login`` is set and + ``INSTAGRAM_PASSWORD`` is configured; otherwise + :class:`InstagramAuthRequired` names the reason and the way to log in. Raises: - InstagramAuthRequired: No valid session and the login failed or - needs user interaction that is not allowed; or Instagram asks - for a confirmation (checkpoint). + InstagramAuthRequired: No usable session and no password login + allowed (or possible), the login failed or needs user + interaction that is not allowed, or Instagram asks for a + confirmation (checkpoint). InstagramSessionCheckFailed: The session check was throttled or failed; no password login was attempted. + InstagramFeedUnavailable: (web) Instagram refused the saved-feed + page of the session check with a ``"fail"`` status. InstagramRateLimited: Instagram rate-limited the login. """ self.loader = self._loader_factory(self.options) + self._first_feed_page = None username = self.credentials.username if self.load_path.exists(): logger.info("Loading Instagram session from %s", self.load_path) - valid = False + logged_out: str | None try: self.loader.load_session_from_file(username, str(self.load_path)) except Exception as exc: logger.warning("Instagram session file could not be read: %s", type(exc).__name__) + logged_out = "session file unreadable" else: - valid = self._check_session() - if valid: + logged_out = self._check_session() + if logged_out is None: self.logged_in = True logger.info("Instagram session is valid") + self._session_event("session", "Instagram session verified (no password login)") return - logger.info("Instagram session is not logged in") + why = logged_out + logger.info("Instagram session is not usable (%s)", why) else: logger.info("No Instagram session file at %s", self.load_path) + why = "no session file" + if not self.allow_password_login: + raise InstagramAuthRequired( + f"No password login was attempted ({why}); automatic password logins " + "are disabled because they trigger Instagram checkpoints." + ) if not self.credentials.password: - raise InstagramAuthRequired("No valid session and INSTAGRAM_PASSWORD is not set.") - logger.info("Falling back to the Instagram password login") + raise InstagramAuthRequired( + f"No valid session ({why}) and INSTAGRAM_PASSWORD is not set." + ) + logger.info("Falling back to the Instagram password login (%s)", why) + self._session_event( + "login", + f"No usable Instagram session ({why}); logging in with the password now", + ) self._password_login() - def _check_session(self) -> bool: + def _check_session(self) -> str | None: """Verify the loaded session with at most one request. The ``sessionid`` / ``ds_user_id`` cookies are checked locally first - (missing: not logged in, no request). Then the private user-info - endpoint (``api/v1/users//info/``) is asked once, with - ``max_connection_attempts`` temporarily set to 1. instaloader's - ``test_login()`` is not used: it queries a legacy GraphQL - ``query_hash`` and turns every error (including throttles) into - "not logged in". + (missing: not logged in, no request). Then Instagram is asked once, + with ``max_connection_attempts`` temporarily set to 1, over the API the + feed uses, so a run has one client identity and a browser session is + never sent with iPad headers to ``i.instagram.com``: + + * ``feed_api = "web"``: the first page of the saved feed + (``api/v1/feed/saved/posts/``), exactly as the walk requests it + (:class:`_WebClient`, ``Referer`` = the saved page). The Instagram + web app makes this request itself when the saved page is opened; + the user-info endpoint it does not normally call (Instagram answered + a fresh import there with 429). The page is kept for the walk + (:meth:`_take_first_feed_page`), so it is not requested twice. The + feed does not name the viewer, so the account cannot be compared + with :attr:`credentials`: it is the account the ``sessionid`` + belongs to (its leading number is ``ds_user_id``). + * ``"iphone"``: the user-info endpoint + (``api/v1/users//info/``) through ``get_iphone_json``; + a session of another account than :attr:`credentials` ``.username`` + is not usable. + + instaloader's ``test_login()`` is not used: it queries a legacy GraphQL + ``query_hash`` and turns every error (including throttles) into "not + logged in". Returns: - ``True`` if the session is usable, ``False`` if it is positively - not logged in (or belongs to another account). + ``None`` if the session is usable, otherwise why it is positively + not logged in (e.g. ``session logged out: login_required``, + Instagram's sanitized reason). Raises: InstagramAuthRequired: Instagram asks for a confirmation. + InstagramFeedUnavailable: (web) Instagram answered the feed page + with a ``"fail"`` status that is not about the session (e.g. + "something went wrong"). InstagramSessionCheckFailed: Throttled, unreachable or unknown error. """ + self._first_feed_page = None cookies = _session_cookies(self.loader) - user_id = str(cookies.get("ds_user_id") or "") - if not cookies.get("sessionid") or not user_id.isdigit(): + if not _has_login_cookies(cookies): logger.info("Instagram session file has no login cookies") - return False + return "session logged out: the session file has no login cookies" + user_id = str(cookies["ds_user_id"]) context = self.loader.context context.user_id = int(user_id) # sent as ig-intended-user-id by get_iphone_json + web = self.options.feed_api == "web" attempts = context.max_connection_attempts context.max_connection_attempts = 1 try: - data = context.get_iphone_json(USER_INFO_PATH.format(user_id=user_id), {}) + if web: + data = self._web_client().get( + SAVED_FEED_PATH, + _feed_params("web"), + referer=_saved_page_referer(self.credentials.username), + ) + else: + data = context.get_iphone_json(USER_INFO_PATH.format(user_id=user_id), {}) except Exception as exc: verdict = _session_check_verdict(exc) + reason = _instagram_message(str(exc)) or type(exc).__name__ if verdict == "logged_out": - logger.info("Instagram session check: not logged in (%s)", type(exc).__name__) - return False + logger.info("Instagram session check: not logged in (%s)", reason) + return f"session logged out: {reason}" if verdict == "user_action": - logger.warning("Instagram session check: confirmation required") + logger.warning("Instagram session check: confirmation required (%s)", reason) raise InstagramAuthRequired( - "Instagram asks for a confirmation of the saved session." + f"Instagram asks for a confirmation of the saved session (Instagram: {reason})." ) from exc + if web: + refused = _feed_error(exc, "web") + if isinstance(refused, InstagramFeedUnavailable): + logger.warning("Instagram refused the saved feed in the session check") + raise refused from exc logger.warning( - "Instagram session check failed (%s); no password login attempted", - type(exc).__name__, + "Instagram session check failed (%s); no password login attempted", reason ) - raise InstagramSessionCheckFailed(str(exc) or type(exc).__name__) from exc + raise InstagramSessionCheckFailed(reason) from exc finally: context.max_connection_attempts = attempts + if web: + self._keep_first_feed_page(data) + return None user = data.get("user") if isinstance(data, dict) else None current = user.get("username") if isinstance(user, dict) else None if not isinstance(current, str) or not current: logger.warning("Instagram session check returned no username; using the session") - return True + return None if current.lower() != self.credentials.username.lower(): logger.info("Instagram session belongs to another account") - return False - return True + return "session logged out: the session belongs to another account" + return None + + def _keep_first_feed_page(self, data: Any) -> None: + """Accept the saved-feed answer of the web session check and keep it for the walk. + + Raises: + InstagramSessionCheckFailed: The answer is not a feed page (it + says nothing about the session). + """ + if not isinstance(data, dict) or not ( + data.get("status") == "ok" or isinstance(data.get("items"), list) + ): + logger.warning("Instagram session check: unexpected saved-feed answer") + raise InstagramSessionCheckFailed("unexpected answer to the saved-feed request") + self._first_feed_page = (self.loader.context._session, data) def _password_login(self) -> None: - """Log in with the password (and a 2FA code when interactive).""" + """Log in with the password (and a 2FA code when interactive). + + The new session is saved only after it was verified (see + :meth:`_verify_new_session`): instaloader reports a login as soon as + Instagram answers ``authenticated: true``, even when no ``sessionid`` + cookie came back (instaloader issue #2487). + """ assert self.credentials.password is not None logger.info("Logging in to Instagram as %s", self.credentials.username) try: @@ -697,8 +1322,99 @@ def _password_login(self) -> None: self.loader.two_factor_login(code) except Exception as exc2: raise translate_error(exc2) from exc2 + self._verify_new_session("password login") + self.logged_in = True + self.save_session() + + def _verify_new_session(self, origin: str) -> None: + """Verify a session that a password login just created (nothing is saved). + + instaloader's empty placeholder cookies are removed first (see + :func:`_drop_placeholder_cookies`); without real login cookies no + request is made. Then :meth:`_check_session` asks Instagram once. + + Args: + origin: What created the session (``password login``), for messages. + + Raises: + InstagramAuthRequired: No session cookie, or the check says the + session is not usable (or asks for a confirmation). + InstagramSessionCheckFailed: The check was throttled or failed. + """ + session = getattr(self.loader.context, "_session", None) + if session is not None: + dropped = _drop_placeholder_cookies(session.cookies) + logger.debug("Removed %d placeholder cookies after the %s", dropped, origin) + if not _has_login_cookies(_session_cookies(self.loader)): + logger.warning("Instagram %s returned no session cookie (instaloader #2487)", origin) + raise InstagramAuthRequired( + "Instagram accepted the password but returned no session cookie " + "(instaloader issue #2487); nothing was saved." + ) + reason = self._check_after(origin) + if reason is not None: + logger.warning("Instagram session check after the %s failed (%s)", origin, reason) + raise InstagramAuthRequired( + f"Instagram accepted the password, but the session check after the {origin} " + f"failed ({reason}); nothing was saved." + ) + + def _check_after(self, origin: str) -> str | None: + """:meth:`_check_session` for a new session (a failed check names ``origin``).""" + try: + return self._check_session() + except InstagramSessionCheckFailed as exc: + raise InstagramSessionCheckFailed(exc.detail, exc.retry_after, after=origin) from exc + + def import_session(self, sessionid: str, csrftoken: str | None = None) -> None: + """Import the session of the user's logged-in browser and verify it. + + Never uses the password and never falls back to a password login. The + ``sessionid`` cookie is normalized (:func:`parse_sessionid`; its + leading number is the ``ds_user_id``), loaded into a fresh instaloader + session (``Instaloader.load_session``) and verified with + :meth:`_check_session` (exactly one request; with ``feed_api = + "web"`` the first saved-feed page, kept for the walk). Only a confirmed + session is saved (the session file is overwritten only then). In web + mode the account is the one the ``sessionid`` belongs to (the feed + does not name the viewer); with ``"iphone"`` a session of another + account than :attr:`credentials` ``.username`` is rejected. + + Args: + sessionid: ``sessionid`` cookie value copied from the browser. + csrftoken: ``csrftoken`` cookie value; empty or ``None`` generates + a random one. + + Raises: + InvalidSessionCookie: A value is not shaped like the cookie (no + request was made). + InstagramAuthRequired: The session is not usable (logged out, + another account) or Instagram asks for a confirmation; + nothing was saved. + InstagramFeedUnavailable: (web) Instagram answered the feed page + with a ``"fail"`` status; nothing was saved. + InstagramSessionCheckFailed: The check was throttled or failed; + nothing was saved. + """ + value, user_id = parse_sessionid(sessionid) + token = _csrftoken(csrftoken) + self.logged_in = False + self.loader = self._loader_factory(self.options) + self._first_feed_page = None + username = self.credentials.username + logger.info("Importing the browser session of Instagram user %s", username) + self.loader.load_session( + username, {"sessionid": value, "ds_user_id": user_id, "csrftoken": token} + ) + reason = self._check_after("session import") + if reason is not None: + logger.warning("Imported Instagram session is not usable (%s)", reason) + raise InstagramAuthRequired( + f"The imported session is not usable ({reason}); nothing was saved." + ) self.logged_in = True self.save_session() + self._session_event("session", "Browser session imported and verified (no password login)") def save_session(self) -> None: """Save the session file (only when logged in).""" @@ -767,6 +1483,8 @@ def collect_saved( Raises: InstagramRateLimited: Instagram rate-limited the feed (completed and pending batches are kept). + InstagramFeedUnavailable: Instagram refused a feed page with a + ``"fail"`` status (completed and pending batches are kept). InstagramAuthRequired: The session became invalid during the run. """ self._require_login() @@ -808,7 +1526,9 @@ def collect_saved( except Exception: logger.exception("Could not write the last Instagram batch") translated = translate_error(exc) if isinstance(exc, Exception) else exc - if isinstance(translated, InstagramRateLimited): + if isinstance(translated, InstagramFeedUnavailable): + stats.stopped_reason = "feed_unavailable" + elif isinstance(translated, InstagramRateLimited): stats.stopped_reason = "rate_limited" elif isinstance(translated, AuthRequired): stats.stopped_reason = "auth_required" diff --git a/src/postparse/services/extraction.py b/src/postparse/services/extraction.py index 78a3b52..4d570c2 100644 --- a/src/postparse/services/extraction.py +++ b/src/postparse/services/extraction.py @@ -25,6 +25,7 @@ from postparse.collectors.base import ( AuthRequired, CollectStats, + InstagramFeedUnavailable, ProgressCallback, RateLimited, StopReason, @@ -54,8 +55,9 @@ class ExtractionReport: last_external_id: Last committed item (how far the run got). errors: Non-fatal per-item problems plus the fatal error, if any. stopped_reason: ``early_stop``, ``limit``, ``end_of_feed``, - ``rate_limited`` or ``auth_required`` (``None`` after an - unexpected error). + ``rate_limited``, ``auth_required`` or ``feed_unavailable`` + (Instagram refused the saved feed; ``None`` after an unexpected + error). error: Message of the error that ended the run, if any. duration_s: Wall-clock duration in seconds. """ @@ -242,7 +244,10 @@ def instagram( InstagramOptions.from_config(self.config), interactive=interactive, session=session, - **self.instagram_overrides, + # Collection never logs in with the password (Instagram checkpoints); + # only `postparse check instagram --login` does, interactively + # (`--import-session` takes the browser session instead). + **{"progress": progress, **self.instagram_overrides, "allow_password_login": False}, ) with collector: collector.collect_saved( @@ -272,7 +277,12 @@ def _failed( if stats is not None else ExtractionReport(source=source, duration_s=duration) ) - report.stopped_reason = "rate_limited" if isinstance(exc, RateLimited) else "auth_required" + if isinstance(exc, InstagramFeedUnavailable): + report.stopped_reason = "feed_unavailable" + elif isinstance(exc, RateLimited): + report.stopped_reason = "rate_limited" + else: + report.stopped_reason = "auth_required" report.error = str(exc) report.errors.append(str(exc)) logger.warning("%s extraction stopped: %s", source, exc) diff --git a/src/postparse/services/transcription.py b/src/postparse/services/transcription.py index fff0854..895af2d 100644 --- a/src/postparse/services/transcription.py +++ b/src/postparse/services/transcription.py @@ -248,7 +248,9 @@ def _make_collector(self) -> Any: instagram_credentials(self.env), InstagramOptions.from_config(self.config), interactive=self.interactive, - **self.instagram_overrides, + # Re-fetches never log in with the password (see `check instagram + # --import-session` / `--login`). + **{**self.instagram_overrides, "allow_password_login": False}, ) def _fetcher(self, refetch: bool) -> Any: diff --git a/tests/unit/api/test_job_runner.py b/tests/unit/api/test_job_runner.py index a83d17a..99066b2 100644 --- a/tests/unit/api/test_job_runner.py +++ b/tests/unit/api/test_job_runner.py @@ -15,6 +15,7 @@ from postparse.collectors.base import ( CredentialsMissing, InstagramAuthRequired, + InstagramFeedUnavailable, TelegramRateLimited, ) @@ -90,12 +91,29 @@ async def work(progress: Any) -> Report: assert cache.invalidations == 1 # partial runs may have written data +async def test_feed_unavailable_report_fails_the_job() -> None: + runner, jobs, _ws, _cache = _runner() + + async def work(progress: Any) -> Report: + return Report(processed=2, stopped_reason="feed_unavailable", error="feed refused") + + job_id = runner.submit("instagram_extract", {}, work) + await runner.wait(job_id, timeout=5) + job = jobs.get_job(job_id) + assert (job.status, job.error_code, job.messages_processed) == ( + ExtractionStatus.FAILED, + "feed_unavailable", + 2, + ) + + @pytest.mark.parametrize( ("exc", "code"), [ (CredentialsMissing("Telegram", ("TELEGRAM_API_ID",)), "credentials_missing"), (InstagramAuthRequired(), "auth_required"), (TelegramRateLimited(30), "rate_limited"), + (InstagramFeedUnavailable("web", "something went wrong"), "feed_unavailable"), (ValueError("bad provider"), "invalid_request"), (KeyError("taxonomy"), "invalid_request"), (RuntimeError("boom"), "internal_error"), diff --git a/tests/unit/cli/test_check.py b/tests/unit/cli/test_check.py index e0952d3..d749a69 100644 --- a/tests/unit/cli/test_check.py +++ b/tests/unit/cli/test_check.py @@ -102,6 +102,14 @@ def test_instagram_status_variants(settings: Settings) -> None: assert ok.status == "ok" +@pytest.mark.parametrize("password", [True, False]) +def test_instagram_status_recommends_the_session_import(settings: Settings, password: bool) -> None: + env = {"INSTAGRAM_USERNAME": "me", **({"INSTAGRAM_PASSWORD": "pw"} if password else {})} + hints = check_mod.instagram_status(settings, env=env).hints + assert "--import-session" in hints[0] and "no password" in hints[0] + assert "--login" in hints[1] and "#2487" in hints[1] + + def test_check_telegram_command_makes_no_network_call( no_network: dict[str, Any], monkeypatch: pytest.MonkeyPatch ) -> None: @@ -193,6 +201,317 @@ def test_check_instagram_login( assert result.exit_code == code, result.output +@pytest.fixture +def ig_login(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """``check instagram --login`` with the real collector on a fake instaloader.""" + from postparse.collectors.instagram import collector as collector_mod + from tests.unit.collectors.fakes import FakeLoader + + monkeypatch.chdir(tmp_path) + settings = Settings(data_dir=tmp_path / "data") + assert settings.sessions_dir is not None + session = settings.sessions_dir / "instagram_me" + session.parent.mkdir(parents=True) + session.write_text("original-session") + monkeypatch.setattr(check_mod, "_settings", lambda ctx: settings) + monkeypatch.setattr(check_mod, "_config", lambda ctx: None) + state: dict[str, Any] = {"session": session, "loader": FakeLoader(session_user="me")} + monkeypatch.setattr(collector_mod, "_default_loader_factory", lambda options: state["loader"]) + + def invoke() -> Any: + return CliRunner().invoke( + cli, + ["check", "instagram", "--login"], + env={"INSTAGRAM_USERNAME": "me", "INSTAGRAM_PASSWORD": "pw-secret"}, + ) + + state["invoke"] = invoke + return state + + +@pytest.mark.parametrize("setup", ["logged_out", "no_file"]) +def test_check_instagram_login_is_the_only_password_login(ig_login, setup: str) -> None: + from tests.unit.collectors.fakes import FakeLoader + + loader = FakeLoader(session_user=None) + ig_login["loader"] = loader + if setup == "no_file": + ig_login["session"].unlink() + + result = ig_login["invoke"]() + + assert result.exit_code == 0, result.output + text = " ".join(result.output.split()) + why = "session logged out: login_required" if setup == "logged_out" else "no session file" + assert f"No usable Instagram session ({why}); logging in with the password now" in text + assert "only command that logs in with the password" in text + assert loader.logins == ["me"] + assert loader.saved and ig_login["session"].read_text() == "fake-session" + assert "pw-secret" not in result.output + + +def test_check_instagram_login_with_a_valid_session_uses_no_password(ig_login) -> None: + result = ig_login["invoke"]() + assert result.exit_code == 0, result.output + assert "Instagram session verified (no password login)" in result.output + assert ig_login["loader"].logins == [] + + +def test_check_instagram_login_never_reports_a_session_without_cookie(ig_login) -> None: + """instaloader #2487: "authenticated" without a sessionid cookie is not a valid session.""" + from tests.unit.collectors.fakes import FakeLoader + + loader = FakeLoader(session_user=None, login_cookies={"csrftoken": "c-new"}) + ig_login["loader"] = loader + + result = ig_login["invoke"]() + + assert result.exit_code == 1, result.output + text = " ".join(result.output.split()) + assert "returned no session cookie (instaloader issue #2487); nothing was saved" in text + assert "`postparse check instagram --import-session`" in text + assert "session is valid" not in text + assert loader.logins == ["me"] and loader.saved == [] + assert ig_login["session"].read_text() == "original-session" + assert "pw-secret" not in result.output + + +def test_check_instagram_login_never_logs_in_on_a_throttled_check(ig_login) -> None: + from tests.unit.collectors.fakes import THROTTLED_401, FakeLoader, ig_error + + loader = FakeLoader(check_error=ig_error(THROTTLED_401)) + ig_login["loader"] = loader + + result = ig_login["invoke"]() + + assert result.exit_code == 1, result.output + text = " ".join(result.output.split()) + assert "No password login was attempted" in text + assert "Please wait a few minutes" in text and "https://" not in text + assert "logging in with the password" not in text + assert loader.logins == [] and loader.saved == [] + assert ig_login["session"].read_text() == "original-session" + + +# -- --import-session (browser session, hidden prompt) ------------------------------- + +#: Fake browser cookies (never shown in any output). +BROWSER_SID = "4242%3AsecretBrowserSid%3A27%3AAYleakyleaky" +BROWSER_CSRF = "browsercsrfLEAK0123456789abcdefX" + + +def _assert_no_cookie_values(text: str) -> None: + for leak in ("secretBrowserSid", "AYleakyleaky", BROWSER_CSRF): + assert leak not in text + + +@pytest.fixture +def ig_import(ig_login, monkeypatch: pytest.MonkeyPatch): + """``check instagram --import-session`` on a terminal (real collector, fake instaloader).""" + from tests.unit.collectors.fakes import FakeLoader + + monkeypatch.setattr(check_mod, "_stdin_is_tty", lambda: True) + ig_login["loader"] = FakeLoader(session_user="me") + + def invoke(stdin: str, *args: str, env: dict[str, str] | None = None) -> Any: + return CliRunner().invoke( + cli, + ["check", "instagram", "--import-session", *args], + input=stdin, + env={"INSTAGRAM_USERNAME": "me"} if env is None else env, + ) + + ig_login["invoke"] = invoke + return ig_login + + +def test_check_instagram_import_session_saves_the_browser_session(ig_import) -> None: + loader = ig_import["loader"] + + result = ig_import["invoke"](f"{BROWSER_SID}\n\n") + + assert result.exit_code == 0, result.output + text = " ".join(result.output.split()) + assert "Browser session imported and verified (no password login)" in text + assert "instagram import: browser session imported and verified" in text + assert "user_agent" in text and "Do not log out of Instagram in that browser" in text + assert "(input hidden)" in text + # Exactly one request: the first page of the saved feed (as the web app asks for it). + assert [r[:3] for r in loader.context.requests] == [ + ("web", "api/v1/feed/saved/posts/", {"count": "50"}) + ] + assert loader.logins == [] + assert loader.imported[0][1]["sessionid"] == BROWSER_SID + assert len(loader.imported[0][1]["csrftoken"]) == 32 # generated (Enter) + assert ig_import["session"].read_text() == "fake-session" + _assert_no_cookie_values(result.output) + + +def test_check_instagram_import_session_with_csrftoken_and_session_option( + ig_import, tmp_path: Path +) -> None: + target = tmp_path / "custom_session" + result = ig_import["invoke"](f"{BROWSER_SID}\n{BROWSER_CSRF}\n", "--session", str(target)) + assert result.exit_code == 0, result.output + assert ig_import["loader"].imported[0][1]["csrftoken"] == BROWSER_CSRF + assert target.read_text() == "fake-session" + assert ig_import["session"].read_text() == "original-session" + _assert_no_cookie_values(result.output) + + +def test_check_instagram_import_session_needs_no_password(ig_import) -> None: + ig_import["session"].unlink() + result = ig_import["invoke"](f"{BROWSER_SID}\n\n") + assert result.exit_code == 0, result.output # "no session file" is fixed by the import + assert ig_import["session"].read_text() == "fake-session" + + +class _FeedApiConfig: + """ConfigManager stand-in that only sets ``instagram.feed_api``.""" + + def __init__(self, feed_api: str) -> None: + self.feed_api = feed_api + + def get(self, key: str, default: Any = None) -> Any: + return self.feed_api if key == "instagram.feed_api" else default + + +@pytest.mark.parametrize( + ("loader_kwargs", "why", "feed_api"), + [ + ({"new_user": None}, "session logged out: login_required", "web"), + ({"new_user": None}, "session logged out: login_required", "iphone"), + # Only the iPhone check (user info) names the viewer. + ({"new_user": "someone_else"}, "the session belongs to another account", "iphone"), + ], + ids=["logged-out", "logged-out-iphone", "other-user-iphone"], +) +def test_check_instagram_import_session_unusable_saves_nothing( + ig_import, monkeypatch: pytest.MonkeyPatch, loader_kwargs: dict, why: str, feed_api: str +) -> None: + from tests.unit.collectors.fakes import IG_SAVED_FEED, IG_USER_INFO, FakeLoader + + monkeypatch.setattr(check_mod, "_config", lambda ctx: _FeedApiConfig(feed_api)) + loader = FakeLoader(**loader_kwargs) + ig_import["loader"] = loader + result = ig_import["invoke"](f"{BROWSER_SID}\n{BROWSER_CSRF}\n") + assert result.exit_code == 1, result.output + text = " ".join(result.output.split()) + assert "The imported session is not usable" in text and why in text + assert "nothing was saved" in text + assert loader.saved == [] and loader.logins == [] + expected = ("web", IG_SAVED_FEED) if feed_api == "web" else ("iphone", IG_USER_INFO) + assert [r[:2] for r in loader.context.requests] == [expected] + assert ig_import["session"].read_text() == "original-session" + _assert_no_cookie_values(result.output) + + +#: A 200 answer with ``"status": "fail"`` (not a statement about the session). +FEED_FAIL_200 = ( + '200 OK - "fail" status, message "We\'re sorry, but something went wrong. Please try again."' +) + + +@pytest.mark.parametrize( + ("status", "expected"), + [ + ("429 Too Many Requests", "Instagram did not confirm the session after the session import"), + ( + '400 Bad Request - "fail" status, message "checkpoint_required"', + "asks for a confirmation of the saved session (Instagram: checkpoint_required)", + ), + (FEED_FAIL_200, "Instagram refused the saved feed (web API)"), + ], + ids=["429", "checkpoint", "fail-status"], +) +def test_check_instagram_import_session_failed_check_saves_nothing( + ig_import, status: str, expected: str +) -> None: + from tests.unit.collectors.fakes import IG_SAVED_FEED, FakeLoader, ig_error + + loader = FakeLoader(new_check_error=ig_error(status, IG_SAVED_FEED)) + ig_import["loader"] = loader + result = ig_import["invoke"](f"{BROWSER_SID}\n{BROWSER_CSRF}\n") + assert result.exit_code == 1, result.output + text = " ".join(result.output.split()) + verdict = text.split("instagram import:", 1)[1] # after the instructions + assert expected in verdict + assert "session logged out" not in verdict and "https://" not in verdict + assert loader.saved == [] and loader.logins == [] + assert [r[:2] for r in loader.context.requests] == [("web", IG_SAVED_FEED)] # one request + assert ig_import["session"].read_text() == "original-session" + _assert_no_cookie_values(result.output) + + +def test_check_instagram_import_session_malformed_value(ig_import) -> None: + result = ig_import["invoke"]("secretBrowserSid-AYleakyleaky\n\n") + assert result.exit_code == 1, result.output + text = " ".join(result.output.split()) + assert "does not look like an Instagram sessionid cookie" in text + assert ig_import["loader"].context.requests == [] + assert ig_import["session"].read_text() == "original-session" + _assert_no_cookie_values(result.output) + + +def test_check_instagram_import_session_needs_a_terminal( + no_network: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("INSTAGRAM_USERNAME", "me") + result = CliRunner().invoke( + cli, ["check", "instagram", "--import-session"], input=f"{BROWSER_SID}\n\n" + ) + assert result.exit_code == 1, result.output + assert "needs an interactive terminal" in " ".join(result.output.split()) + assert "(input hidden)" not in result.output # no prompt + assert no_network["instagram"] == 0 + _assert_no_cookie_values(result.output) + + +def test_check_instagram_import_session_needs_a_username( + no_network: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("INSTAGRAM_USERNAME", raising=False) + monkeypatch.setattr(check_mod, "_stdin_is_tty", lambda: True) + result = CliRunner().invoke(cli, ["check", "instagram", "--import-session"], input="x\n\n") + assert result.exit_code == 1, result.output + assert "INSTAGRAM_USERNAME not set" in result.output + assert no_network["instagram"] == 0 + + +def test_check_instagram_import_session_and_login_are_exclusive( + no_network: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("INSTAGRAM_USERNAME", "me") + result = CliRunner().invoke(cli, ["check", "instagram", "--import-session", "--login"]) + assert result.exit_code == 2, result.output + assert "cannot be combined" in result.output + assert no_network["instagram"] == 0 + + +def test_instagram_import_with_an_injected_prompt( + settings: Settings, monkeypatch: pytest.MonkeyPatch +) -> None: + from postparse.collectors.instagram import collector as collector_mod + from tests.unit.collectors.fakes import FakeLoader + + monkeypatch.setattr(check_mod, "_stdin_is_tty", lambda: False) # not needed with a prompt + monkeypatch.delenv("INSTAGRAM_PASSWORD", raising=False) + loader = FakeLoader(session_user="me") + monkeypatch.setattr(collector_mod, "_default_loader_factory", lambda options: loader) + asked: list[tuple[str, bool]] = [] + + def prompt(text: str, optional: bool) -> str: + asked.append((text, optional)) + return BROWSER_SID if not optional else "" + + result = check_mod.instagram_import(settings, None, "me", None, prompt=prompt) + assert result.status == "ok", result.summary + assert [optional for _, optional in asked] == [False, True] + assert all("hidden" in text for text, _ in asked) + rows = " ".join(f"{k} {v}" for k, v in result.rows) + " ".join(result.hints) + _assert_no_cookie_values(rows + result.summary) + + # -- transcription -------------------------------------------------------------------- diff --git a/tests/unit/cli/test_config.py b/tests/unit/cli/test_config.py index 6931bf5..d2cade3 100644 --- a/tests/unit/cli/test_config.py +++ b/tests/unit/cli/test_config.py @@ -76,6 +76,7 @@ def test_test_config_validates_with_warnings(self) -> None: assert "Taxonomies" in result.output assert "Transcription" in result.output assert "Enrichment" in result.output + assert "feed_api web" in result.output def test_fix_creates_directories(self, tmp_path: Path) -> None: cfg = _write_config(tmp_path, f'[paths]\ndata_dir = "{(tmp_path / "d").as_posix()}"\n') @@ -89,6 +90,7 @@ def test_fix_creates_directories(self, tmp_path: Path) -> None: [ ('[transcription]\nbackend = "cloud"\n', "Transcription"), ("[enrichment]\nconcurrency = 0\n", "Enrichment"), + ('[instagram]\nfeed_api = "graphql"\n', "instagram.feed_api must be one of"), ( '[[classification.taxonomies]]\nname = "t"\nmode = "weird"\nlabels = ["a"]\n', "Taxonomies", diff --git a/tests/unit/cli/test_extract.py b/tests/unit/cli/test_extract.py index b013cd9..c2ec17d 100644 --- a/tests/unit/cli/test_extract.py +++ b/tests/unit/cli/test_extract.py @@ -6,13 +6,15 @@ import pytest from click.testing import CliRunner -from instaloader.exceptions import LoginException, TooManyRequestsException +from instaloader.exceptions import AbortDownloadException, TooManyRequestsException from postparse.cli.main import cli +from postparse.collectors.base import InstagramFeedUnavailable from postparse.config import Settings from postparse.core.db import Database from postparse.services.extraction import ExtractionService from tests.unit.collectors.fakes import ( + IG_SAVED_FEED, THROTTLED_401, FakeLoader, FakeTelegramClient, @@ -20,10 +22,12 @@ SleepRecorder, client_factory, ig_error, + ig_iphone_media, ig_node, ig_post, loader_factory, no_sleep, + saved_page, tg_text, ) @@ -41,9 +45,14 @@ def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): """Patch the CLI's service factory; returns a dict to configure the fakes.""" monkeypatch.chdir(tmp_path) settings = Settings(data_dir=tmp_path / "data") + assert settings.sessions_dir is not None + session = settings.sessions_dir / "instagram_me" + session.parent.mkdir(parents=True, exist_ok=True) + session.write_text("original-session") state: dict = { "client": FakeTelegramClient([tg_text(1, "a"), tg_text(2, "b")]), - "loader": FakeLoader(), + "loader": FakeLoader(session_user="me"), + "session": session, "feed": Feed([ig_post(ig_node("p1")), ig_post(ig_node("p2"))]), "db_paths": [], } @@ -142,10 +151,8 @@ def test_instagram_rate_limited_exit_3(env) -> None: assert "kept" in result.output -def test_instagram_throttled_session_check_exit_3(env, tmp_path: Path) -> None: - session = Settings(data_dir=tmp_path / "data").sessions_dir / "instagram_me" - session.parent.mkdir(parents=True) - session.write_text("original-session") +def test_instagram_throttled_session_check_exit_3(env) -> None: + session = env["session"] env["loader"] = FakeLoader(check_error=ig_error(THROTTLED_401)) result = invoke(["instagram"], SECRETS) @@ -159,14 +166,186 @@ def test_instagram_throttled_session_check_exit_3(env, tmp_path: Path) -> None: assert_no_secrets(result.output) -def test_instagram_checkpoint_exit_2(env) -> None: - env["loader"] = FakeLoader(login_error=LoginException("Checkpoint required")) +FEED_FAIL = ( + '200 OK - "fail" status, message "We\'re sorry, but something went wrong. Please try again."' +) + + +def test_instagram_feed_refused_exit_3_keeps_progress(env, tmp_path: Path) -> None: + env["feed"] = Feed( + [ig_post(ig_node(c)) for c in "abc"], + fail_at=2, + error=InstagramFeedUnavailable("web", "We're sorry, but something went wrong."), + ) + result = invoke(["instagram", "--batch-size", "1"], SECRETS) + + assert result.exit_code == 3, result.output + text = " ".join(result.output.split()) + assert "feed refused by Instagram" in text + assert "session is fine" in text and 'instagram.feed_api = "iphone"' in text + assert "Everything committed before the feed was refused has been kept." in text + assert "ConnectionException" not in text + with Database.open(Settings(data_dir=tmp_path / "data").db_path).read() as conn: + assert conn.execute("SELECT count(*) FROM items").fetchone()[0] == 2 + assert_no_secrets(result.output) + + +def test_instagram_feed_fail_status_from_the_web_feed_exit_3(env) -> None: + """The web session check is the first feed page: one request, typed error.""" + loader = FakeLoader(session_user="me") + loader.context.web_responses[IG_SAVED_FEED] = ig_error(FEED_FAIL, IG_SAVED_FEED) + env["loader"] = loader + env["feed"] = None # the collector's own saved-feed walk + result = invoke(["instagram"], SECRETS) - assert result.exit_code == 2 - assert "Instagram app" in result.output + + assert result.exit_code == 3, result.output + assert [r[:2] for r in loader.context.requests] == [("web", IG_SAVED_FEED)] + text = " ".join(result.output.split()) + assert "something went wrong" in text and "feed refused by Instagram" in text + assert "logged out" not in text + assert loader.logins == [] and loader.saved == [] + assert env["session"].read_text() == "original-session" + + +def test_instagram_valid_web_session_is_exactly_one_request(env, tmp_path: Path) -> None: + """``--limit 1 --stop-after-known 1``: the check's feed page is the walk's page 1.""" + loader = FakeLoader(session_user="me") + loader.context.web_responses[IG_SAVED_FEED] = saved_page( + [ig_iphone_media("n1"), ig_iphone_media("n2")], next_max_id="c1" + ) + env["loader"] = loader + env["feed"] = None # the collector's own saved-feed walk + + result = invoke(["instagram", "--limit", "1", "--stop-after-known", "1"], SECRETS) + + assert result.exit_code == 0, result.output + assert loader.context.requests == [("web", IG_SAVED_FEED, {"count": "50"}, 1)] + with Database.open(Settings(data_dir=tmp_path / "data").db_path).read() as conn: + codes = [r[0] for r in conn.execute("SELECT external_id FROM items")] + assert codes == ["n1"] # a post of page 1 was processed + assert loader.logins == [] assert_no_secrets(result.output) +def test_instagram_prints_verified_session(env) -> None: + result = invoke(["instagram"], SECRETS) + assert result.exit_code == 0, result.output + assert "Instagram session verified (no password login)" in result.output + assert "password (" not in result.output + assert_no_secrets(result.output) + + +def _unreadable(loader: FakeLoader) -> FakeLoader: + def broken(username: str, filename: str) -> None: + raise EOFError("Ran out of input") + + loader.load_session_from_file = broken # type: ignore[method-assign] + return loader + + +#: ``(setup, loader factory, reason in the message)`` of a session that cannot be used. +UNUSABLE_SESSIONS = [ + ("no_file", lambda: FakeLoader(session_user="me"), "no session file"), + ("unreadable", lambda: _unreadable(FakeLoader(session_user="me")), "session file unreadable"), + ("logged_out", lambda: FakeLoader(session_user=None), "session logged out: login_required"), + ( + "login_redirect", + lambda: FakeLoader( + check_error=AbortDownloadException( + "Redirected to login page. You've been logged out, please wait some time, " + "recreate the session and try again" + ) + ), + "session logged out: redirected to login page", + ), +] + + +@pytest.mark.parametrize("password", ["ig-pass-secret", None], ids=["password", "no-password"]) +@pytest.mark.parametrize( + ("setup", "make_loader", "why"), + UNUSABLE_SESSIONS, + ids=[case[0] for case in UNUSABLE_SESSIONS], +) +def test_instagram_never_logs_in_with_the_password_exit_2( + env, setup: str, make_loader, why: str, password: str | None +) -> None: + session: Path = env["session"] + if setup == "no_file": + session.unlink() + loader = make_loader() + env["loader"] = loader + secrets = {k: v for k, v in SECRETS.items() if k != "INSTAGRAM_PASSWORD"} + if password is not None: + secrets["INSTAGRAM_PASSWORD"] = password + + result = invoke(["instagram"], secrets) + + assert result.exit_code == 2, result.output + text = " ".join(result.output.split()) + assert f"No password login was attempted ({why})" in text + assert "automatic password logins are disabled" in text + assert "`postparse check instagram --login`" in text + assert "Logging in" not in text and "logging in with the password" not in text + assert loader.logins == [] and loader.two_factor_codes == [] + assert loader.saved == [] # the session file is never written + assert session.exists() is (setup != "no_file") + if setup != "no_file": + assert session.read_text() == "original-session" + assert_no_secrets(result.output) + + +def test_instagram_checkpoint_on_session_check_exit_2(env) -> None: + loader = FakeLoader( + check_error=AbortDownloadException( + 'Query to https://i.instagram.com/api/v1/users/4242/info/ responded with "400 Bad ' + 'Request": {"message": "challenge_required", "status": "fail"}' + ) + ) + env["loader"] = loader + result = invoke(["instagram"], SECRETS) + assert result.exit_code == 2, result.output + text = " ".join(result.output.split()) + assert "(Instagram: challenge_required)" in text + assert "`postparse check instagram --login`" in text and "Instagram app" in text + assert loader.logins == [] and loader.saved == [] + + +def test_instagram_checkpoint_during_feed_exit_2_shows_the_reason(env) -> None: + from instaloader.exceptions import ConnectionException + + env["feed"] = Feed( + [ig_post(ig_node("a"))], + fail_at=0, + error=ConnectionException( + f'JSON Query to {IG_SAVED_FEED}: 400 Bad Request - "fail" status, message ' + f'"checkpoint_required" when accessing https://www.instagram.com/{IG_SAVED_FEED}' + "?count=50&max_id=QVFC3429&sessionid=leaked-sid" + ), + ) + result = invoke(["instagram"], SECRETS) + assert result.exit_code == 2, result.output + text = " ".join(result.output.split()) + assert "(Instagram: checkpoint_required)" in text + assert "`postparse check instagram --login`" in text + assert "leaked-sid" not in text and "max_id" not in text + assert env["loader"].logins == [] + + +def test_instagram_invalid_feed_api_is_a_clear_error(env, monkeypatch: pytest.MonkeyPatch) -> None: + from postparse.collectors.instagram import InstagramOptions + + def broken(config): + return InstagramOptions(feed_api="graphql") # type: ignore[arg-type] + + monkeypatch.setattr(InstagramOptions, "from_config", staticmethod(broken)) + result = invoke(["instagram"], SECRETS) + assert result.exit_code == 1 + assert "instagram.feed_api must be one of 'web', 'iphone'" in " ".join(result.output.split()) + assert env["loader"].logins == [] + + def test_instagram_force_walks_everything(env) -> None: invoke(["instagram"], SECRETS) feed = Feed([ig_post(ig_node("p1")), ig_post(ig_node("p2"))]) @@ -190,7 +369,7 @@ def test_default_invokes_all(env) -> None: def test_all_runs_both_and_uses_highest_exit_code(env) -> None: - env["loader"] = FakeLoader(login_error=TooManyRequestsException("429")) + env["loader"] = FakeLoader(check_error=TooManyRequestsException("429 Too Many Requests")) env["client"] = FakeTelegramClient(authorized=False) result = invoke(["all", "--no-interactive"], SECRETS) assert result.exit_code == 3, result.output diff --git a/tests/unit/cli/test_transcribe.py b/tests/unit/cli/test_transcribe.py index aa5d206..7941824 100644 --- a/tests/unit/cli/test_transcribe.py +++ b/tests/unit/cli/test_transcribe.py @@ -165,6 +165,15 @@ def test_summarize_run(env) -> None: assert "Nothing to summarize" in again.output +def _saved_session(settings: Settings) -> FakeLoader: + """A verified saved Instagram session (extract never logs in with the password).""" + assert settings.sessions_dir is not None + path = settings.sessions_dir / "instagram_me" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("session") + return FakeLoader(session_user="me") + + def test_extract_instagram_transcribe(env, monkeypatch: pytest.MonkeyPatch) -> None: db: Database = env["db"] feed = Feed( @@ -181,7 +190,7 @@ def build(ctx, db_path): db, env["settings"], instagram_overrides={ - "loader_factory": loader_factory(FakeLoader()), + "loader_factory": loader_factory(_saved_session(env["settings"])), "saved_posts": feed, "sleep": SleepRecorder(), }, @@ -214,7 +223,7 @@ def test_extract_instagram_without_transcribe_flag(env, monkeypatch) -> None: env["db"], env["settings"], instagram_overrides={ - "loader_factory": loader_factory(FakeLoader()), + "loader_factory": loader_factory(_saved_session(env["settings"])), "saved_posts": feed, "sleep": SleepRecorder(), }, diff --git a/tests/unit/collectors/fakes.py b/tests/unit/collectors/fakes.py index e11bb56..6caf1f0 100644 --- a/tests/unit/collectors/fakes.py +++ b/tests/unit/collectors/fakes.py @@ -260,24 +260,45 @@ def ig_error(status: str, path: str = IG_USER_INFO) -> Exception: class FakeIgContext: """instaloader context that records requests and answers only scripted ones. - ``iphone_responses`` maps a private API path to a response dict, an - exception to raise, or a callable ``params -> dict | exception``. Any other - request raises :class:`NetworkUsed`. + ``iphone_responses`` (``get_iphone_json``, ``i.instagram.com``) and + ``web_responses`` (``get_json`` with ``host="www.instagram.com"``) map a + path to a response dict, an exception to raise, or a callable + ``params -> dict | exception``. Any other request raises :class:`NetworkUsed`. + ``web_gate(path, params)`` (optional) runs before a web answer: an + exception it returns is raised instead (the session state of + :class:`FakeLoader`). + ``_session`` is a real (never used for I/O) ``requests.Session`` holding the + loaded cookies, as in instaloader. """ def __init__(self, username: str | None = None) -> None: + import requests + self.username = username self.is_logged_in = username is not None self.iphone_support = False self.user_id: int | None = None self.max_connection_attempts = 3 + self.request_timeout = 30.0 + self._session = requests.Session() self.iphone_responses: dict[str, Any] = {} + self.web_responses: dict[str, Any] = {} + self.web_gate: Any = None #: ``(kind, path or query id, params, max_connection_attempts)`` per request. self.requests: list[tuple[str, str, dict[str, Any], int]] = [] + #: Request headers of each ``get_json`` call (same order as the "web" requests). + self.web_headers: list[dict[str, str]] = [] - def get_iphone_json(self, path: str, params: dict[str, Any]) -> dict[str, Any]: - self.requests.append(("iphone", path, dict(params), self.max_connection_attempts)) - answer = self.iphone_responses.get(path) + def set_cookies(self, cookies: dict[str, str]) -> None: + """Replace the session with a new one holding ``cookies`` (as instaloader does).""" + import requests + + self._session = requests.Session() + self._session.cookies = requests.utils.cookiejar_from_dict(dict(cookies)) + + @staticmethod + def _answer(table: dict[str, Any], path: str, params: dict[str, Any]) -> dict[str, Any]: + answer = table.get(path) if answer is None: raise NetworkUsed(f"unexpected Instagram request: {path}") if callable(answer): @@ -286,6 +307,30 @@ def get_iphone_json(self, path: str, params: dict[str, Any]) -> dict[str, Any]: raise answer return answer + def get_iphone_json(self, path: str, params: dict[str, Any]) -> dict[str, Any]: + self.requests.append(("iphone", path, dict(params), self.max_connection_attempts)) + return self._answer(self.iphone_responses, path, params) + + def get_json( + self, + path: str, + params: dict[str, Any], + host: str = "www.instagram.com", + session: Any = None, + response_headers: dict[str, Any] | None = None, + **kwargs: Any, + ) -> dict[str, Any]: + if host != "www.instagram.com": + raise NetworkUsed(f"unexpected Instagram request to {host}/{path}") + self.requests.append(("web", path, dict(params), self.max_connection_attempts)) + sess = session if session is not None else self._session + self.web_headers.append(dict(sess.headers)) + if self.web_gate is not None: + refusal = self.web_gate(path, params) + if refusal is not None: + raise refusal + return self._answer(self.web_responses, path, params) + def graphql_query(self, query_hash: str, variables: Any, referer: Any = None) -> Any: self.requests.append(("graphql", query_hash, dict(variables), self.max_connection_attempts)) raise NetworkUsed(f"unexpected GraphQL query {query_hash}") @@ -297,7 +342,7 @@ def doc_id_graphql_query(self, doc_id: str, variables: Any, referer: Any = None) def _refuse(self, *args: Any, **kwargs: Any) -> Any: raise NetworkUsed("unexpected Instagram request") - get_json = head = _refuse + head = _refuse def error(self, *args: Any, **kwargs: Any) -> None: return None @@ -306,15 +351,44 @@ def log(self, *args: Any, **kwargs: Any) -> None: return None +#: Placeholder cookies ``InstaloaderContext.login`` puts into a fresh jar (no domain). +LOGIN_PLACEHOLDERS = { + "sessionid": "", + "mid": "", + "ig_pr": "1", + "ig_vw": "1920", + "ig_cb": "1", + "csrftoken": "", + "s_network": "", + "ds_user_id": "", +} + + class FakeLoader: """Stand-in for ``instaloader.Instaloader`` (login/session methods only). + The answer of the session check depends on where the session came from: + the session file (``session_user`` / ``check_error``) or a password login / + imported session (``new_user`` / ``new_check_error``). With + ``feed_api = "iphone"`` the check is the user-info endpoint on + ``i.instagram.com`` (the username is compared); with ``"web"`` it is the + first page of the saved feed on ``www.instagram.com``: the session state + gates every web feed request (logged out / ``check_error`` is raised), the + page itself comes from ``context.web_responses[IG_SAVED_FEED]`` (default: + an empty first page). The web feed does not name the viewer, so any + ``session_user`` other than ``None`` is a usable web session. + Args: - session_user: Username the session check (user-info endpoint) returns; + session_user: Username the check of the session file returns; ``None`` answers like a logged-out session (403 ``login_required``). - check_error: Raised by the session check instead (e.g. a throttle). + check_error: Raised by the check of the session file instead (e.g. a throttle). session_cookies: Cookies the loaded session file contains. login_error / two_factor_error: Raised by the password / 2FA login. + login_cookies: Cookies Instagram sets on a password / 2FA login (domain + ``.instagram.com``; default: a full login). instaloader's empty + placeholders (no domain) are always in the jar as well. + new_user / new_check_error: Answer of the check of a session created by + a password login or :meth:`load_session` (``None`` user: logged out). """ def __init__( @@ -325,53 +399,106 @@ def __init__( session_cookies: dict[str, str] | None = None, login_error: BaseException | None = None, two_factor_error: BaseException | None = None, + login_cookies: dict[str, str] | None = None, + new_user: str | None = "me", + new_check_error: BaseException | None = None, ) -> None: self.context = FakeIgContext() self.session_user = session_user + self.check_error = check_error self.login_error = login_error self.two_factor_error = two_factor_error self.session_cookies = dict(SESSION_COOKIES if session_cookies is None else session_cookies) - self.cookies: dict[str, str] = {} + self.login_cookies = dict(SESSION_COOKIES if login_cookies is None else login_cookies) + self.new_user = new_user + self.new_check_error = new_check_error + #: ``file`` (session file or nothing loaded) or ``new`` (login / imported session). + self.origin = "file" self.loaded: list[tuple[str, str]] = [] + self.imported: list[tuple[str, dict[str, Any]]] = [] self.logins: list[str] = [] self.two_factor_codes: list[str] = [] self.saved: list[str] = [] - if check_error is not None: - self.context.iphone_responses[IG_USER_INFO] = check_error - elif session_user is None: - self.context.iphone_responses[IG_USER_INFO] = lambda _params: ig_error(LOGGED_OUT_403) - else: - self.context.iphone_responses[IG_USER_INFO] = { - "user": {"pk": int(IG_USER_ID), "username": session_user}, - "status": "ok", - } + self.context.iphone_responses[IG_USER_INFO] = self._user_info + self.context.web_responses[IG_SAVED_FEED] = saved_page([]) + self.context.web_gate = self._web_session + + def _session_state(self) -> tuple[str | None, BaseException | None]: + if self.origin == "file": + return self.session_user, self.check_error + return self.new_user, self.new_check_error + + def _user_info(self, _params: dict[str, Any]) -> Any: + user, error = self._session_state() + if error is not None: + return error + if user is None: + return ig_error(LOGGED_OUT_403) + return {"user": {"pk": int(IG_USER_ID), "username": user}, "status": "ok"} + + def _web_session(self, path: str, _params: dict[str, Any]) -> BaseException | None: + if path != IG_SAVED_FEED: + return None + user, error = self._session_state() + if error is not None: + return error + if user is None: + return ig_error(LOGGED_OUT_403, IG_SAVED_FEED) + return None + + def check_requests(self) -> list[tuple[str, str, dict[str, Any], int]]: + """Session-check requests (iPhone user info, or the first web feed page).""" + return [ + r + for r in self.context.requests + if r[:2] == ("iphone", IG_USER_INFO) + or (r[:2] == ("web", IG_SAVED_FEED) and "max_id" not in r[2]) + ] def load_session_from_file(self, username: str, filename: str) -> None: self.loaded.append((username, filename)) self.context.username = username self.context.is_logged_in = True - self.cookies = dict(self.session_cookies) + self.context.set_cookies(self.session_cookies) + + def load_session(self, username: str, session_data: dict[str, Any]) -> None: + if not session_data.get("csrftoken"): + raise KeyError("csrftoken") # instaloader reads it for X-CSRFToken + self.imported.append((username, dict(session_data))) + self.origin = "new" + self.context.username = username + self.context.is_logged_in = True + self.context.set_cookies(session_data) def save_session(self) -> dict[str, str]: - return dict(self.cookies) + import requests + + return dict(requests.utils.dict_from_cookiejar(self.context._session.cookies)) def test_login(self) -> str | None: raise AssertionError("test_login() uses a legacy query_hash and must not be called") + def _logged_in_jar(self) -> None: + """A fresh jar with instaloader's placeholders plus the cookies Instagram set.""" + self.context.set_cookies(LOGIN_PLACEHOLDERS) + for name, value in self.login_cookies.items(): + self.context._session.cookies.set(name, value, domain=".instagram.com", path="/") + self.origin = "new" + def login(self, user: str, passwd: str) -> None: self.logins.append(user) if self.login_error is not None: raise self.login_error self.context.username = user self.context.is_logged_in = True - self.cookies = dict(SESSION_COOKIES) + self._logged_in_jar() def two_factor_login(self, code: str) -> None: self.two_factor_codes.append(code) if self.two_factor_error is not None: raise self.two_factor_error self.context.is_logged_in = True - self.cookies = dict(SESSION_COOKIES) + self._logged_in_jar() def save_session_to_file(self, filename: str) -> None: self.saved.append(filename) diff --git a/tests/unit/collectors/test_instagram_collector.py b/tests/unit/collectors/test_instagram_collector.py index e887e78..2c3f63a 100644 --- a/tests/unit/collectors/test_instagram_collector.py +++ b/tests/unit/collectors/test_instagram_collector.py @@ -5,6 +5,7 @@ import json import pickle from pathlib import Path +from typing import Any import instaloader import pytest @@ -21,12 +22,14 @@ from postparse.collectors.base import ( InstagramAuthRequired, + InstagramFeedUnavailable, InstagramRateLimited, InstagramSessionCheckFailed, ) from postparse.collectors.credentials import InstagramCredentials from postparse.collectors.instagram.collector import ( InstagramCollector, + InstagramOptions, iter_saved_feed, map_post, post_from_iphone_media, @@ -42,6 +45,7 @@ IG_USER_ID, IG_USER_INFO, LEGACY_LOGIN_HASH, + LOGGED_OUT_403, SESSION_COOKIES, THROTTLED_401, FakeIgContext, @@ -70,14 +74,21 @@ def make( loader: FakeLoader | None = None, creds: InstagramCredentials = CREDS, interactive: bool = True, + allow_password_login: bool = True, sleep: SleepRecorder | None = None, **kwargs, ) -> InstagramCollector: + """A collector on fakes; by default as `check instagram --login` builds it. + + Extract runs (``allow_password_login=False``, the collector default) are + tested explicitly below. + """ return InstagramCollector( db, settings, creds, interactive=interactive, + allow_password_login=allow_password_login, loader_factory=loader_factory(loader or FakeLoader()), saved_posts=feed or Feed([]), sleep=sleep or SleepRecorder(), @@ -497,6 +508,12 @@ def from_shortcode(loader, code): # --------------------------------------------------------------------------- +#: Request of the session check per feed API: web = the saved feed's first page. +CHECK = {"web": ("web", IG_SAVED_FEED), "iphone": ("iphone", IG_USER_INFO)} +#: ``Referer`` of saved-feed requests (the saved page of the web app). +SAVED_REFERER = "https://www.instagram.com/me/saved/all-posts/" + + def _existing_session(settings: Settings) -> Path: path = _session(settings) path.parent.mkdir(parents=True, exist_ok=True) @@ -531,13 +548,13 @@ def test_throttled_session_check_never_logs_in_with_password( assert loader.logins == [] and loader.saved == [] assert path.read_text() == "original-session" # session file not rewritten assert not collector.logged_in - assert [r[:2] for r in loader.context.requests] == [("iphone", IG_USER_INFO)] + assert [r[:2] for r in loader.context.requests] == [CHECK["web"]] @pytest.mark.parametrize( - ("loader", "requests"), + ("loader", "requests", "feed_api"), [ - (FakeLoader(session_user=None), 1), # 403 login_required + (FakeLoader(session_user=None), 1, "web"), # 403 login_required ( FakeLoader( check_error=AbortDownloadException( @@ -546,12 +563,14 @@ def test_throttled_session_check_never_logs_in_with_password( ) ), 1, + "web", ), - (FakeLoader(check_error=LoginRequiredException("Redirected to login page.")), 1), - (FakeLoader(session_user="someone_else"), 1), # session of another account - (FakeLoader(session_cookies={"csrftoken": "x"}), 0), # no sessionid: no request - (FakeLoader(session_cookies={"sessionid": "", "ds_user_id": IG_USER_ID}), 0), - ], + (FakeLoader(check_error=LoginRequiredException("Redirected to login page.")), 1, "web"), + # Session of another account (only the iPhone check names the viewer). + (FakeLoader(session_user="someone_else"), 1, "iphone"), + (FakeLoader(session_cookies={"csrftoken": "x"}), 0, "web"), # no sessionid: no request + (FakeLoader(session_cookies={"sessionid": "", "ds_user_id": IG_USER_ID}), 0, "web"), + ], # requests: checks of the session file (the new session is checked once more) ids=[ "login-required", "login-redirect", @@ -562,14 +581,26 @@ def test_throttled_session_check_never_logs_in_with_password( ], ) def test_logged_out_session_falls_back_to_password( - db: Database, settings: Settings, loader: FakeLoader, requests: int + db: Database, settings: Settings, loader: FakeLoader, requests: int, feed_api: str ) -> None: path = _existing_session(settings) - with make(db, settings, loader=loader) as collector: + options = InstagramOptions(feed_api=feed_api) # type: ignore[arg-type] + with make(db, settings, loader=loader, options=options) as collector: assert collector.logged_in assert loader.logins == ["me"] assert loader.saved[0] == str(path) - assert len(loader.context.requests) == requests + assert len(loader.context.requests) == requests + 1 + assert loader.context.requests[-1][:2] == CHECK[feed_api] # check after the login + + +def test_web_check_uses_the_session_of_another_account(db: Database, settings: Settings) -> None: + """The saved feed does not name the viewer: the account is the sessionid's.""" + _existing_session(settings) + loader = FakeLoader(session_user="someone_else") + with make(db, settings, loader=loader) as collector: + assert collector.logged_in + assert loader.logins == [] + assert [r[:2] for r in loader.context.requests] == [CHECK["web"]] def test_logged_out_session_without_password_is_auth_required( @@ -603,7 +634,7 @@ def test_valid_session_check_uses_one_attempt_and_no_legacy_hash( ) -> None: _existing_session(settings) loader = FakeLoader(session_user="Me") # usernames compare case-insensitively - loader.context.iphone_responses[IG_SAVED_FEED] = saved_feed_pages( + loader.context.web_responses[IG_SAVED_FEED] = saved_feed_pages( saved_page([ig_iphone_media("a")]) ) collector = InstagramCollector( @@ -614,10 +645,9 @@ def test_valid_session_check_uses_one_attempt_and_no_legacy_hash( assert loader.logins == [] assert loader.legacy_hash_requests() == [] - assert [r[0] for r in loader.context.requests] == ["iphone", "iphone"] - (check, feed) = loader.context.requests - assert check[1] == IG_USER_INFO and check[3] == 1 # single connection attempt - assert feed[1] == IG_SAVED_FEED and feed[3] == 3 # feed keeps the configured attempts + # One request: the check (single connection attempt) is the walk's first page. + assert loader.context.requests == [("web", IG_SAVED_FEED, {"count": "50"}, 1)] + assert count(db) == 1 assert loader.context.max_connection_attempts == 3 # restored assert loader.context.user_id == int(IG_USER_ID) @@ -633,15 +663,35 @@ def test_failed_session_check_restores_connection_attempts( assert loader.context.max_connection_attempts == 3 -def test_unexpected_check_response_keeps_the_session(db: Database, settings: Settings) -> None: +@pytest.mark.parametrize("feed_api", ["web", "iphone"]) +def test_check_answer_without_details_keeps_the_session( + db: Database, settings: Settings, feed_api: str +) -> None: _existing_session(settings) loader = FakeLoader(session_user="me") - loader.context.iphone_responses[IG_USER_INFO] = {"status": "ok"} - with make(db, settings, loader=loader) as collector: + if feed_api == "web": + loader.context.web_responses[IG_SAVED_FEED] = {"status": "ok"} # no items + else: + loader.context.iphone_responses[IG_USER_INFO] = {"status": "ok"} # no username + options = InstagramOptions(feed_api=feed_api) # type: ignore[arg-type] + with make(db, settings, loader=loader, options=options) as collector: assert collector.logged_in assert loader.logins == [] +def test_web_check_answer_that_is_no_feed_page_saves_nothing( + db: Database, settings: Settings +) -> None: + path = _existing_session(settings) + loader = FakeLoader(session_user="me") + loader.context.web_responses[IG_SAVED_FEED] = {"num_results": 0} + collector = make(db, settings, loader=loader) + with pytest.raises(InstagramSessionCheckFailed, match="unexpected answer"), collector: + pytest.fail("must not enter") + assert loader.logins == [] and loader.saved == [] and not collector.logged_in + assert path.read_text() == "original-session" + + def test_unreadable_session_file_falls_back_to_password(db: Database, settings: Settings) -> None: _existing_session(settings) loader = FakeLoader(session_user="me") @@ -652,22 +702,45 @@ def broken(username: str, filename: str) -> None: loader.load_session_from_file = broken # type: ignore[method-assign] with make(db, settings, loader=loader) as collector: assert collector.logged_in - assert loader.logins == ["me"] and loader.context.requests == [] + assert loader.logins == ["me"] + # No check of the unreadable file; one check of the new session. + assert [r[:2] for r in loader.context.requests] == [CHECK["web"]] # --------------------------------------------------------------------------- -# Saved feed via the private API +# Saved feed (web REST API by default, private iPhone API as fallback) # --------------------------------------------------------------------------- +FEED_APIS = pytest.mark.parametrize("feed_api", ["web", "iphone"]) +#: First-page parameters per feed API. +BASE_PARAMS = {"web": {"count": "50"}, "iphone": {"include_igtv_preview": "false"}} +#: ``FakeIgContext.requests`` kind per feed API. +KIND = {"web": "web", "iphone": "iphone"} + +FEED_FAIL_200 = ( + '200 OK - "fail" status, message "We\'re sorry, but something went wrong. Please try again."' +) + + +def _feed_table(loader: FakeLoader | FakeIgContext, feed_api: str) -> dict: + context = loader.context if isinstance(loader, FakeLoader) else loader + return context.web_responses if feed_api == "web" else context.iphone_responses + def _feed_collector( - db: Database, settings: Settings, *pages: dict + db: Database, settings: Settings, *pages: dict, feed_api: str = "web", **kwargs ) -> tuple[InstagramCollector, FakeLoader]: _existing_session(settings) loader = FakeLoader(session_user="me") - loader.context.iphone_responses[IG_SAVED_FEED] = saved_feed_pages(*pages) + _feed_table(loader, feed_api)[IG_SAVED_FEED] = saved_feed_pages(*pages) collector = InstagramCollector( - db, settings, CREDS, loader_factory=loader_factory(loader), sleep=SleepRecorder() + db, + settings, + CREDS, + InstagramOptions(feed_api=feed_api), + loader_factory=loader_factory(loader), + sleep=SleepRecorder(), + **kwargs, ) return collector, loader @@ -676,27 +749,89 @@ def _feed_requests(loader: FakeLoader) -> list[dict]: return [r[2] for r in loader.context.requests if r[1] == IG_SAVED_FEED] -def test_saved_feed_paginates_with_max_id(db: Database, settings: Settings) -> None: +@FEED_APIS +def test_saved_feed_paginates_with_max_id(db: Database, settings: Settings, feed_api: str) -> None: collector, loader = _feed_collector( db, settings, saved_page([ig_iphone_media("a"), ig_iphone_media("b")], next_max_id="cursor-1"), saved_page([ig_iphone_media("c")], next_max_id="cursor-2"), saved_page([ig_iphone_media("d")]), + feed_api=feed_api, ) with collector: stats = collector.collect_saved() assert (stats.new, stats.stopped_reason) == (4, "end_of_feed") + base = BASE_PARAMS[feed_api] assert _feed_requests(loader) == [ - {"include_igtv_preview": "false"}, - {"include_igtv_preview": "false", "max_id": "cursor-1"}, - {"include_igtv_preview": "false", "max_id": "cursor-2"}, + base, + {**base, "max_id": "cursor-1"}, + {**base, "max_id": "cursor-2"}, ] + # Only the configured API is used for the feed (and for the session check). + feed_kinds = {r[0] for r in loader.context.requests if r[1] == IG_SAVED_FEED} + assert feed_kinds == {KIND[feed_api]} assert [get(db, c)[1].saved_feed_rank for c in "abcd"] == [0, 1, 2, 3] -def test_saved_feed_early_stop_skips_further_pages(db: Database, settings: Settings) -> None: +def test_default_feed_api_is_web_and_never_calls_the_iphone_feed( + db: Database, settings: Settings +) -> None: + _existing_session(settings) + loader = FakeLoader(session_user="me") + loader.context.web_responses[IG_SAVED_FEED] = saved_feed_pages( + saved_page([ig_iphone_media("w1")]) + ) + # An iphone feed request would raise NetworkUsed (no scripted answer). + collector = InstagramCollector( + db, settings, CREDS, loader_factory=loader_factory(loader), sleep=SleepRecorder() + ) + with collector: + collector.collect_saved() + assert ("iphone", IG_SAVED_FEED) not in [r[:2] for r in loader.context.requests] + assert count(db) == 1 + + +def test_web_feed_sends_the_web_app_headers(db: Database, settings: Settings) -> None: + collector, loader = _feed_collector( + db, settings, saved_page([ig_iphone_media("a")], next_max_id="c1"), saved_page([]) + ) + pages = saved_feed_pages(saved_page([ig_iphone_media("a")], next_max_id="c1")) + claims: list[str] = [] + + def answer(params: dict) -> dict: + claims.append(loader.context.web_headers[-1]["X-IG-WWW-Claim"]) + return pages(params) if "max_id" not in params else saved_page([]) + + loader.context.web_responses[IG_SAVED_FEED] = answer + with collector: + collector.collect_saved() + + # Page 1 (the session check, reused by the walk) and page 2: no other request. + assert [r[:2] for r in loader.context.requests] == [CHECK["web"]] * 2 + headers = loader.context.web_headers[0] # first feed page = the session check + lower = {k.lower(): v for k, v in headers.items()} + assert lower["x-ig-app-id"] == "936619743392459" + assert lower["x-csrftoken"] == SESSION_COOKIES["csrftoken"] # from the session cookie + assert lower["x-requested-with"] == "XMLHttpRequest" + assert lower["x-asbd-id"] == "129477" + assert lower["referer"] == SAVED_REFERER + assert lower["origin"] == "https://www.instagram.com" + assert lower["sec-fetch-site"] == "same-origin" + assert "x-instagram-ajax" not in lower and "content-length" not in lower + page2 = {k.lower(): v for k, v in loader.context.web_headers[1].items()} + assert page2["referer"] == SAVED_REFERER and page2["x-ig-app-id"] == lower["x-ig-app-id"] + assert claims == ["0", "0"] + # The main session is left unchanged (headers live on a temporary copy). + main = {k.lower() for k in loader.context._session.headers} + assert "x-asbd-id" not in main and "x-ig-www-claim" not in main + + +@FEED_APIS +def test_saved_feed_early_stop_skips_further_pages( + db: Database, settings: Settings, feed_api: str +) -> None: store(db, "k1", "k2") collector, loader = _feed_collector( db, @@ -704,6 +839,7 @@ def test_saved_feed_early_stop_skips_further_pages(db: Database, settings: Setti saved_page([ig_iphone_media("n1"), ig_iphone_media("k1")], next_max_id="c1"), saved_page([ig_iphone_media("k2"), ig_iphone_media("n2")], next_max_id="c2"), saved_page([ig_iphone_media("n3")]), + feed_api=feed_api, ) with collector: stats = collector.collect_saved(stop_after_known=2) @@ -712,38 +848,70 @@ def test_saved_feed_early_stop_skips_further_pages(db: Database, settings: Setti assert len(_feed_requests(loader)) == 2 # the third page is never requested +@FEED_APIS +def test_saved_feed_early_stop_on_page_one(db: Database, settings: Settings, feed_api: str) -> None: + store(db, "k1") + collector, loader = _feed_collector( + db, + settings, + saved_page([ig_iphone_media("k1"), ig_iphone_media("n1")], next_max_id="c1"), + saved_page([ig_iphone_media("n2")]), + feed_api=feed_api, + ) + with collector: + stats = collector.collect_saved(stop_after_known=1) + assert (stats.new, stats.stopped_reason) == (0, "early_stop") + assert _feed_requests(loader) == [BASE_PARAMS[feed_api]] # page 2 never requested + + +@FEED_APIS def test_saved_feed_stops_on_empty_page_and_repeated_cursor( - db: Database, settings: Settings + db: Database, settings: Settings, feed_api: str ) -> None: collector, loader = _feed_collector( - db, settings, saved_page([ig_iphone_media("a")], next_max_id="same") + db, settings, saved_page([ig_iphone_media("a")], next_max_id="same"), feed_api=feed_api ) # The second request (max_id=same) answers the same cursor again. - loader.context.iphone_responses[IG_SAVED_FEED] = lambda params: saved_page( + _feed_table(loader, feed_api)[IG_SAVED_FEED] = lambda params: saved_page( [ig_iphone_media("a" if "max_id" not in params else "b")], next_max_id="same" ) with collector: stats = collector.collect_saved() assert stats.new == 2 and len(_feed_requests(loader)) == 2 - empty = iter_saved_feed(_context_with_feed(saved_page([], next_max_id="x"))) - assert list(empty) == [] + context = _context_with_feed(saved_page([], next_max_id="x"), feed_api=feed_api) + assert list(iter_saved_feed(context, feed_api)) == [] + assert len(context.requests) == 1 + + +def test_saved_feed_accepts_bare_media_items() -> None: + """Items may be ``{"media": {...}}`` or the media struct itself; others are skipped.""" + page = saved_page([ig_iphone_media("wrapped")]) + page["items"] += [ig_iphone_media("bare"), {"media": {"no": "code"}}, "junk"] + context = _context_with_feed(page) + assert [p.shortcode for p in iter_saved_feed(context, "web", "me")] == ["wrapped", "bare"] -def _context_with_feed(*pages: dict) -> FakeIgContext: +def test_unknown_feed_api_is_rejected() -> None: + with pytest.raises(ValueError, match="unknown feed_api"): + list(iter_saved_feed(FakeIgContext("me"), "graphql")) # type: ignore[arg-type] + + +def _context_with_feed(*pages: dict, feed_api: str = "web") -> FakeIgContext: context = FakeIgContext("me") - context.iphone_responses[IG_SAVED_FEED] = saved_feed_pages(*pages) + _feed_table(context, feed_api)[IG_SAVED_FEED] = saved_feed_pages(*pages) return context -def test_saved_feed_rate_limit_keeps_progress(db: Database, settings: Settings) -> None: - collector, loader = _feed_collector( - db, settings, saved_page([ig_iphone_media("a"), ig_iphone_media("b")], next_max_id="c1") - ) +@FEED_APIS +def test_saved_feed_rate_limit_keeps_progress( + db: Database, settings: Settings, feed_api: str +) -> None: + collector, loader = _feed_collector(db, settings, feed_api=feed_api) pages = saved_feed_pages( saved_page([ig_iphone_media("a"), ig_iphone_media("b")], next_max_id="c1") ) - loader.context.iphone_responses[IG_SAVED_FEED] = lambda params: ( + _feed_table(loader, feed_api)[IG_SAVED_FEED] = lambda params: ( ig_error(THROTTLED_401, IG_SAVED_FEED) if params.get("max_id") else pages(params) ) with pytest.raises(InstagramRateLimited), collector: @@ -751,6 +919,134 @@ def test_saved_feed_rate_limit_keeps_progress(db: Database, settings: Settings) assert count(db) == 2 and collector.stats.stopped_reason == "rate_limited" +@FEED_APIS +def test_feed_fail_status_is_one_request_and_keeps_progress( + db: Database, settings: Settings, feed_api: str +) -> None: + collector, loader = _feed_collector(db, settings, feed_api=feed_api) + pages = saved_feed_pages( + saved_page([ig_iphone_media("a"), ig_iphone_media("b")], next_max_id="c1") + ) + _feed_table(loader, feed_api)[IG_SAVED_FEED] = lambda params: ( + ig_error(FEED_FAIL_200, IG_SAVED_FEED) if params.get("max_id") else pages(params) + ) + with pytest.raises(InstagramFeedUnavailable) as info, collector: + collector.collect_saved() + + other = "iphone" if feed_api == "web" else "web" + message = str(info.value) + assert info.value.feed_api == feed_api + assert "something went wrong" in message and "session is fine" in message + assert "nothing stored was lost" in message and f'feed_api = "{other}"' in message + assert "https://" not in message # no URL / query string in the message + assert len(_feed_requests(loader)) == 2 # page 2 asked once, no retries + assert all(r[3] == 1 for r in loader.context.requests if r[1] == IG_SAVED_FEED) + assert loader.context.max_connection_attempts == 3 # restored + assert count(db) == 2 and collector.stats.stopped_reason == "feed_unavailable" + assert loader.logins == [] + + +def test_feed_fail_status_on_the_first_page_fails_the_web_check( + db: Database, settings: Settings +) -> None: + """A 200 "fail" answer to the check's feed page is a refused feed, not a logout.""" + collector, loader = _feed_collector(db, settings) + loader.context.web_responses[IG_SAVED_FEED] = ig_error(FEED_FAIL_200, IG_SAVED_FEED) + with pytest.raises(InstagramFeedUnavailable, match="something went wrong") as info, collector: + pytest.fail("must not enter") + assert info.value.feed_api == "web" and "session is fine" in str(info.value) + assert "https://" not in str(info.value) + assert loader.context.requests == [("web", IG_SAVED_FEED, {"count": "50"}, 1)] + assert loader.logins == [] and loader.saved == [] and not collector.logged_in + assert _session(settings).read_text() == "original-session" and count(db) == 0 + + +def _network_error() -> Exception: + from instaloader.exceptions import ConnectionException + + cause = requests.exceptions.ReadTimeout("Read timed out.") + try: + raise ConnectionException(f"JSON Query to {IG_SAVED_FEED}: {cause}") from cause + except ConnectionException as exc: + return exc + + +def test_feed_network_errors_are_retried_up_to_the_configured_attempts( + db: Database, settings: Settings +) -> None: + first = saved_page([ig_iphone_media("a")], next_max_id="c1") + collector, loader = _feed_collector(db, settings) + answers = [_network_error(), saved_page([ig_iphone_media("b")])] + loader.context.web_responses[IG_SAVED_FEED] = lambda params: ( + answers.pop(0) if params.get("max_id") else first + ) + with collector: + stats = collector.collect_saved() + assert stats.new == 2 and len(_feed_requests(loader)) == 3 # check, page 2 twice + + collector, loader = _feed_collector(db, settings) + loader.context.web_responses[IG_SAVED_FEED] = lambda params: ( + _network_error() if params.get("max_id") else first + ) + with pytest.raises(Exception, match="Read timed out"), collector: + collector.collect_saved() + assert len(_feed_requests(loader)) == 1 + 3 # page 2: max_connection_attempts + assert loader.context.max_connection_attempts == 3 + + +def test_feed_api_option_parsing() -> None: + class Cfg: + def __init__(self, **values: object) -> None: + self.values = {f"instagram.{k}": v for k, v in values.items()} + + def get(self, key: str, default: object = None) -> object: + return self.values.get(key, default) + + assert InstagramOptions.from_config(None).feed_api == "web" + assert InstagramOptions.from_config(Cfg()).feed_api == "web" + assert InstagramOptions.from_config(Cfg(feed_api="iphone")).feed_api == "iphone" + assert InstagramOptions.from_config(Cfg(feed_api=" Web ")).feed_api == "web" + with pytest.raises(ValueError, match=r"instagram\.feed_api must be one of 'web', 'iphone'"): + InstagramOptions.from_config(Cfg(feed_api="graphql")) + with pytest.raises(ValueError, match="feed_api"): + InstagramOptions(feed_api="mobile") # type: ignore[arg-type] + + +# --------------------------------------------------------------------------- +# Session outcome on the progress callback +# --------------------------------------------------------------------------- + + +def test_verified_session_is_reported(db: Database, settings: Settings) -> None: + events: list = [] + collector, _ = _feed_collector(db, settings, saved_page([]), progress=events.append) + collector.login() + assert [(e.phase, e.message) for e in events] == [ + ("session", "Instagram session verified (no password login)") + ] + + +@pytest.mark.parametrize( + ("setup", "why"), + [ + ("logged_out", "session logged out: login_required"), + ("no_file", "no session file"), + ], +) +def test_password_login_is_reported(db: Database, settings: Settings, setup: str, why: str) -> None: + if setup == "logged_out": + _existing_session(settings) + events: list = [] + loader = FakeLoader(session_user=None) + collector = make(db, settings, loader=loader, progress=events.append) + collector.login() + assert loader.logins == ["me"] + assert [(e.phase, e.message) for e in events] == [ + ("login", f"No usable Instagram session ({why}); logging in with the password now") + ] + assert all("pw-secret" not in (e.message or "") for e in events) + + def test_map_iphone_image_post() -> None: post = post_from_iphone_media(FakeIgContext("me"), ig_iphone_media("Img1")) item = map_post(post, rank=3) @@ -832,16 +1128,22 @@ def test_iphone_mapping_never_triggers_requests() -> None: class _Http: """Records ``requests.Session.get/post`` calls and answers from a script.""" - def __init__(self, answers: list[tuple[int, dict]]) -> None: + def __init__(self, answers: list[tuple]) -> None: self.answers = answers self.calls: list[tuple[str, str, dict]] = [] + #: Request headers per call (lower-case names). + self.headers: list[dict[str, str]] = [] - def response(self, method: str, url: str, params: dict | None) -> requests.Response: + def response( + self, method: str, url: str, params: dict | None, headers: Any = None + ) -> requests.Response: self.calls.append((method, url, dict(params or {}))) + self.headers.append({k.lower(): v for k, v in dict(headers or {}).items()}) if not self.answers: raise AssertionError(f"unexpected request {method} {url}") - status, body = self.answers.pop(0) + status, body, *extra = self.answers.pop(0) resp = requests.Response() + resp.headers.update(extra[0] if extra else {}) resp.status_code = status resp.reason = {200: "OK", 401: "Unauthorized", 403: "Forbidden"}.get(status, "") resp._content = json.dumps(body).encode() @@ -857,12 +1159,12 @@ def install(*answers: tuple[int, dict]) -> _Http: monkeypatch.setattr( requests.Session, "get", - lambda self, url, params=None, **kw: fake.response("GET", url, params), + lambda self, url, params=None, **kw: fake.response("GET", url, params, self.headers), ) monkeypatch.setattr( requests.Session, "post", - lambda self, url, data=None, **kw: fake.response("POST", url, data), + lambda self, url, data=None, **kw: fake.response("POST", url, data, self.headers), ) return fake @@ -894,35 +1196,65 @@ def test_real_context_throttled_check_is_one_request( _real_collector(db, settings).login() assert [(m, u) for m, u, _ in fake.calls] == [ - ("GET", f"https://i.instagram.com/{IG_USER_INFO}") + ("GET", f"https://www.instagram.com/{IG_SAVED_FEED}") ] + assert fake.calls[0][2] == {"count": "50"} assert path.read_bytes() == before -def test_real_context_valid_session_and_saved_feed(db: Database, settings: Settings, http) -> None: +@pytest.mark.parametrize( + ("feed_api", "feed_url"), + [ + ("web", f"https://www.instagram.com/{IG_SAVED_FEED}"), + ("iphone", f"https://i.instagram.com/{IG_SAVED_FEED}"), + ], +) +def test_real_context_valid_session_and_saved_feed( + db: Database, settings: Settings, http, feed_api: str, feed_url: str +) -> None: _real_session_file(settings) - fake = http( - (200, {"user": {"pk": 4242, "username": "me"}, "status": "ok"}), - (200, saved_page([ig_iphone_media("r1", 2, video_url="https://cdn/r1.mp4")], "c1")), + pages = [ + ( + 200, + saved_page([ig_iphone_media("r1", 2, video_url="https://cdn/r1.mp4")], "c1"), + {"x-ig-set-www-claim": "hmac.claim-1"}, + ), ( 200, saved_page( [ig_iphone_media("r2", 8, children=[ig_iphone_child(2, "https://cdn/r2.mp4")])] ), ), - ) - collector = _real_collector(db, settings) + ] + user_info = (200, {"user": {"pk": 4242, "username": "me"}, "status": "ok"}) + # web: the check is the first feed page (reused); iphone: user info, then the feed. + fake = http(*(pages if feed_api == "web" else [user_info, *pages])) + collector = _real_collector(db, settings, options=InstagramOptions(feed_api=feed_api)) with collector: stats = collector.collect_saved() assert stats.new == 2 urls = [u for _, u, _ in fake.calls] - assert ( - urls - == [f"https://i.instagram.com/{IG_USER_INFO}"] - + [f"https://i.instagram.com/{IG_SAVED_FEED}"] * 2 - ) - assert fake.calls[2][2]["max_id"] == "c1" + if feed_api == "web": + assert urls == [feed_url] * 2 + else: + assert urls == [f"https://i.instagram.com/{IG_USER_INFO}"] + [feed_url] * 2 + page1 = 0 if feed_api == "web" else 1 + assert fake.calls[page1 + 1][2]["max_id"] == "c1" + first, second = fake.headers[page1], fake.headers[page1 + 1] + if feed_api == "web": + assert fake.calls[page1][2] == {"count": "50"} + assert first["x-ig-app-id"] == "936619743392459" + assert first["x-csrftoken"] == SESSION_COOKIES["csrftoken"] + assert first["x-requested-with"] == "XMLHttpRequest" + assert first["referer"] == "https://www.instagram.com/me/saved/all-posts/" + assert first["host"] == "www.instagram.com" + assert (first["x-ig-www-claim"], second["x-ig-www-claim"]) == ("0", "hmac.claim-1") + assert "x-instagram-ajax" not in first and "x-pigeon-session-id" not in first + else: + assert fake.calls[page1][2] == {"include_igtv_preview": "false"} + assert first["x-ig-app-id"] == "124024574287414" # instaloader's iPad headers + assert "x-requested-with" not in first assert all(LEGACY_LOGIN_HASH not in repr(call) for call in fake.calls) assert all("query_hash" not in call[2] for call in fake.calls) assert get(db, "r1")[2][0].remote_url == "https://cdn/r1.mp4" @@ -934,11 +1266,854 @@ def test_real_context_login_required_falls_back_to_password( db: Database, settings: Settings, http, monkeypatch: pytest.MonkeyPatch ) -> None: _real_session_file(settings) - http((403, {"message": "login_required", "status": "fail"})) + fake = http( + (403, {"message": "login_required", "status": "fail"}), + (200, saved_page([])), # check of the new session (first feed page) + ) logins: list[str] = [] monkeypatch.setattr( instaloader.Instaloader, "login", lambda self, user, passwd: logins.append(user) ) - collector = _real_collector(db, settings) + collector = _real_collector(db, settings, allow_password_login=True) collector.login() assert logins == ["me"] and collector.logged_in + assert [u for _, u, _ in fake.calls] == [f"https://www.instagram.com/{IG_SAVED_FEED}"] * 2 + + +def test_real_context_login_required_never_logs_in_by_default( + db: Database, settings: Settings, http, monkeypatch: pytest.MonkeyPatch +) -> None: + path = _real_session_file(settings) + before = path.read_bytes() + http( + ( + 403, + {"message": "login_required", "status": "fail"}, + {"Set-Cookie": "sessionid=leaked-sid; Path=/"}, + ) + ) + monkeypatch.setattr( + instaloader.Instaloader, + "login", + lambda self, user, passwd: pytest.fail("no password login"), + ) + collector = _real_collector(db, settings) + with pytest.raises(InstagramAuthRequired) as info: + collector.login() + message = str(info.value) + assert "No password login was attempted (session logged out: login_required)" in message + assert "`postparse check instagram --login`" in message + assert "https://" not in message and "leaked-sid" not in message + assert path.read_bytes() == before and not collector.logged_in + + +@pytest.mark.parametrize("feed_api", ["web", "iphone"]) +def test_real_context_feed_fail_status_is_exactly_one_request( + db: Database, settings: Settings, http, feed_api: str +) -> None: + _real_session_file(settings) + fail = {"message": "We're sorry, but something went wrong. Please try again.", "status": "fail"} + user_info = (200, {"user": {"pk": 4242, "username": "me"}, "status": "ok"}) + # web: the session check is the feed page; iphone: user info, then the feed. + answers = [(200, fail)] if feed_api == "web" else [user_info, (200, fail)] + fake = http(*answers) + collector = _real_collector(db, settings, options=InstagramOptions(feed_api=feed_api)) + with pytest.raises(InstagramFeedUnavailable, match="something went wrong"), collector: + collector.collect_saved() + assert len(fake.calls) == len(answers) # no retries + if feed_api == "web": + assert not collector.logged_in # refused in the session check, nothing saved + else: + assert collector.stats.stopped_reason == "feed_unavailable" + assert collector.loader.context.max_connection_attempts == 3 + + +# --------------------------------------------------------------------------- +# No automatic password login (extract runs, re-fetches, API jobs) +# --------------------------------------------------------------------------- + + +def _broken_session_file(loader: FakeLoader) -> FakeLoader: + def broken(username: str, filename: str) -> None: + raise EOFError("Ran out of input") + + loader.load_session_from_file = broken # type: ignore[method-assign] + return loader + + +#: ``(setup, loader factory, reason in the message, feed_api)`` of sessions that +#: cannot be used. +UNUSABLE_SESSIONS = [ + ("no_file", lambda: FakeLoader(session_user="me"), "no session file", "web"), + ( + "file", + lambda: _broken_session_file(FakeLoader(session_user="me")), + "session file unreadable", + "web", + ), + ("file", lambda: FakeLoader(session_user=None), "session logged out: login_required", "web"), + ( + "file", + lambda: FakeLoader(check_error=LoginRequiredException("Redirected to login page.")), + "session logged out: redirected to login page", + "web", + ), + ( + "file", + lambda: FakeLoader(session_cookies={"csrftoken": "x"}), + "session logged out: the session file has no login cookies", + "web", + ), + ( # only the iPhone check names the viewer + "file", + lambda: FakeLoader(session_user="someone_else"), + "session logged out: the session belongs to another account", + "iphone", + ), +] + + +@pytest.mark.parametrize( + "creds", [CREDS, InstagramCredentials("me", None)], ids=["password", "no-password"] +) +@pytest.mark.parametrize( + ("setup", "make_loader", "why", "feed_api"), + UNUSABLE_SESSIONS, + ids=["no-file", "unreadable", "login-required", "login-redirect", "no-cookies", "other-user"], +) +def test_extract_never_logs_in_with_the_password( + db: Database, + settings: Settings, + setup: str, + make_loader: Any, + why: str, + feed_api: str, + creds: InstagramCredentials, +) -> None: + path = _existing_session(settings) if setup == "file" else _session(settings) + loader = make_loader() + events: list = [] + collector = InstagramCollector( + db, + settings, + creds, + InstagramOptions(feed_api=feed_api), # type: ignore[arg-type] + loader_factory=loader_factory(loader), + saved_posts=Feed([]), + sleep=SleepRecorder(), + prompt=lambda _: pytest.fail("must not prompt"), + progress=events.append, + ) + assert collector.allow_password_login is False # the default + + with pytest.raises(InstagramAuthRequired) as info, collector: + pytest.fail("must not enter") + + message = str(info.value) + assert message.startswith(f"No password login was attempted ({why}); automatic password ") + assert "trigger Instagram checkpoints" in message + assert "`postparse check instagram --import-session` in a terminal" in message + assert "`postparse check instagram --login`" in message and "#2487" in message + assert "2FA code" in message and "then retry" in message + assert loader.logins == [] and loader.two_factor_codes == [] and loader.saved == [] + assert events == [] # no "logging in with the password" line + assert not collector.logged_in + if setup == "file": + assert path.read_text() == "original-session" + else: + assert not path.exists() + assert "pw-secret" not in message + + +# --------------------------------------------------------------------------- +# Instagram's reason in messages (sanitized) +# --------------------------------------------------------------------------- + +#: A login redirect whose location carries a query string with cookie-like values. +REDIRECT_WITH_QUERY = ( + 'Query to https://i.instagram.com/api/v1/users/4242/info/ responded with "302 Found" ' + "redirect to https://www.instagram.com/accounts/login/?next=%2Fapi%2F&sessionid=leaked-sid" + "&csrftoken=leaked-csrf#frag" +) + + +@pytest.mark.parametrize( + ("text", "reason"), + [ + ('403 Forbidden - "fail" status, message "login_required"', "login_required"), + ('400 Bad Request - "fail" status, message "checkpoint_required"', "checkpoint_required"), + ('400 Bad Request - "fail" status, message "challenge_required"', "challenge_required"), + ('400 Bad Request - "fail" status, message "feedback_required"', "feedback_required"), + ( + 'Query to https://i.instagram.com/x/ responded with "400 Bad Request": ' + '{"message": "challenge_required", "status": "fail", "checkpoint_url": ' + '"https://i.instagram.com/challenge/?token=leaked-token"}', + "challenge_required", + ), + (REDIRECT_WITH_QUERY, "redirect to https://www.instagram.com/accounts/login/"), + ("Redirected to login page. Use --login or --load-cookies.", "redirected to login page"), + ], + ids=[ + "login_required", + "checkpoint_required", + "challenge_required", + "feedback_required", + "json-body", + "redirect", + "login-redirect", + ], +) +def test_instagram_reason_is_short_and_sanitized(text: str, reason: str) -> None: + from postparse.collectors.instagram.collector import _instagram_message + + full = ( + f"JSON Query to {IG_USER_INFO}: {text} when accessing " + "https://i.instagram.com/x?sessionid=leaked-sid" + ) + result = _instagram_message(full) + assert result == reason + for leak in ("leaked", "sessionid", "csrftoken", "token=", "?", "#"): + assert leak not in result + + +def test_instagram_reason_redacts_secrets_and_is_truncated() -> None: + from postparse.collectors.instagram.collector import MAX_REASON_LENGTH, _instagram_message + + reason = _instagram_message("odd answer sessionid=leaked-sid; csrftoken=leaked " + "x" * 500) + assert "leaked" not in reason and "sessionid=" in reason + assert len(reason) <= MAX_REASON_LENGTH + + +def test_checkpoint_on_session_check_shows_the_reason(db: Database, settings: Settings) -> None: + from instaloader.exceptions import ConnectionException + + _existing_session(settings) + loader = FakeLoader( + check_error=ConnectionException( + f'JSON Query to {IG_USER_INFO}: 400 Bad Request - "fail" status, message ' + f'"checkpoint_required" when accessing https://i.instagram.com/{IG_USER_INFO}' + "?sessionid=leaked-sid" + ) + ) + with pytest.raises(InstagramAuthRequired) as info: + make(db, settings, loader=loader, allow_password_login=False).login() + message = str(info.value) + assert "(Instagram: checkpoint_required)" in message + assert "leaked-sid" not in message and "https://" not in message + assert loader.logins == [] + + +def test_login_redirect_during_feed_shows_the_redirect_without_query( + db: Database, settings: Settings +) -> None: + collector, loader = _feed_collector(db, settings) + first = saved_page([ig_iphone_media("a")], next_max_id="c1") + loader.context.web_responses[IG_SAVED_FEED] = lambda params: ( + AbortDownloadException(REDIRECT_WITH_QUERY) if params.get("max_id") else first + ) + with pytest.raises(InstagramAuthRequired) as info, collector: + collector.collect_saved() + message = str(info.value) + assert "(Instagram: redirect to https://www.instagram.com/accounts/login/)" in message + assert "`postparse check instagram --login`" in message + for leak in ("leaked", "next=", "?", "#frag"): + assert leak not in message + assert collector.stats.stopped_reason == "auth_required" + assert loader.logins == [] + + +def test_throttled_session_check_message_has_no_url(db: Database, settings: Settings) -> None: + _existing_session(settings) + loader = FakeLoader(check_error=ig_error(THROTTLED_401)) + with pytest.raises(InstagramSessionCheckFailed) as info: + make(db, settings, loader=loader).login() + message = str(info.value) + assert "(Please wait a few minutes before you try again.)" in message + assert "https://" not in message and IG_USER_INFO not in message + assert loader.logins == [] + + +# --------------------------------------------------------------------------- +# "429" only as an HTTP status, never inside URLs +# --------------------------------------------------------------------------- + + +def _feed_fail_with_cursor(cursor: str) -> Exception: + from instaloader.exceptions import ConnectionException + + return ConnectionException( + f'JSON Query to {IG_SAVED_FEED}: 200 OK - "fail" status, message "We\'re sorry, but ' + f'something went wrong." when accessing https://www.instagram.com/{IG_SAVED_FEED}' + f"?count=50&max_id={cursor}" + ) + + +@pytest.mark.parametrize("cursor", ["3429876543210", "429", "QVFD429-x_429"]) +def test_429_inside_the_url_is_not_a_rate_limit( + db: Database, settings: Settings, cursor: str +) -> None: + collector, loader = _feed_collector(db, settings) + pages = saved_feed_pages(saved_page([ig_iphone_media("a")], next_max_id=cursor)) + loader.context.web_responses[IG_SAVED_FEED] = lambda params: ( + _feed_fail_with_cursor(cursor) if params.get("max_id") else pages(params) + ) + with pytest.raises(InstagramFeedUnavailable) as info, collector: + collector.collect_saved() + assert "something went wrong" in str(info.value) and "max_id" not in str(info.value) + assert collector.stats.stopped_reason == "feed_unavailable" + assert count(db) == 1 + + +@pytest.mark.parametrize( + "error", + [ + TooManyRequestsException("429 Too Many Requests when accessing https://x/?max_id=1"), + ig_error("429 Too Many Requests", IG_SAVED_FEED), + ig_error('429 - "fail" status, message "slow down"', IG_SAVED_FEED), + ig_error(THROTTLED_401, IG_SAVED_FEED), + ], + ids=["exception", "status-429", "status-429-bare", "401-please-wait"], +) +def test_real_rate_limits_are_still_detected( + db: Database, settings: Settings, error: Exception +) -> None: + collector, loader = _feed_collector(db, settings) + first = saved_page([ig_iphone_media("a")], next_max_id="c1") + loader.context.web_responses[IG_SAVED_FEED] = lambda params: ( + error if params.get("max_id") else first + ) + with pytest.raises(InstagramRateLimited) as info, collector: + collector.collect_saved() + assert not isinstance(info.value, InstagramFeedUnavailable) + assert collector.stats.stopped_reason == "rate_limited" + assert "https://" not in str(info.value) + + +def test_session_check_ids_in_the_path_are_not_a_throttle() -> None: + """A user id containing 429 does not turn "login_required" into a throttle.""" + from postparse.collectors.instagram.collector import _session_check_verdict + + exc = ig_error(LOGGED_OUT_403, "api/v1/users/14290/info/") + assert "429" in str(exc) + assert _session_check_verdict(exc) == "logged_out" + assert _session_check_verdict(ig_error("429 Too Many Requests")) == "failed" + + +# --------------------------------------------------------------------------- +# Password login: verified before it is saved (instaloader issue #2487) +# --------------------------------------------------------------------------- + + +def test_placeholder_cookies_are_dropped() -> None: + from postparse.collectors.instagram.collector import _drop_placeholder_cookies + + from .fakes import LOGIN_PLACEHOLDERS + + session = requests.Session() + session.cookies.update(LOGIN_PLACEHOLDERS) # as InstaloaderContext.login does + session.cookies.set("csrftoken", "real-csrf", domain=".instagram.com", path="/") + session.cookies.set("mid", "real-mid", domain=".instagram.com", path="/") + session.cookies.set("rur", "", domain=".instagram.com", path="/") # set by Instagram: kept + + assert _drop_placeholder_cookies(session.cookies) == 5 + kept = {(c.name, c.value, c.domain) for c in session.cookies} + assert kept == { + ("ig_pr", "1", ""), + ("ig_vw", "1920", ""), + ("ig_cb", "1", ""), + ("csrftoken", "real-csrf", ".instagram.com"), + ("mid", "real-mid", ".instagram.com"), + ("rur", "", ".instagram.com"), + } + assert _drop_placeholder_cookies(session.cookies) == 0 + + +@pytest.mark.parametrize("setup", ["logged_out", "no_file"]) +def test_password_login_without_session_cookie_saves_nothing( + db: Database, settings: Settings, setup: str +) -> None: + path = _existing_session(settings) if setup == "logged_out" else _session(settings) + # Instagram answered "authenticated" but set no sessionid / ds_user_id cookie. + loader = FakeLoader(session_user=None, login_cookies={"csrftoken": "c-new", "mid": "m"}) + collector = make(db, settings, loader=loader) + + with pytest.raises(InstagramAuthRequired) as info, collector: + pytest.fail("must not enter") + + message = str(info.value) + assert message.startswith( + "Instagram accepted the password but returned no session cookie " + "(instaloader issue #2487); nothing was saved." + ) + assert "`postparse check instagram --import-session`" in message + assert loader.logins == ["me"] and loader.saved == [] and not collector.logged_in + # Only the check of the session file; no request with the cookie-less session. + assert len(loader.context.requests) == (1 if setup == "logged_out" else 0) + if setup == "logged_out": + assert path.read_text() == "original-session" + else: + assert not path.exists() + assert "pw-secret" not in message + + +@pytest.mark.parametrize( + ("loader", "why", "feed_api"), + [ + ( + FakeLoader(session_user=None, new_user=None), + "session logged out: login_required", + "web", + ), + ( + FakeLoader(session_user=None, new_user=None), + "session logged out: login_required", + "iphone", + ), + ( + FakeLoader(session_user=None, new_user="someone_else"), + "session logged out: the session belongs to another account", + "iphone", + ), + ], + ids=["logged-out", "logged-out-iphone", "other-user-iphone"], +) +def test_password_login_with_a_failing_check_saves_nothing( + db: Database, settings: Settings, loader: FakeLoader, why: str, feed_api: str +) -> None: + path = _existing_session(settings) + options = InstagramOptions(feed_api=feed_api) # type: ignore[arg-type] + collector = make(db, settings, loader=loader, options=options) + with pytest.raises(InstagramAuthRequired) as info: + collector.login() + assert str(info.value).startswith( + "Instagram accepted the password, but the session check after the password login " + f"failed ({why}); nothing was saved." + ) + assert loader.logins == ["me"] and loader.saved == [] and not collector.logged_in + assert len(loader.check_requests()) == 2 # session file, then the new session + assert path.read_text() == "original-session" + + +def test_password_login_with_a_throttled_check_saves_nothing( + db: Database, settings: Settings +) -> None: + path = _existing_session(settings) + loader = FakeLoader(session_user=None, new_check_error=ig_error(THROTTLED_401)) + collector = make(db, settings, loader=loader) + with pytest.raises(InstagramSessionCheckFailed) as info: + collector.login() + message = str(info.value) + assert message.startswith("Instagram did not confirm the session after the password login") + assert "No password login was attempted" not in message and "Nothing was saved" in message + assert info.value.after == "password login" + assert loader.saved == [] and not collector.logged_in + assert path.read_text() == "original-session" + + +def test_password_login_is_verified_before_it_is_saved(db: Database, settings: Settings) -> None: + path = _existing_session(settings) + loader = FakeLoader(session_user=None, login_cookies={**SESSION_COOKIES, "csrftoken": "c-new"}) + with make(db, settings, loader=loader) as collector: + assert collector.logged_in + assert loader.saved == [str(path)] # saved after the check + _check_file, check_new = loader.check_requests() + assert check_new[0] == "web" and check_new[3] == 1 + # The web client follows the new session (its csrftoken), not the loaded file. + assert loader.context.web_headers[-1]["X-CSRFToken"] == "c-new" + cookies = loader.save_session() + assert cookies["sessionid"] == SESSION_COOKIES["sessionid"] + assert {"s_network", "ig_pr"} & set(cookies) == {"ig_pr"} # placeholders gone, rest kept + + +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({"login_cookies": {"csrftoken": "c"}}, "returned no session cookie"), + ({"new_user": None}, "session check after the password login failed"), + ], + ids=["no-cookie", "logged-out"], +) +def test_two_factor_login_is_verified_the_same_way( + db: Database, settings: Settings, kwargs: dict, message: str +) -> None: + loader = FakeLoader(login_error=TwoFactorAuthRequiredException("2fa"), **kwargs) + collector = make(db, settings, loader=loader, prompt=lambda _: "123456") + with pytest.raises(InstagramAuthRequired, match=message): + collector.login() + assert loader.two_factor_codes == ["123456"] + assert loader.saved == [] and not collector.logged_in + assert not _session(settings).exists() + + +# --------------------------------------------------------------------------- +# Session check routing: web API by default, iPhone API with feed_api="iphone" +# --------------------------------------------------------------------------- + + +@FEED_APIS +def test_session_check_uses_the_feed_api(db: Database, settings: Settings, feed_api: str) -> None: + _existing_session(settings) + loader = FakeLoader(session_user="me") + collector = make(db, settings, loader=loader, options=InstagramOptions(feed_api=feed_api)) + collector.login() + assert [r[:2] for r in loader.context.requests] == [CHECK[feed_api]] + assert loader.context.requests[0][3] == 1 + if feed_api == "iphone": + assert loader.context.web_headers == [] # no web request at all + return + # web: the first saved-feed page, exactly as the walk asks for it; no user info. + assert loader.context.requests[0][2] == BASE_PARAMS["web"] + headers = {k.lower(): v for k, v in loader.context.web_headers[0].items()} + assert headers["x-ig-app-id"] == "936619743392459" + assert headers["x-asbd-id"] == "129477" + assert headers["x-csrftoken"] == SESSION_COOKIES["csrftoken"] + assert headers["x-ig-www-claim"] == "0" + assert headers["x-requested-with"] == "XMLHttpRequest" + assert headers["referer"] == SAVED_REFERER + assert headers["origin"] == "https://www.instagram.com" + assert headers["accept"] == "*/*" + assert headers["sec-fetch-mode"] == "cors" and headers["sec-fetch-site"] == "same-origin" + assert headers["sec-fetch-dest"] == "empty" + assert "x-instagram-ajax" not in headers + + +def test_real_context_web_check_and_feed_share_one_client( + db: Database, settings: Settings, http +) -> None: + _real_session_file(settings) + fake = http( + ( + 200, + saved_page([ig_iphone_media("s1")], "c1"), + {"x-ig-set-www-claim": "hmac.from-check"}, + ), + (200, saved_page([ig_iphone_media("s2")])), + ) + collector = _real_collector(db, settings) + with collector: + stats = collector.collect_saved() + assert stats.new == 2 + # The check's page is page 1 of the walk; only page 2 is requested afterwards. + assert [u for _, u, _ in fake.calls] == [f"https://www.instagram.com/{IG_SAVED_FEED}"] * 2 + assert fake.calls[0][2] == {"count": "50"} + assert fake.calls[1][2] == {"count": "50", "max_id": "c1"} + check, feed = fake.headers + assert check["referer"] == SAVED_REFERER + assert check["x-ig-app-id"] == "936619743392459" and check["x-ig-www-claim"] == "0" + assert check["x-csrftoken"] == SESSION_COOKIES["csrftoken"] + assert feed["referer"] == SAVED_REFERER + assert feed["x-ig-www-claim"] == "hmac.from-check" # one client identity per run + assert "x-pigeon-session-id" not in check # no iPad headers + + +# --------------------------------------------------------------------------- +# Importing the browser session (no password) +# --------------------------------------------------------------------------- + +#: A fake ``sessionid`` as the browser shows it (URL-encoded). +BROWSER_SID = f"{IG_USER_ID}%3AsecretBrowserSid%3A27%3AAYleakyleaky" +BROWSER_CSRF = "browsercsrfLEAK0123456789abcdefX" + + +def _assert_no_cookie_values(*texts: str) -> None: + for text in texts: + for leak in ("secretBrowserSid", "AYleakyleaky", BROWSER_CSRF): + assert leak not in text + + +def test_import_session_saves_a_verified_browser_session( + db: Database, settings: Settings, caplog: pytest.LogCaptureFixture +) -> None: + import logging + + caplog.set_level(logging.DEBUG) + events: list = [] + loader = FakeLoader() + collector = make( + db, + settings, + loader=loader, + creds=InstagramCredentials("me", None), + allow_password_login=False, + progress=events.append, + ) + + collector.import_session(f" {BROWSER_SID}\n", BROWSER_CSRF) + + assert loader.imported == [ + ("me", {"sessionid": BROWSER_SID, "ds_user_id": IG_USER_ID, "csrftoken": BROWSER_CSRF}) + ] + assert [r[:2] for r in loader.context.requests] == [CHECK["web"]] # exactly one + assert loader.context.requests[0][2:] == ({"count": "50"}, 1) + headers = {k.lower(): v for k, v in loader.context.web_headers[0].items()} + assert headers["x-csrftoken"] == BROWSER_CSRF and headers["x-ig-app-id"] == "936619743392459" + assert headers["referer"] == SAVED_REFERER + assert collector.logged_in and loader.saved == [str(_session(settings))] + assert _session(settings).read_text() == "fake-session" + assert loader.logins == [] and loader.two_factor_codes == [] + assert [(e.phase, e.message) for e in events] == [ + ("session", "Browser session imported and verified (no password login)") + ] + _assert_no_cookie_values(caplog.text, repr(events)) + + +def test_import_session_with_the_iphone_api_checks_on_i_instagram( + db: Database, settings: Settings +) -> None: + loader = FakeLoader() + collector = make(db, settings, loader=loader, options=InstagramOptions(feed_api="iphone")) + collector.import_session(BROWSER_SID, BROWSER_CSRF) + assert [r[:2] for r in loader.context.requests] == [("iphone", IG_USER_INFO)] + assert collector.logged_in + + +@pytest.mark.parametrize( + "pasted", + [ + f"{IG_USER_ID}:secretBrowserSid:27:AYleakyleaky", # URL-decoded copy + f'"{BROWSER_SID}"', + f"'{IG_USER_ID}:secretBrowserSid%3A27:AYleakyleaky' ", + ], + ids=["decoded", "double-quoted", "mixed"], +) +def test_import_session_normalizes_the_value(db: Database, settings: Settings, pasted: str) -> None: + from postparse.collectors.instagram import parse_sessionid + + assert parse_sessionid(pasted) == (BROWSER_SID, IG_USER_ID) + loader = FakeLoader() + make(db, settings, loader=loader).import_session(pasted, BROWSER_CSRF) + assert loader.imported[0][1]["sessionid"] == BROWSER_SID + assert loader.imported[0][1]["ds_user_id"] == IG_USER_ID + + +@pytest.mark.parametrize( + "pasted", + ["", " ", "secretBrowserSid", "4242", "4242%3A", "x4242%3AsecretBrowserSid", "4242%3Aa b"], +) +def test_malformed_sessionid_is_rejected_without_the_value( + db: Database, settings: Settings, pasted: str +) -> None: + from postparse.collectors.instagram import InvalidSessionCookie + + loader = FakeLoader() + collector = make(db, settings, loader=loader) + with pytest.raises(InvalidSessionCookie) as info: + collector.import_session(pasted, BROWSER_CSRF) + message = str(info.value) + assert "does not look like an Instagram sessionid cookie (expected %3A…)" in message + _assert_no_cookie_values(message) + assert loader.imported == [] and loader.context.requests == [] and loader.saved == [] + + +def test_malformed_csrftoken_is_rejected(db: Database, settings: Settings) -> None: + from postparse.collectors.instagram import InvalidSessionCookie + + loader = FakeLoader() + with pytest.raises(InvalidSessionCookie, match="csrftoken") as info: + make(db, settings, loader=loader).import_session(BROWSER_SID, "bad token;x") + _assert_no_cookie_values(str(info.value)) + assert loader.context.requests == [] + + +@pytest.mark.parametrize("csrftoken", [None, "", " "]) +def test_import_session_generates_a_csrftoken( + db: Database, settings: Settings, csrftoken: str | None +) -> None: + tokens = [] + for _ in range(2): + loader = FakeLoader() + make(db, settings, loader=loader).import_session(BROWSER_SID, csrftoken) + token = loader.imported[0][1]["csrftoken"] + assert len(token) == 32 and token.isalnum() and token.isascii() + assert loader.context.web_headers[0]["X-CSRFToken"] == token + tokens.append(token) + assert tokens[0] != tokens[1] + + +@pytest.mark.parametrize( + ("loader", "why", "feed_api"), + [ + (FakeLoader(new_user=None), "session logged out: login_required", "web"), + (FakeLoader(new_user=None), "session logged out: login_required", "iphone"), + ( + FakeLoader(new_user="someone_else"), + "session logged out: the session belongs to another account", + "iphone", + ), + ], + ids=["logged-out", "logged-out-iphone", "other-user-iphone"], +) +def test_unusable_imported_session_saves_nothing( + db: Database, settings: Settings, loader: FakeLoader, why: str, feed_api: str +) -> None: + path = _existing_session(settings) + options = InstagramOptions(feed_api=feed_api) # type: ignore[arg-type] + collector = make(db, settings, loader=loader, options=options) + with pytest.raises(InstagramAuthRequired) as info: + collector.import_session(BROWSER_SID, BROWSER_CSRF) + message = str(info.value) + assert message.startswith(f"The imported session is not usable ({why}); nothing was saved.") + _assert_no_cookie_values(message) + assert loader.saved == [] and loader.logins == [] and not collector.logged_in + assert len(loader.context.requests) == 1 + assert path.read_text() == "original-session" + + +@pytest.mark.parametrize( + ("error", "expected"), + [ + (ig_error(THROTTLED_401, IG_SAVED_FEED), InstagramSessionCheckFailed), + (ig_error("429 Too Many Requests", IG_SAVED_FEED), InstagramSessionCheckFailed), + ( + ig_error('400 Bad Request - "fail" status, message "checkpoint_required"'), + InstagramAuthRequired, + ), + (ig_error(FEED_FAIL_200, IG_SAVED_FEED), InstagramFeedUnavailable), + ], + ids=["throttled", "429", "checkpoint", "fail-status"], +) +def test_failed_check_of_an_imported_session_saves_nothing( + db: Database, settings: Settings, error: Exception, expected: type +) -> None: + path = _existing_session(settings) + loader = FakeLoader(new_check_error=error) + collector = make(db, settings, loader=loader) + with pytest.raises(expected) as info: + collector.import_session(BROWSER_SID, BROWSER_CSRF) + if expected is InstagramSessionCheckFailed: + assert "after the session import" in str(info.value) + assert "No password login was attempted" not in str(info.value) + _assert_no_cookie_values(str(info.value)) + assert loader.saved == [] and loader.logins == [] and not collector.logged_in + assert len(loader.context.requests) == 1 + assert loader.context.max_connection_attempts == 3 + assert path.read_text() == "original-session" + + +@pytest.mark.parametrize( + "text", + [ + f'odd answer {{"sessionid": "{BROWSER_SID}", "csrftoken": "{BROWSER_CSRF}"}}', + f"Cookie: sessionid={BROWSER_SID}; csrftoken={BROWSER_CSRF}", + f"unexpected value {BROWSER_SID} in the answer", + f"decoded {IG_USER_ID}:secretBrowserSid:27:AYleakyleaky here", + ], + ids=["json", "header", "bare-value", "bare-decoded"], +) +def test_instagram_reason_redacts_session_cookie_values(text: str) -> None: + from postparse.collectors.instagram.collector import _instagram_message + + reason = _instagram_message(text) + _assert_no_cookie_values(reason) + assert "" in reason + + +# --------------------------------------------------------------------------- +# Web: the session check's feed page is the walk's first page +# --------------------------------------------------------------------------- + + +def test_web_run_with_a_valid_session_is_exactly_one_request( + db: Database, settings: Settings +) -> None: + """``extract --limit 1 --stop-after-known 1``: the check's page is enough.""" + store(db, "k1") + collector, loader = _feed_collector( + db, + settings, + saved_page([ig_iphone_media("n1"), ig_iphone_media("k1")], next_max_id="c1"), + saved_page([ig_iphone_media("n2")]), + ) + with collector: + stats = collector.collect_saved(limit=1, stop_after_known=1) + assert (stats.new, stats.stopped_reason) == (1, "limit") + assert count(db) == 2 # n1 stored, k1 was known + assert loader.context.requests == [("web", IG_SAVED_FEED, {"count": "50"}, 1)] + + +def test_web_walk_continues_after_the_checks_page_with_its_cursor( + db: Database, settings: Settings +) -> None: + collector, loader = _feed_collector( + db, + settings, + saved_page([ig_iphone_media("a")], next_max_id="cursor-1"), + saved_page([ig_iphone_media("b")]), + ) + with collector: + stats = collector.collect_saved() + assert stats.new == 2 + assert _feed_requests(loader) == [{"count": "50"}, {"count": "50", "max_id": "cursor-1"}] + assert loader.check_requests() == loader.context.requests[:1] + + +def test_web_checks_page_is_used_once(db: Database, settings: Settings) -> None: + collector, loader = _feed_collector(db, settings, saved_page([ig_iphone_media("a")])) + with collector: + collector.collect_saved() + collector.collect_saved() # a second walk asks for page 1 itself + assert _feed_requests(loader) == [{"count": "50"}, {"count": "50"}] + + +def test_web_checks_page_is_dropped_when_the_session_changes( + db: Database, settings: Settings +) -> None: + collector, loader = _feed_collector(db, settings, saved_page([ig_iphone_media("a")])) + with collector: + loader.context.set_cookies(SESSION_COOKIES) # instaloader replaced its session + collector.collect_saved() + assert _feed_requests(loader) == [{"count": "50"}, {"count": "50"}] + + +def test_web_password_login_reuses_the_page_of_the_new_session( + db: Database, settings: Settings +) -> None: + _existing_session(settings) + loader = FakeLoader(session_user=None) # the session file is logged out + loader.context.web_responses[IG_SAVED_FEED] = saved_feed_pages( + saved_page([ig_iphone_media("a")]) + ) + collector = InstagramCollector( + db, + settings, + CREDS, + allow_password_login=True, + loader_factory=loader_factory(loader), + sleep=SleepRecorder(), + ) + with collector: + collector.collect_saved() + assert loader.logins == ["me"] and count(db) == 1 + # Check of the file (logged out), check of the new session = the walk's page 1. + assert _feed_requests(loader) == [{"count": "50"}, {"count": "50"}] + + +def test_injected_saved_posts_ignore_the_checks_page(db: Database, settings: Settings) -> None: + _existing_session(settings) + loader = FakeLoader(session_user="me") + loader.context.web_responses[IG_SAVED_FEED] = saved_page([ig_iphone_media("cached")]) + feed = Feed([ig_post(ig_node("injected"))]) + with make(db, settings, feed, loader=loader) as collector: + collector.collect_saved() + assert feed.consumed == 1 and count(db) == 1 and get(db, "injected") + assert len(loader.context.requests) == 1 # only the check + + +@FEED_APIS +def test_fetch_post_needs_no_feed_request(db: Database, settings: Settings, feed_api: str) -> None: + """A transcription re-fetch: the session check, then the post itself.""" + _existing_session(settings) + loader = FakeLoader(session_user="me") + fetched: list[str] = [] + + def from_shortcode(_loader: Any, code: str) -> Any: + fetched.append(code) + return ig_post(ig_node(code)) + + options = InstagramOptions(feed_api=feed_api) # type: ignore[arg-type] + with make( + db, settings, loader=loader, options=options, post_from_shortcode=from_shortcode + ) as collector: + collector.fetch_post("p1") + assert fetched == ["p1"] + assert [r[:2] for r in loader.context.requests] == [CHECK[feed_api]] diff --git a/tests/unit/services/test_extraction.py b/tests/unit/services/test_extraction.py index 2f80188..614c383 100644 --- a/tests/unit/services/test_extraction.py +++ b/tests/unit/services/test_extraction.py @@ -30,7 +30,12 @@ @pytest.fixture def settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Settings: monkeypatch.chdir(tmp_path) - return Settings(data_dir=tmp_path / "data") + settings = Settings(data_dir=tmp_path / "data") + assert settings.sessions_dir is not None + session = settings.sessions_dir / "instagram_me" # a verified saved session + session.parent.mkdir(parents=True) + session.write_text("original-session") + return settings @pytest.fixture @@ -48,7 +53,7 @@ def service(db, settings, env, client=None, feed=None, loader=None, **ig) -> Ext "sleep": no_sleep, }, instagram_overrides={ - "loader_factory": loader_factory(loader or FakeLoader()), + "loader_factory": loader_factory(loader or FakeLoader(session_user="me")), "saved_posts": feed or Feed([]), "sleep": SleepRecorder(), **ig, @@ -96,6 +101,21 @@ def test_instagram_rate_limit_gives_partial_report(db: Database, settings: Setti assert "rate limit" in report.error +def test_instagram_feed_unavailable_gives_partial_report(db: Database, settings: Settings) -> None: + from postparse.collectors.base import InstagramFeedUnavailable + + feed = Feed( + [ig_post(ig_node(c)) for c in "abcd"], + fail_at=3, + error=InstagramFeedUnavailable("web", "something went wrong"), + ) + report = service(db, settings, IG_ENV, feed=feed).instagram(batch_size=2) + + assert report.stopped_reason == "feed_unavailable" and not report.ok + assert report.new == 3 and report.last_external_id == "c" + assert "session is fine" in report.error + + def test_instagram_refresh_dates_keeps_collect_reason(db: Database, settings: Settings) -> None: from postparse.core.db.models import InstagramDetail, ItemUpsert from postparse.core.db.repos import ItemsRepo @@ -126,3 +146,46 @@ def test_instagram_missing_username(db: Database, settings: Settings) -> None: report = service(db, settings, {}).instagram() assert report.stopped_reason == "auth_required" assert "INSTAGRAM_USERNAME" in report.error + + +# -- no automatic password login (CLI extract and API jobs) ------------------------- + + +@pytest.mark.parametrize( + "overrides", [{}, {"allow_password_login": True}], ids=["default", "forced"] +) +def test_instagram_never_logs_in_with_the_password( + db: Database, settings: Settings, overrides: dict +) -> None: + loader = FakeLoader(session_user=None) # the saved session is logged out + report = service(db, settings, IG_ENV, loader=loader, **overrides).instagram() + + assert report.stopped_reason == "auth_required" and not report.ok + assert "No password login was attempted (session logged out: login_required)" in report.error + assert "`postparse check instagram --login`" in report.error + assert loader.logins == [] and loader.two_factor_codes == [] and loader.saved == [] + assert (settings.sessions_dir / "instagram_me").read_text() == "original-session" + + +def test_api_instagram_job_never_logs_in_with_the_password( + db: Database, settings: Settings +) -> None: + import asyncio + + from postparse.api.jobs.kinds import instagram_extract_job, with_credentials + + (settings.sessions_dir / "instagram_me").unlink() + loader = FakeLoader(session_user="me") + shared = service(db, settings, {}, loader=loader) + job = instagram_extract_job( + with_credentials(shared, {"INSTAGRAM_USERNAME": "me", "INSTAGRAM_PASSWORD": "pw"}), + limit=None, + stop_after_known=20, + username="me", + ) + report = asyncio.run(job(lambda *args: None)) + + assert report.stopped_reason == "auth_required" + assert "No password login was attempted (no session file)" in report.error + assert loader.logins == [] and loader.saved == [] + assert not (settings.sessions_dir / "instagram_me").exists() diff --git a/tests/unit/services/test_transcription_service.py b/tests/unit/services/test_transcription_service.py index c4ceafb..18b2108 100644 --- a/tests/unit/services/test_transcription_service.py +++ b/tests/unit/services/test_transcription_service.py @@ -423,3 +423,31 @@ def test_circuit_breaker_option_from_config() -> None: config = SimpleNamespace(get_section=lambda name: {"max_consecutive_refetch_failures": 5}) assert TranscriptionOptions.from_config(config).max_consecutive_refetch_failures == 5 assert TranscriptionOptions().max_consecutive_refetch_failures == 3 + + +@pytest.mark.parametrize( + "overrides", [{}, {"allow_password_login": True}], ids=["default", "forced"] +) +def test_refetch_collector_never_logs_in_with_the_password( + db: Database, settings: Settings, overrides: dict[str, Any] +) -> None: + from tests.unit.collectors.fakes import FakeLoader, loader_factory + + assert settings.sessions_dir is not None + session = settings.sessions_dir / "instagram_me" + session.parent.mkdir(parents=True) + session.write_text("original-session") + loader = FakeLoader(session_user=None) # logged out + svc = TranscriptionService( + db, + settings, + env={"INSTAGRAM_USERNAME": "me", "INSTAGRAM_PASSWORD": "pw"}, + instagram_overrides={"loader_factory": loader_factory(loader), **overrides}, + interactive=True, + ) + collector = svc._make_collector() + assert collector.allow_password_login is False + with pytest.raises(InstagramAuthRequired, match="No password login was attempted"): + collector.login() + assert loader.logins == [] and loader.two_factor_codes == [] and loader.saved == [] + assert session.read_text() == "original-session"