diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 0c16cbca70..d8a9efc662 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -334,7 +334,7 @@ improvising or retrying when something is off. | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](packages/flow/benchmark/skill_cache/README.md) | | Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (merged 2026-11-14), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | On main ([#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294), merged 2026-11-20) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | -| Sign-ins with a second factor: a `second_factor` step (`code` for a text-message, email or authenticator code, `approval` for a push approval) waits for a person when it runs, through the runner's control plane or a local command. Before anyone is asked, the focused field must be an empty `autocomplete="one-time-code"` input and the page draws it as dots; after the answer the same field must still have focus and be empty. The code is filled once into that element (a field split into one box per character is refused), never retried, and never stored, logged, shown to a model or drawn on screen. No source, a late or malformed answer, a decline, a field that changed, or a backend that can't bind the field stops the step before typing with a closed `second_factor_*` code; an older runtime refuses the bundle. Over the control plane the code is sealed in the person's browser to a one-step key the control plane can't open. The wrap recorder finds a code field from `autocomplete="one-time-code"` alone; it doesn't detect push approvals, and only the local browser backend can take a code | In PR | Synthetic (a notes app with an authenticator page in headless Chromium through the real wrap path: first run, canary, admission, publish staging, a cached run and a declined run, with a byte scan for the TOTP secret and recent codes; headless-browser tests that two codes render the same pixels and that a focus change, a prefilled field or an auto-submitting page are handled; unit tests for both sources, late answers, the step shape and every refusal). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, `openadapt_flow.runtime.second_factor_step`, [SECOND_FACTOR.md](packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.py`, `packages/flow/tests/test_second_factor_browser.py`, `packages/flow/tests/e2e/test_wrap_second_factor_e2e.py` | +| Sign-ins with a second factor: a `second_factor` step (`code` for a text-message, email or authenticator code, `approval` for a push approval) waits for a person when it runs, through the runner's control plane, a local command, or the run's own terminal when it has one (on a POSIX terminal or the Windows console; the code is never echoed, and normal input comes back however the read ends). Before anyone is asked, the focused field must be an empty `autocomplete="one-time-code"` input and the page draws it as dots; after the answer the same field must still have focus and be empty. The code is filled once into that element (a field split into one box per character is refused), never retried, and never stored, logged, shown to a model or drawn on screen. No source, a late or malformed answer, a decline, a field that changed, or a backend that can't bind the field stops the step before typing with a closed `second_factor_*` code; an older runtime refuses the bundle. Over the control plane the code is sealed in the person's browser to a one-step key the control plane can't open. The wrap recorder finds a code field from `autocomplete="one-time-code"` alone; it doesn't detect push approvals, and only the local browser backend can take a code | In PR | Synthetic (a notes app with an authenticator page in headless Chromium through the real wrap path: first run, canary, admission, publish staging, a cached run and a declined run, with a byte scan for the TOTP secret and recent codes; headless-browser tests that two codes render the same pixels and that a focus change, a prefilled field or an auto-submitting page are handled; unit tests for every source, late answers, the step shape and every refusal; pty tests that a terminal prompt hides the code, restores echo after a timeout and answers the next prompt; the Windows console reader's deadline and discard logic on a fake keyboard). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, `openadapt_flow.runtime.second_factor_step`, [SECOND_FACTOR.md](packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.py`, `packages/flow/tests/test_second_factor_browser.py`, `packages/flow/tests/test_second_factor_terminal.py`, `packages/flow/tests/test_second_factor_console.py`, `packages/flow/tests/e2e/test_wrap_second_factor_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](packages/flow/docs/AGENT_FRAMEWORKS.md) | | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | | Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks. The approval card shows each field's value now, the value the held save sends (read by the app's `write_adapter`; without one the card says the values were not read and not checked before saving, and shows a screenshot and the form's values on screen taken when the save is held; with neither a value nor a readable screenshot no approval is offered and the run ends `ESCALATED` `values_unread`), the task's value beside it and its source; each save gets a ledger row with no values whose outcome follows the guard's own verdict, and a 0600 diff; the read-back goes through a `ReadbackProvider` where only an independent read can verify | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)); card values, ledger row and `ReadbackProvider` in PR [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults; the approval card in headless Chromium with and without MockMed's write adapter) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](packages/flow/docs/GUARD_AN_AGENT.md) | diff --git a/llms-full.txt b/llms-full.txt index 06357ddcad..38ff0c1686 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -794,7 +794,7 @@ improvising or retrying when something is off. | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/skill_cache/README.md) | | Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (merged 2026-11-14), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | On main ([#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294), merged 2026-11-20) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | -| Sign-ins with a second factor: a `second_factor` step (`code` for a text-message, email or authenticator code, `approval` for a push approval) waits for a person when it runs, through the runner's control plane or a local command. Before anyone is asked, the focused field must be an empty `autocomplete="one-time-code"` input and the page draws it as dots; after the answer the same field must still have focus and be empty. The code is filled once into that element (a field split into one box per character is refused), never retried, and never stored, logged, shown to a model or drawn on screen. No source, a late or malformed answer, a decline, a field that changed, or a backend that can't bind the field stops the step before typing with a closed `second_factor_*` code; an older runtime refuses the bundle. Over the control plane the code is sealed in the person's browser to a one-step key the control plane can't open. The wrap recorder finds a code field from `autocomplete="one-time-code"` alone; it doesn't detect push approvals, and only the local browser backend can take a code | In PR | Synthetic (a notes app with an authenticator page in headless Chromium through the real wrap path: first run, canary, admission, publish staging, a cached run and a declined run, with a byte scan for the TOTP secret and recent codes; headless-browser tests that two codes render the same pixels and that a focus change, a prefilled field or an auto-submitting page are handled; unit tests for both sources, late answers, the step shape and every refusal). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, `openadapt_flow.runtime.second_factor_step`, [SECOND_FACTOR.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.py`, `packages/flow/tests/test_second_factor_browser.py`, `packages/flow/tests/e2e/test_wrap_second_factor_e2e.py` | +| Sign-ins with a second factor: a `second_factor` step (`code` for a text-message, email or authenticator code, `approval` for a push approval) waits for a person when it runs, through the runner's control plane, a local command, or the run's own terminal when it has one (on a POSIX terminal or the Windows console; the code is never echoed, and normal input comes back however the read ends). Before anyone is asked, the focused field must be an empty `autocomplete="one-time-code"` input and the page draws it as dots; after the answer the same field must still have focus and be empty. The code is filled once into that element (a field split into one box per character is refused), never retried, and never stored, logged, shown to a model or drawn on screen. No source, a late or malformed answer, a decline, a field that changed, or a backend that can't bind the field stops the step before typing with a closed `second_factor_*` code; an older runtime refuses the bundle. Over the control plane the code is sealed in the person's browser to a one-step key the control plane can't open. The wrap recorder finds a code field from `autocomplete="one-time-code"` alone; it doesn't detect push approvals, and only the local browser backend can take a code | In PR | Synthetic (a notes app with an authenticator page in headless Chromium through the real wrap path: first run, canary, admission, publish staging, a cached run and a declined run, with a byte scan for the TOTP secret and recent codes; headless-browser tests that two codes render the same pixels and that a focus change, a prefilled field or an auto-submitting page are handled; unit tests for every source, late answers, the step shape and every refusal; pty tests that a terminal prompt hides the code, restores echo after a timeout and answers the next prompt; the Windows console reader's deadline and discard logic on a fake keyboard). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, `openadapt_flow.runtime.second_factor_step`, [SECOND_FACTOR.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.py`, `packages/flow/tests/test_second_factor_browser.py`, `packages/flow/tests/test_second_factor_terminal.py`, `packages/flow/tests/test_second_factor_console.py`, `packages/flow/tests/e2e/test_wrap_second_factor_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AGENT_FRAMEWORKS.md) | | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | | Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks. The approval card shows each field's value now, the value the held save sends (read by the app's `write_adapter`; without one the card says the values were not read and not checked before saving, and shows a screenshot and the form's values on screen taken when the save is held; with neither a value nor a readable screenshot no approval is offered and the run ends `ESCALATED` `values_unread`), the task's value beside it and its source; each save gets a ledger row with no values whose outcome follows the guard's own verdict, and a 0600 diff; the read-back goes through a `ReadbackProvider` where only an independent read can verify | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)); card values, ledger row and `ReadbackProvider` in PR [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults; the approval card in headless Chromium with and without MockMed's write adapter) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GUARD_AN_AGENT.md) | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 10fdc26d6b..a2b6e104dd 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -41,6 +41,15 @@ form's submit counts as a sign-in only once, right after a username-and-password sign-in. A field split into one box per character is refused. See docs/SECOND_FACTOR.md. +- An interactive run (a terminal on stdin and stderr) asks for a sign-in's + second factor at that terminal when no control plane or command is set. A + code is read without echo, under the step's deadline, in the calling + thread; echo comes back on when the read ends, including on a timeout, and + input typed before the prompt is discarded. On Windows the console is read + one key at a time with `msvcrt.getwch`, which never echoes, under the same + deadline and discard rules. A run without a terminal never + prompts and still stops before typing. `OPENADAPT_SECOND_FACTOR_PROMPT=off` + turns the prompt off. - Effect locations (`openadapt.effect-location/v1`, `openadapt_flow/effect_location/`): the place a careful person would look again to see an intended value, stored as pack data. Each record holds the diff --git a/packages/flow/docs/SECOND_FACTOR.md b/packages/flow/docs/SECOND_FACTOR.md index 78702ce6ce..32f120a1da 100644 --- a/packages/flow/docs/SECOND_FACTOR.md +++ b/packages/flow/docs/SECOND_FACTOR.md @@ -115,6 +115,7 @@ first match wins. | --- | --- | | `OPENADAPT_SECOND_FACTOR_URL` with `OPENADAPT_RUNNER_TOKEN` | The control plane of a hosted or customer-run runner. A named person answers on the dashboard | | `OPENADAPT_SECOND_FACTOR_COMMAND` | A local command, run with no shell as ` code ` or ` approval `. Exit 0 prints the code (or confirms the approval), and exit 3 means the person declined. A password manager's one-time-code command works here | +| The run's terminal | Used when no variable above is set and the run's stdin and stderr are both a terminal. The person types the code (not echoed; empty declines), or presses Enter after approving (`n` declines). `OPENADAPT_SECOND_FACTOR_PROMPT=off` turns it off. A service, hosted sandbox or MCP server has no terminal and never prompts. On a POSIX terminal echo is turned off for the read; on Windows the console is read one key at a time with `msvcrt.getwch`, which never echoes. Either way the read runs under the step's deadline without a background thread, input typed before the prompt and input left when the read ends are discarded, and normal input comes back however the read ends | `OPENADAPT_SECOND_FACTOR_TIMEOUT_S` sets how long a step waits, from 10 to 600 seconds. The default is 120. While it waits, the runtime prints a line to @@ -173,6 +174,15 @@ page still showing and halts there. refusal, the handoff's bind, re-check, type-once and read-back rules with a field that counts every delivery, replay, recording, and the run token's scope. +- `tests/test_second_factor_console.py`: the same line reader over the + Windows console's key-at-a-time interface, with a fake keyboard and clock + on every platform (the deadline, keys typed before the prompt or left after + it, Ctrl-C, function keys, backspace, an over-long answer), plus a test + against the real `msvcrt` that runs only on Windows. +- `tests/test_second_factor_terminal.py`: a real pty. A code is read without + echo and echo comes back on; after a timeout the next prompt gets its + answer; input typed before a prompt doesn't answer it; a run without a + terminal never prompts. - `tests/test_second_factor_browser.py`: headless Chromium. Two different codes of the same length render the same pixels; a later document masks its code field; focus taken during the wait, a prefilled field and an ordinary diff --git a/packages/flow/openadapt_flow/second_factor.py b/packages/flow/openadapt_flow/second_factor.py index feae9c2b23..fe7b37a678 100644 --- a/packages/flow/openadapt_flow/second_factor.py +++ b/packages/flow/openadapt_flow/second_factor.py @@ -24,6 +24,11 @@ manager's one-time-code command). It is run as `` code|approval `` with no shell. Exit 0 prints the code (or confirms the approval), exit 3 means the person declined. +- The run's own terminal, when it has one (stdin and stderr are both a TTY + and ``OPENADAPT_SECOND_FACTOR_PROMPT`` is not ``off``): the person types + the code, which is not echoed, or presses Enter after approving + (:mod:`openadapt_flow.second_factor_terminal`). A run with no terminal (a + service, a hosted sandbox, an MCP server, CI) never prompts. With no source, or when the source fails, times out, answers after the deadline or declines, the step stops before anything is typed, with one closed @@ -50,6 +55,7 @@ "ONE_TIME_CODE_MARKER", "ONE_TIME_CODE_PARAM", "REFUSAL_CODES", + "PROMPT_ENV", "SOURCE_ENV_KEYS", "TIMEOUT_ENV", "URL_ENV", @@ -74,9 +80,12 @@ TOKEN_ENV = "OPENADAPT_RUNNER_TOKEN" COMMAND_ENV = "OPENADAPT_SECOND_FACTOR_COMMAND" TIMEOUT_ENV = "OPENADAPT_SECOND_FACTOR_TIMEOUT_S" +#: ``off`` (or ``0``, ``false``) stops an interactive run from asking at its +#: terminal. +PROMPT_ENV = "OPENADAPT_SECOND_FACTOR_PROMPT" #: Every variable a source reads. :func:`source_env` forwards only the ones #: the selected source uses. -SOURCE_ENV_KEYS = (URL_ENV, TOKEN_ENV, COMMAND_ENV, TIMEOUT_ENV) +SOURCE_ENV_KEYS = (URL_ENV, TOKEN_ENV, COMMAND_ENV, TIMEOUT_ENV, PROMPT_ENV) def source_env(environ: Optional[Mapping[str, str]] = None) -> dict[str, str]: @@ -87,7 +96,7 @@ def source_env(environ: Optional[Mapping[str, str]] = None) -> dict[str, str]: """ environ = os.environ if environ is None else environ - keys = [TIMEOUT_ENV] + keys = [TIMEOUT_ENV, PROMPT_ENV] if (environ.get(URL_ENV) or "").strip(): keys += [URL_ENV, TOKEN_ENV] elif (environ.get(COMMAND_ENV) or "").strip(): @@ -254,6 +263,10 @@ def source_from_env(env: Optional[Mapping[str, str]] = None) -> Optional[Source] command = (env.get(COMMAND_ENV) or "").strip() if command: return CommandSource(command) + from openadapt_flow.second_factor_terminal import PROMPT_OFF, TerminalSource + + if (env.get(PROMPT_ENV) or "").strip().lower() not in PROMPT_OFF: + return TerminalSource.open() return None @@ -282,7 +295,7 @@ def obtain( raise SecondFactorRefused( "second_factor_unavailable", "this sign-in asks for a second factor and no source is set " - f"({URL_ENV} or {COMMAND_ENV}); nothing was typed", + f"({URL_ENV} or {COMMAND_ENV}, or a terminal); nothing was typed", ) beat = heartbeat or _stderr_heartbeat() started = clock() diff --git a/packages/flow/openadapt_flow/second_factor_terminal.py b/packages/flow/openadapt_flow/second_factor_terminal.py new file mode 100644 index 0000000000..bbbb80ae16 --- /dev/null +++ b/packages/flow/openadapt_flow/second_factor_terminal.py @@ -0,0 +1,352 @@ +"""Ask for a sign-in's second factor at the run's own terminal. + +:class:`TerminalSource` is the last source :func:`openadapt_flow.second_factor.source_from_env` +tries: only when no control plane and no command is set, stdin and stderr are +both a terminal, and ``OPENADAPT_SECOND_FACTOR_PROMPT`` is not ``off``. A +service, a hosted sandbox, an MCP server or CI has no terminal and never +prompts. + +One line reader (:func:`read_line`) serves every platform, over a small +:class:`Console` interface: + +- :class:`PosixConsole` (``termios``): echo is turned off for a code, and + ``select`` waits on the terminal's descriptor. +- :class:`WindowsConsole` (``msvcrt``): ``getwch`` reads one key at a time + without echo, and ``kbhit`` is polled in short slices. + +Either way the read runs in the calling thread under the step's deadline, so +nothing keeps reading after the step gives up. Anything typed before the +prompt is discarded, so an earlier keystroke can't answer it. When the read +ends, whatever ends it (an answer, the deadline, an over-long answer, Ctrl-C +or a failed read), input it did not take is discarded and the terminal's +normal input mode is restored in ``finally``, so the shell never reads part +of a code. +""" + +from __future__ import annotations + +import os +import sys +import time +from collections.abc import Callable +from typing import Any, Optional, Protocol + +from openadapt_flow.second_factor import Request, SecondFactorRefused + +__all__ = [ + "PROMPT_OFF", + "Console", + "PosixConsole", + "TerminalSource", + "WindowsConsole", + "read_line", +] + +#: Values of ``OPENADAPT_SECOND_FACTOR_PROMPT`` that turn the prompt off. +PROMPT_OFF = ("off", "0", "false") +#: The longest answer read from the terminal; a code is far shorter. +_MAX_LINE = 256 +#: How often the Windows console is polled for a key. +_POLL_S = 0.05 + + +class Console(Protocol): + """The terminal primitives :func:`read_line` needs.""" + + #: Whether typed characters are shown by the terminal itself. + echoes: bool + #: Whether ``\x00`` or ``\xe0`` starts a two-character function or + #: arrow key (the Windows console); elsewhere they are ordinary input. + prefixed_keys: bool + + def begin(self, *, hidden: bool) -> None: + """Enter reading mode (no echo when ``hidden``); drop pending input.""" + + def wait(self, timeout_s: float) -> bool: + """Whether a character is ready within ``timeout_s``.""" + + def read(self) -> str: + """Characters that are ready; ``""`` at end of input.""" + + def end(self) -> None: + """Drop input not taken and restore normal input. Never raises.""" + + +def read_line( + console: Console, + out: Any, + prompt: str, + *, + hidden: bool, + deadline: float, + timeout_s: float, + clock: Callable[[], float] = time.monotonic, +) -> str: + """One line from ``console`` before ``deadline``, or a refusal.""" + + try: + try: + console.begin(hidden=hidden) + except Exception: # noqa: BLE001 - an unusable terminal is unavailable + raise SecondFactorRefused( + "second_factor_unavailable", "the terminal can't be read" + ) from None + _write(out, prompt) + line: list[str] = [] + skip = False + while True: + remaining = deadline - clock() + if remaining <= 0: + raise SecondFactorRefused( + "second_factor_timeout", + f"no second factor within {timeout_s:g} s; nothing was typed", + ) + if not console.wait(remaining): + continue + chunk = console.read() + if not chunk: + raise SecondFactorRefused( + "second_factor_unavailable", + "the terminal closed; nothing was typed", + ) + for char in chunk: + if skip: # the second half of a Windows function or arrow key + skip = False + continue + if console.prefixed_keys and char in ("\x00", "\xe0"): + skip = True + continue + if char == "\x03": + raise KeyboardInterrupt + if char in ("\r", "\n"): + return "".join(line) + if char in ("\b", "\x7f"): + if line: + line.pop() + if not hidden and not console.echoes: + _write(out, "\b \b") + continue + line.append(char) + if not hidden and not console.echoes: + _write(out, char) # an approval reply is shown, a code never + if len(line) > _MAX_LINE: + raise SecondFactorRefused( + "second_factor_invalid", "the answer is too long" + ) + except OSError: + raise SecondFactorRefused( + "second_factor_unavailable", "the terminal can't be read" + ) from None + finally: + console.end() + _write(out, "\n") + + +def _write(out: Any, text: str) -> None: + try: + out.write(text) + out.flush() + except (OSError, ValueError, AttributeError): + pass + + +class PosixConsole: + """A POSIX terminal on file descriptor ``fd`` (``termios``).""" + + echoes = True + prefixed_keys = False + + def __init__(self, fd: int) -> None: + import codecs + + self._fd = fd + self._saved: Optional[list[Any]] = None + # A multi-byte character split across two reads still decodes. + self._decoder = codecs.getincrementaldecoder("utf-8")("replace") + + def begin(self, *, hidden: bool) -> None: + import termios + + self._saved = termios.tcgetattr(self._fd) + quiet = list(self._saved) + if hidden: + quiet[3] = quiet[3] & ~termios.ECHO + termios.tcsetattr(self._fd, termios.TCSANOW, quiet) + # Input only: waiting for output to drain could block on a terminal + # nobody reads. + termios.tcflush(self._fd, termios.TCIFLUSH) + + def wait(self, timeout_s: float) -> bool: + import select + + ready, _, _ = select.select([self._fd], [], [], timeout_s) + return bool(ready) + + def read(self) -> str: + while True: + raw = os.read(self._fd, _MAX_LINE) + if not raw: + return "" + text = self._decoder.decode(raw) + if text: # empty: half a character; its rest is in the same line + return text + + def end(self) -> None: + try: + import termios + except ImportError: + return + try: + termios.tcflush(self._fd, termios.TCIFLUSH) + except (termios.error, OSError): + pass + if self._saved is not None: + try: + termios.tcsetattr(self._fd, termios.TCSANOW, self._saved) + except (termios.error, OSError): + pass + self._saved = None + + +class WindowsConsole: + """The Windows console (``msvcrt``). ``getwch`` reads without echo. + + ``msvcrt`` changes no console mode, so there is no mode to restore; + ending a read drops the keys it did not take. ``kbhit``, ``getwch`` and + ``sleep`` are injectable, so the logic is tested on every platform. + """ + + echoes = False + prefixed_keys = True + #: How long ending a read keeps dropping keys (a long paste included). + drain_s = 0.5 + + def __init__( + self, + *, + kbhit: Optional[Callable[[], bool]] = None, + getwch: Optional[Callable[[], str]] = None, + sleep: Callable[[float], None] = time.sleep, + clock: Callable[[], float] = time.monotonic, + ) -> None: + if kbhit is None or getwch is None: + import msvcrt # type: ignore[import-not-found,unused-ignore] + + kbhit = kbhit or msvcrt.kbhit # type: ignore[attr-defined,unused-ignore] + getwch = getwch or msvcrt.getwch # type: ignore[attr-defined,unused-ignore] + self._kbhit = kbhit + self._getwch = getwch + self._sleep = sleep + self._clock = clock + + def _drain(self) -> None: + # Bounded by time, not by a count, so a long paste is dropped whole + # and a key held down can't hang the run. + until = self._clock() + self.drain_s + while self._kbhit() and self._clock() < until: + self._getwch() + + def begin(self, *, hidden: bool) -> None: + self._drain() + + def wait(self, timeout_s: float) -> bool: + # Measured on the clock: a sleep that oversleeps can't stretch the + # deadline. + until = self._clock() + timeout_s + while True: + if self._kbhit(): + return True + left = until - self._clock() + if left <= 0: + return False + self._sleep(min(_POLL_S, left)) + + def read(self) -> str: + return self._getwch() + + def end(self) -> None: + try: + self._drain() + except Exception: # noqa: BLE001 - ending never raises + pass + + +class TerminalSource: + """Ask the person at the run's own terminal (no echo for a code). + + ``fd_in`` is a POSIX terminal descriptor; pass ``console`` instead for + another :class:`Console` (the Windows console, or a test double). + """ + + def __init__( + self, + fd_in: Optional[int], + out: Any, + *, + console: Optional[Console] = None, + clock: Callable[[], float] = time.monotonic, + ) -> None: + if console is None: + if fd_in is None: + raise ValueError("a terminal source needs a descriptor or a console") + console = PosixConsole(fd_in) + self._console = console + self._out = out + self._clock = clock + + @classmethod + def open(cls) -> Optional["TerminalSource"]: + """The run's terminal, or None when it has none.""" + + try: + if not (sys.stdin.isatty() and sys.stderr.isatty()): + return None + if sys.platform == "win32": + return cls(None, sys.stderr, console=WindowsConsole()) + import termios # noqa: F401 - POSIX terminals + + return cls(sys.stdin.fileno(), sys.stderr) + except (AttributeError, ValueError, OSError, ImportError): + return None + + def obtain( + self, request: Request, *, heartbeat: Callable[[], None] + ) -> Optional[str]: + deadline = self._clock() + request.timeout_s + if request.kind == "approval": + reply = self._ask( + "Approve the sign-in on your device, then press Enter " + "(type n and Enter to decline): ", + hidden=False, + deadline=deadline, + timeout_s=request.timeout_s, + ) + if reply.strip().lower() in ("n", "no"): + raise SecondFactorRefused( + "second_factor_declined", "the person declined; nothing was typed" + ) + return None + reply = self._ask( + "Sign-in code (not shown; leave empty to decline): ", + hidden=True, + deadline=deadline, + timeout_s=request.timeout_s, + ) + if not reply.strip(): + raise SecondFactorRefused( + "second_factor_declined", "the person declined; nothing was typed" + ) + return reply + + def _ask( + self, prompt: str, *, hidden: bool, deadline: float, timeout_s: float + ) -> str: + return read_line( + self._console, + self._out, + prompt, + hidden=hidden, + deadline=deadline, + timeout_s=timeout_s, + clock=self._clock, + ) diff --git a/packages/flow/tests/test_second_factor_console.py b/packages/flow/tests/test_second_factor_console.py new file mode 100644 index 0000000000..5c735c85b6 --- /dev/null +++ b/packages/flow/tests/test_second_factor_console.py @@ -0,0 +1,181 @@ +"""The terminal prompt's line reader, on every platform. + +:class:`WindowsConsole` takes injected ``kbhit``, ``getwch`` and ``sleep``, +so its deadline, discard and key handling run here on a fake keyboard with a +fake clock: no console, no person and no real waiting. The last test runs +only on Windows, against the real ``msvcrt``. +""" + +from __future__ import annotations + +import io +import sys +from typing import Optional + +import pytest + +from openadapt_flow import second_factor as sf +from openadapt_flow.second_factor_terminal import ( + TerminalSource, + WindowsConsole, + read_line, +) + +CODE = "482913" + + +class Keyboard: + """Keys that arrive at given times on a fake clock.""" + + def __init__(self, keys: list[tuple[float, str]] = ()) -> None: # type: ignore[assignment] + self.now = 0.0 + self.keys = sorted(keys, key=lambda k: k[0]) + self.taken: list[str] = [] + + def clock(self) -> float: + return self.now + + def sleep(self, seconds: float) -> None: + self.now += seconds + + def kbhit(self) -> bool: + return bool(self.keys) and self.keys[0][0] <= self.now + + def getwch(self) -> str: + assert self.kbhit(), "getwch would block" + key = self.keys.pop(0)[1] + self.taken.append(key) + return key + + def type(self, at: float, text: str) -> None: + self.keys = sorted([*self.keys, *((at, c) for c in text)], key=lambda k: k[0]) + + def console(self) -> WindowsConsole: + return WindowsConsole( + kbhit=self.kbhit, getwch=self.getwch, sleep=self.sleep, clock=self.clock + ) + + +def _ask(kb: Keyboard, kind: str = "code", timeout_s: float = 30.0) -> Optional[str]: + source = TerminalSource(None, io.StringIO(), console=kb.console(), clock=kb.clock) + return source.obtain(sf.Request(kind, "s", timeout_s), heartbeat=lambda: None) + + +def test_a_code_is_read_key_by_key_and_never_shown() -> None: + kb = Keyboard() + kb.type(1.0, "482 913\r") + out = io.StringIO() + source = TerminalSource(None, out, console=kb.console(), clock=kb.clock) + reply = source.obtain(sf.Request("code", "s", 30.0), heartbeat=lambda: None) + assert reply == "482 913" and sf.normalize_code(reply) == CODE + assert CODE[:3] not in out.getvalue() and "not shown" in out.getvalue() + + +def test_keys_typed_before_the_prompt_are_discarded() -> None: + kb = Keyboard([(0.0, c) for c in "111111\r"]) + kb.type(2.0, f"{CODE}\r") + assert _ask(kb) == CODE + + +def test_the_deadline_holds_and_left_over_keys_are_discarded() -> None: + kb = Keyboard() + kb.type(1.0, "4829") # part of a code, then nothing + kb.type(40.0, "13\r") # after the deadline + with pytest.raises(sf.SecondFactorRefused) as refused: + _ask(kb, timeout_s=30.0) + assert refused.value.code == "second_factor_timeout" + assert 30.0 <= kb.now < 31.0 # gave up at the deadline, not later + kb.now = 41.0 + # What arrived late is still queued for nobody: the next read drops it + # before its prompt, so it can't answer or reach the shell. + kb.type(42.0, f"{CODE}\r") + assert _ask(kb) == CODE + + +def test_a_sleep_that_oversleeps_does_not_stretch_the_deadline() -> None: + kb = Keyboard() + kb.sleep = lambda seconds: setattr(kb, "now", kb.now + 3 * seconds + 0.015) # type: ignore[method-assign] + with pytest.raises(sf.SecondFactorRefused) as refused: + _ask(kb, timeout_s=30.0) + assert refused.value.code == "second_factor_timeout" + assert kb.now < 30.5 + + +def test_a_long_paste_is_dropped_whole() -> None: + kb = Keyboard() + kb.type(1.0, "9" * 5000) + with pytest.raises(sf.SecondFactorRefused) as refused: + _ask(kb) + assert refused.value.code == "second_factor_invalid" + assert not kb.kbhit() # nothing of the paste is left for the shell + + +def test_ctrl_c_interrupts_and_still_discards_what_was_typed() -> None: + kb = Keyboard() + kb.type(1.0, "48\x03") + kb.type(1.0, "2913\r") + with pytest.raises(KeyboardInterrupt): + _ask(kb) + assert not kb.kbhit() # the rest was dropped, not left for the shell + + +def test_function_keys_backspace_and_an_over_long_answer() -> None: + kb = Keyboard() + kb.type(1.0, "\xe0H48\x00;27\b913\r") # arrow, F1, a corrected digit + assert _ask(kb) == CODE + kb = Keyboard() + kb.type(1.0, "9" * 300 + "\r") + with pytest.raises(sf.SecondFactorRefused) as refused: + _ask(kb) + assert refused.value.code == "second_factor_invalid" + assert not kb.kbhit() + + +def test_an_approval_reply_is_shown_and_can_decline() -> None: + kb = Keyboard() + kb.type(1.0, "n\r") + out = io.StringIO() + source = TerminalSource(None, out, console=kb.console(), clock=kb.clock) + with pytest.raises(sf.SecondFactorRefused) as refused: + source.obtain(sf.Request("approval", "s", 30.0), heartbeat=lambda: None) + assert refused.value.code == "second_factor_declined" + assert out.getvalue().rstrip("\n").endswith("n") + + +def test_a_failing_console_is_unavailable() -> None: + class Broken(WindowsConsole): + def begin(self, *, hidden: bool) -> None: + raise OSError("no console") + + kb = Keyboard() + console = Broken(kbhit=kb.kbhit, getwch=kb.getwch, sleep=kb.sleep) + with pytest.raises(sf.SecondFactorRefused) as refused: + read_line( + console, + io.StringIO(), + "? ", + hidden=True, + deadline=10.0, + timeout_s=10.0, + clock=kb.clock, + ) + assert refused.value.code == "second_factor_unavailable" + + +@pytest.mark.skipif(sys.platform != "win32", reason="needs the Windows console") +def test_the_real_windows_console_times_out_without_a_key() -> None: + import time + + console = WindowsConsole() # the real msvcrt.kbhit and getwch + started = time.monotonic() + with pytest.raises(sf.SecondFactorRefused) as refused: + read_line( + console, + io.StringIO(), + "? ", + hidden=True, + deadline=time.monotonic() + 0.5, + timeout_s=0.5, + ) + assert refused.value.code == "second_factor_timeout" + assert time.monotonic() - started < 5.0 diff --git a/packages/flow/tests/test_second_factor_terminal.py b/packages/flow/tests/test_second_factor_terminal.py new file mode 100644 index 0000000000..d99d14f5df --- /dev/null +++ b/packages/flow/tests/test_second_factor_terminal.py @@ -0,0 +1,208 @@ +"""Asking for a second factor at the run's own terminal, on a real pty. + +Each test opens a pseudo-terminal: the source reads the follower side, and +the test plays the person by writing to the leader side once the prompt has +been written. Nothing here needs a real terminal or a person. +""" + +from __future__ import annotations + +import io +import os +import sys +import threading +import time +from typing import Any, Iterator, Optional + +import pytest + +from openadapt_flow import second_factor as sf + +termios = pytest.importorskip("termios") +pty = pytest.importorskip("pty") + +CODE = "482913" +#: Generous: the person answers as soon as the prompt shows, so a slow +#: machine only makes a test slower, never wrong. +WAIT_S = 10.0 + + +@pytest.fixture(autouse=True) +def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + for key in sf.SOURCE_ENV_KEYS: + monkeypatch.delenv(key, raising=False) + + +@pytest.fixture +def terminal() -> Iterator[tuple[int, int]]: + leader, follower = pty.openpty() + yield leader, follower + os.close(leader) + os.close(follower) + + +class _Screen(io.StringIO): + """The prompt side of the terminal; counts prompts as they are written.""" + + def __init__(self) -> None: + super().__init__() + self.prompts = threading.Semaphore(0) + + def write(self, text: str) -> int: + written = super().write(text) + if text.endswith(": "): + self.prompts.release() + return written + + +def _source(follower: int) -> tuple[Any, _Screen]: + from openadapt_flow.second_factor_terminal import TerminalSource + + screen = _Screen() + return TerminalSource(follower, screen), screen + + +def _person( + leader: int, + screen: _Screen, + text: str, + *, + sample: Optional[list[bool]] = None, + follower: int = -1, +) -> threading.Thread: + """Answer the next prompt once it shows, sampling echo first if asked.""" + + def answer() -> None: + if not screen.prompts.acquire(timeout=WAIT_S): + return + if sample is not None: + sample.append(_echo_on(follower)) + os.write(leader, text.encode()) + + thread = threading.Thread(target=answer, daemon=True) + thread.start() + return thread + + +def _echo_on(follower: int) -> bool: + return bool(termios.tcgetattr(follower)[3] & termios.ECHO) + + +def _ask(source: Any, kind: str = "code", timeout_s: float = WAIT_S) -> Optional[str]: + return source.obtain(sf.Request(kind, "s", timeout_s), heartbeat=lambda: None) + + +def test_a_code_is_read_without_echo_and_echo_comes_back( + terminal: tuple[int, int], +) -> None: + leader, follower = terminal + assert _echo_on(follower) + source, screen = _source(follower) + seen: list[bool] = [] + _person(leader, screen, "482 913\n", sample=seen, follower=follower) + code = sf.obtain("code", "step_004", source=source, heartbeat=lambda: None) + assert code is not None and code.consume() == CODE + assert seen == [False] # echo was off while the person typed + assert _echo_on(follower) # and on again afterwards + assert "not shown" in screen.getvalue() and CODE not in screen.getvalue() + + +def test_a_timeout_restores_echo_and_the_next_prompt_gets_its_answer( + terminal: tuple[int, int], +) -> None: + leader, follower = terminal + source, screen = _source(follower) + threads = threading.active_count() + started = time.monotonic() + with pytest.raises(sf.SecondFactorRefused) as refused: + _ask(source, timeout_s=0.3) + assert refused.value.code == "second_factor_timeout" + assert time.monotonic() - started < WAIT_S + # No reader is left behind holding the terminal with echo off. + assert _echo_on(follower) + assert threading.active_count() == threads + screen.prompts.acquire(timeout=0) # the prompt that timed out + _person(leader, screen, f"{CODE}\n") + assert _ask(source) == CODE + assert _echo_on(follower) + + +def test_input_typed_before_the_prompt_does_not_answer_it( + terminal: tuple[int, int], +) -> None: + leader, follower = terminal + os.write(leader, b"111111\n") # typed earlier, at some other moment + source, screen = _source(follower) + _person(leader, screen, f"{CODE}\n") + assert _ask(source) == CODE + + +def test_input_left_after_a_timeout_never_reaches_the_shell( + terminal: tuple[int, int], +) -> None: + leader, follower = terminal + source, screen = _source(follower) + _person(leader, screen, "4829") # part of a code, no Enter + with pytest.raises(sf.SecondFactorRefused) as refused: + _ask(source, timeout_s=1.0) + assert refused.value.code == "second_factor_timeout" + import select + + # Nothing is left for the next reader (the shell, after the run exits). + assert select.select([follower], [], [], 0.2)[0] == [] + + +def test_non_ascii_input_is_kept_on_a_posix_terminal( + terminal: tuple[int, int], +) -> None: + """A character such as U+00E0 is ordinary input here, not a key prefix.""" + + leader, follower = terminal + source, screen = _source(follower) + _person(leader, screen, "\u00e0n\n") + # Read whole: the code check (in obtain) refuses it later, but the + # terminal neither swallows it nor skips the next character. + assert _ask(source) == "\u00e0n" + + +def test_an_empty_code_declines_and_an_approval_can_be_confirmed_or_declined( + terminal: tuple[int, int], +) -> None: + leader, follower = terminal + source, screen = _source(follower) + _person(leader, screen, "\n") + with pytest.raises(sf.SecondFactorRefused) as refused: + _ask(source) + assert refused.value.code == "second_factor_declined" + _person(leader, screen, "\n") + assert _ask(source, "approval") is None + _person(leader, screen, "n\n") + with pytest.raises(sf.SecondFactorRefused) as refused: + _ask(source, "approval") + assert refused.value.code == "second_factor_declined" + assert _echo_on(follower) + + +def test_a_run_without_a_terminal_never_prompts( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from openadapt_flow.second_factor_terminal import TerminalSource + + class NotTty: + def isatty(self) -> bool: + return False + + monkeypatch.setattr(sys, "stdin", NotTty()) + assert TerminalSource.open() is None + assert sf.source_from_env({}) is None + monkeypatch.setattr(TerminalSource, "open", classmethod(lambda cls: cls(0, None))) + assert isinstance(sf.source_from_env({}), TerminalSource) + for off in ("off", "0", "false", "OFF"): + assert sf.source_from_env({sf.PROMPT_ENV: off}) is None + # A command or a control plane wins over the terminal. + assert isinstance(sf.source_from_env({sf.COMMAND_ENV: "otp"}), sf.CommandSource) + + +def test_the_prompt_setting_reaches_a_cached_runs_child() -> None: + env = sf.source_env({sf.PROMPT_ENV: "off", sf.TOKEN_ENV: "t"}) + assert env == {sf.PROMPT_ENV: "off"}