From a6364a5f0967105a342206e3dfea059d55bf6eb3 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 18:51:36 -0500 Subject: [PATCH 01/12] feat(flow): wait for a person at a sign-in's second factor A step marked one_time (code or approval) asks the configured source when it runs: the runner's control plane (the code sealed in the person's browser to a one-step P-256 key) or a local command. The code is typed once and kept nowhere. No source, no answer in time, a decline or a malformed answer stops the step before typing with a closed second_factor_* code. The wrap recorder turns an autocomplete=one-time-code field into such a step. --- CAPABILITIES.md | 1 + llms-full.txt | 1 + packages/flow/CHANGELOG.md | 12 + packages/flow/docs/SECOND_FACTOR.md | 115 ++++ packages/flow/docs/WRAP_PUBLISH.md | 5 + .../backends/_field_metadata_js.py | 3 + .../backends/playwright_backend.py | 18 +- .../openadapt_flow/compile_agent/agents.py | 15 + .../flow/openadapt_flow/compiler/compile.py | 25 +- .../integrations/agents/skills.py | 10 +- packages/flow/openadapt_flow/ir.py | 36 ++ packages/flow/openadapt_flow/recorder.py | 44 ++ .../flow/openadapt_flow/runtime/replayer.py | 12 +- .../openadapt_flow/runtime/secret_frames.py | 10 +- packages/flow/openadapt_flow/second_factor.py | 520 ++++++++++++++++++ packages/flow/openadapt_flow/teach_scope.py | 6 +- packages/flow/tests/e2e/_sign_in_app.py | 98 +++- .../tests/e2e/test_wrap_second_factor_e2e.py | 253 +++++++++ packages/flow/tests/test_second_factor.py | 462 ++++++++++++++++ 19 files changed, 1622 insertions(+), 24 deletions(-) create mode 100644 packages/flow/docs/SECOND_FACTOR.md create mode 100644 packages/flow/openadapt_flow/second_factor.py create mode 100644 packages/flow/tests/e2e/test_wrap_second_factor_e2e.py create mode 100644 packages/flow/tests/test_second_factor.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 646eeef048..77be853760 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -319,6 +319,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`. 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 (draft), 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` | | 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 | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | 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 step marked `one_time` (`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; the code is typed once and never stored, logged or put in a report, and frames are blacked out. No source, no answer in time, a decline or a malformed answer stops the step before typing with a closed `second_factor_*` code. 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 | 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; unit tests for both sources, the sealing format and every refusal). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, [SECOND_FACTOR.md](packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.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 | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `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 4328f3f979..e88d652a70 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -753,6 +753,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`. 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 (draft), 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` | | 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 | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | 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 step marked `one_time` (`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; the code is typed once and never stored, logged or put in a report, and frames are blacked out. No source, no answer in time, a decline or a malformed answer stops the step before typing with a closed `second_factor_*` code. 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 | 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; unit tests for both sources, the sealing format and every refusal). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, [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/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 | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `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 7338bb09bf..cfd99b70af 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -19,6 +19,18 @@ ### Features +- A sign-in that asks for a second factor (a code by text message or email, + an authenticator code, or a push approval) no longer has to stop the + program. A step can carry `one_time` (`code` or `approval`). When it runs, + the run waits for a person through the configured source + (`OPENADAPT_SECOND_FACTOR_URL` for a hosted or customer-run runner's control + plane, or a local `OPENADAPT_SECOND_FACTOR_COMMAND`), types the code once + and keeps it nowhere. No source, no answer within the timeout, a decline or + a malformed answer stops the step before typing, with a closed + `second_factor_*` code. Over the control plane the code is sealed in the + person's browser to a one-step P-256 key. The wrap recorder turns a field + marked `autocomplete="one-time-code"` into such a step, and a code-only + form's submit counts as a sign-in, not a save. See docs/SECOND_FACTOR.md. - Dropdowns, searchable selects, type-aheads and native selects are recorded, compiled and run as one model, a choice (`OptionChoice` on a `SELECT_OPTION` step, docs/CHOICES.md). A click on an option of a list the diff --git a/packages/flow/docs/SECOND_FACTOR.md b/packages/flow/docs/SECOND_FACTOR.md new file mode 100644 index 0000000000..bda01f7867 --- /dev/null +++ b/packages/flow/docs/SECOND_FACTOR.md @@ -0,0 +1,115 @@ +# Sign-ins that ask for a second factor + +Some apps ask for a second factor after the password: a code sent by text +message or email, a code from an authenticator app, or a push approval on a +phone. A program can't hold that code, because it changes on every sign-in. +Instead the run waits at that step, a person supplies the code or approves the +sign-in, and the run continues. If no one answers in time, the run stops +before it types anything into the code field. + +The code is used once. It is never written to the program, the recording, the +run report, the receipt or a log. + +## In the program + +A step can carry `one_time` (`openadapt_flow.ir.Step.one_time`): + +| Value | Step | What the run does | +| --- | --- | --- | +| `code` | A secret `TYPE` step whose param is `one_time_code` and that has no text | Asks the configured source for one code when the step runs, types it, and drops it | +| `approval` | A `WAIT` step with no input | Asks a person to approve the sign-in on their own device, and continues when they say they did. The next step still checks the screen | + +`one_time_code` is not a task input, a call parameter or a secret parameter. +No API call, params file or vault set supplies it, and the hosted parameter +schema doesn't list it. Steps without `one_time` serialize exactly as before. + +Replay saves black frames for a program with a one-time step, as it does for +a program with secret parameters. The checks still use the original pixels in +memory. + +A runtime older than this field ignores it, finds no +`OPENADAPT_FLOW_SECRET_ONE_TIME_CODE`, and stops at the code step before +typing. An older runtime given an `approval` step waits only for the page to +settle, then halts at the next step if the sign-in didn't finish. + +## Recording it + +During `openadapt wrap`'s first run the recorder checks each field the agent +types into, using only the page's markup. A field whose `autocomplete` names +`one-time-code` is a code field. The agent never has the code. It is told to +type `⟦one-time-code⟧` there. The recorder discards that text, gets a code +from the configured source and types it instead. The recording keeps +`one_time: "code"` and the param name, and blacks out the field in every +frame that shows it. + +A declared task input typed into a code field is refused, and so is +`⟦one-time-code⟧` typed into any other field. Nothing is typed in either case. + +The submit button of a form that holds only a code (or a username, password +and code together) signs in. It isn't classified as a save. + +The recorder doesn't detect push approvals yet. An `approval` step has to be +added to the program by hand. + +## Where the code comes from + +The runtime reads the source from the environment when the step runs. The +first match wins. + +| Variable | Source | +| --- | --- | +| `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 | + +`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 +stderr every 20 seconds, so a supervisor that ends silent runs doesn't end +one that is waiting for a person. + +A cached `openadapt wrap` run passes these three variables to the program's +MCP server. + +### The control-plane protocol + +1. The runtime makes a P-256 key pair for this one step and keeps the private + half in memory. +2. It sends `POST ` with the run token and + `{"schema": "openadapt.second-factor-request/v1", "kind", "step_id", + "public_key", "timeout_s"}`. The public key is an uncompressed point in + base64url. The answer is `201 {"request_id"}`. +3. It polls `GET /` every 2 seconds. The answer is + `{"state"}`, one of `pending`, `answered`, `approved`, `declined`, + `expired` or `consumed`. An `answered` state also carries + `"sealed": {"epk", "iv", "ciphertext"}`. +4. The person's browser seals the code: ECDH between a fresh browser key and + the runtime's public key, HKDF-SHA256 with the info + `openadapt.second-factor/v1:`, then AES-256-GCM with the request + id as associated data. The control plane stores only that ciphertext, + which it can't open, and deletes it on the first read. + +A network error or a 5xx answer is retried until the deadline. Any other +non-200 answer stops the step. + +## Why a step stops + +Every stop happens before anything is typed into the code field. The step's +result is a governed refusal, and its error starts with one of these codes: + +| Code | Meaning | +| --- | --- | +| `second_factor_unavailable` | No source is set, the source isn't reachable, or the control plane refused the request | +| `second_factor_timeout` | No one answered within the timeout | +| `second_factor_declined` | The person declined | +| `second_factor_invalid` | The answer wasn't 4 to 16 letters or digits (spaces and hyphens are dropped), couldn't be opened, or answered a different kind of request | + +A wrong code that the app rejects isn't retried. The next step finds the code +page still showing and halts there. + +## Tests + +- `tests/test_second_factor.py`: both sources, every refusal, the sealing + format, the step shape, replay with and without a source, and recording. +- `tests/e2e/test_wrap_second_factor_e2e.py`: headless Chromium and a + synthetic notes app with an authenticator page, 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 in every file. diff --git a/packages/flow/docs/WRAP_PUBLISH.md b/packages/flow/docs/WRAP_PUBLISH.md index 7b2f5624fb..887f19e461 100644 --- a/packages/flow/docs/WRAP_PUBLISH.md +++ b/packages/flow/docs/WRAP_PUBLISH.md @@ -246,6 +246,11 @@ input only as a placeholder. Without it, the first run's instruction carries the values to your model provider. Cached and hosted runs make no model calls. +A sign-in that then asks for a one-time code (a field marked +`autocomplete="one-time-code"`) or a push approval is not a task input. The +run asks a person for it when the step runs; see +[SECOND_FACTOR.md](SECOND_FACTOR.md). + `publish` lists the secret parameters under `secret_parameters` in the upload and leaves them out of the call's inputs. The endpoint is callable only after an owner or admin attaches a vault set that holds a key named exactly like diff --git a/packages/flow/openadapt_flow/backends/_field_metadata_js.py b/packages/flow/openadapt_flow/backends/_field_metadata_js.py index 7b02cc6254..ff59c1802d 100644 --- a/packages/flow/openadapt_flow/backends/_field_metadata_js.py +++ b/packages/flow/openadapt_flow/backends/_field_metadata_js.py @@ -34,6 +34,9 @@ (i.getAttribute('autocomplete') || '').toLowerCase().split(/\s+/); const secret = (i) => kind(i) === 'password' || tokens(i).some((t) => t === 'current-password' || t === 'new-password'); + // A sign-in's second factor (SMS, email or authenticator code), named + // the standard way. Its value comes from a person at run time. + if (tokens(el).includes('one-time-code')) return 'one-time-code'; if (secret(el)) { return tokens(el).includes('new-password') ? 'new-password' : 'password'; } diff --git a/packages/flow/openadapt_flow/backends/playwright_backend.py b/packages/flow/openadapt_flow/backends/playwright_backend.py index b14de886ee..dc4154a755 100644 --- a/packages/flow/openadapt_flow/backends/playwright_backend.py +++ b/packages/flow/openadapt_flow/backends/playwright_backend.py @@ -3268,7 +3268,7 @@ def focused_field_credential(self) -> Optional[dict[str, Any]]: RECORD-TIME seam (:class:`openadapt_flow.backend.CredentialFieldBackend`). Returns ``{"kind": "password" | "new-password" | "username" | - "unknown", "box": (x, y, w, h)}`` + "one-time-code" | "unknown", "box": (x, y, w, h)}`` or None. The rules use only the page's own markup, the way a browser's password manager finds a sign-in form: @@ -3279,7 +3279,9 @@ def focused_field_credential(self) -> Optional[dict[str, Any]]: or the uniquely paired text, email or phone input across all password candidates in the composed form (the document when it has no form). Ambiguous controls return ``unknown``; CSS visibility is - not used as evidence that a password candidate is irrelevant. + not used as evidence that a password candidate is irrelevant; + * ``one-time-code``: an input whose ``autocomplete`` names + ``one-time-code`` (a sign-in's second factor). ``box`` is in top-document viewport pixels, or None when the element's box could not be read. Read-only and never raises. None @@ -3293,7 +3295,7 @@ def focused_field_credential(self) -> Optional[dict[str, Any]]: kind = self._focused_element_call(_FIELD_CREDENTIAL_JS, box_out=box) if kind == "none": return None - if kind not in ("password", "new-password", "username"): + if kind not in ("password", "new-password", "username", "one-time-code"): # The focused control could not be read (a frame chain that does # not verify, a failed call). The recorder refuses to type a # declared input into it. @@ -3323,7 +3325,15 @@ def credential_field_at(self, x: int, y: int) -> Optional[str]: return "unknown" return ( found - if found in ("password", "new-password", "username", "frame", "unknown") + if found + in ( + "password", + "new-password", + "username", + "one-time-code", + "frame", + "unknown", + ) else None ) diff --git a/packages/flow/openadapt_flow/compile_agent/agents.py b/packages/flow/openadapt_flow/compile_agent/agents.py index e55e1fc16f..96421f76b6 100644 --- a/packages/flow/openadapt_flow/compile_agent/agents.py +++ b/packages/flow/openadapt_flow/compile_agent/agents.py @@ -41,8 +41,17 @@ from openadapt_flow.jit.adapters import UnsupportedAction from openadapt_flow.jit.compile_agent import TaskRequest from openadapt_flow.privacy import PLACEHOLDER_HELP +from openadapt_flow.second_factor import ONE_TIME_CODE_MARKER from openadapt_flow.teach_scope import ScopeViolation +#: A sign-in that asks for a one-time code: the agent never has the code. +SECOND_FACTOR_HELP = ( + "If a sign-in asks for a one-time code (sent by text message or email, " + "or shown by an authenticator app), click the code field and type " + + ONE_TIME_CODE_MARKER + + "; OpenAdapt gets the code from a person and types it." +) + __all__ = [ "AgentLedger", "CODE_DEFAULT_MODEL", @@ -272,6 +281,8 @@ def drive(self, request: TaskRequest, harness: Harness) -> AgentLedger: task is done, or cannot be done, call finish with a one-line summary.""" + " " + PLACEHOLDER_HELP + + " " + + SECOND_FACTOR_HELP ) _EVERY_TURN_SYSTEM = ( @@ -284,6 +295,8 @@ def drive(self, request: TaskRequest, harness: Harness) -> AgentLedger: finish with a one-line summary.""" + " " + PLACEHOLDER_HELP + + " " + + SECOND_FACTOR_HELP ) _CODE_SYSTEM = ( @@ -303,6 +316,8 @@ def drive(self, request: TaskRequest, harness: Harness) -> AgentLedger: done, call finish with a one-line summary.""" + " " + PLACEHOLDER_HELP + + " " + + SECOND_FACTOR_HELP ) _FINISH_TOOL = { diff --git a/packages/flow/openadapt_flow/compiler/compile.py b/packages/flow/openadapt_flow/compiler/compile.py index 43d46d42cf..1a5cde7bfe 100644 --- a/packages/flow/openadapt_flow/compiler/compile.py +++ b/packages/flow/openadapt_flow/compiler/compile.py @@ -3442,7 +3442,15 @@ def cached_lines(i: int, suffix: str, png: bytes) -> list[OcrLine]: int(raw_rect[3]), ), ) - if secret: + one_time: Optional[Literal["code"]] = ( + "code" if secret and event.get("one_time") == "code" else None + ) + if one_time: + # A sign-in's one-time code: a person supplies it when the + # step runs (openadapt_flow.second_factor). + text = None + intent = "type the one-time sign-in code" + elif secret: # A secret's literal value is never in the recording, so it # is never in the bundle either: the step carries only the # param name, and the value is injected from the environment @@ -3462,6 +3470,7 @@ def cached_lines(i: int, suffix: str, png: bytes) -> list[OcrLine]: text=text, param=param, secret=secret, + one_time=one_time, field_label=field_label, ), before_png, @@ -4676,7 +4685,8 @@ def _form_submit_steps( A sign-in is not a save: when the fields typed since the previous such click are exactly a username and a current password the recorder withheld (``credential_kinds``, from each secret TYPE event's ``credential``), its - submit button signs in and writes no record. A lone password (a PIN or a + submit button signs in and writes no record. So does a form holding only + a one-time sign-in code, or the three together. A lone password (a PIN or a re-authentication), a ``new-password`` field (a password change or sign-up) or any other typed field keeps the escalation, and the keyword risk inference still classifies the button on its own label. @@ -4698,13 +4708,22 @@ def _form_submit_steps( and step.action in (ActionKind.CLICK, ActionKind.DOUBLE_CLICK) and _is_form_save(raw) ): - if sorted(map(str, typed_kinds)) != ["password", "username"]: + if sorted(map(str, typed_kinds)) not in _SIGN_IN_FIELD_SETS: found.append(step) typed = False typed_kinds = [] return found +#: Typed fields whose form submit signs in and saves nothing: a username and +#: current password, a one-time code (a second sign-in page), or all three. +_SIGN_IN_FIELD_SETS = ( + ["password", "username"], + ["one-time-code"], + ["one-time-code", "password", "username"], +) + + def _is_form_save(raw: object) -> bool: """The observation shows the labelled submit button of the typed form.""" diff --git a/packages/flow/openadapt_flow/integrations/agents/skills.py b/packages/flow/openadapt_flow/integrations/agents/skills.py index 00cc1799cb..74ce503cb9 100644 --- a/packages/flow/openadapt_flow/integrations/agents/skills.py +++ b/packages/flow/openadapt_flow/integrations/agents/skills.py @@ -1088,9 +1088,15 @@ async def _call_skill(python: str, server: Path, params: dict[str, Any]) -> dict """Call the compiled task's one tool over MCP (stdio), as a client would.""" from mcp import ClientSession, StdioServerParameters - from mcp.client.stdio import stdio_client + from mcp.client.stdio import get_default_environment, stdio_client - target = StdioServerParameters(command=python, args=[str(server)]) + from openadapt_flow.second_factor import SOURCE_ENV_KEYS + + # The stdio client passes only a minimal environment. A sign-in's second + # factor source is operator configuration the cached run needs too. + env = get_default_environment() + env.update({k: os.environ[k] for k in SOURCE_ENV_KEYS if os.environ.get(k)}) + target = StdioServerParameters(command=python, args=[str(server)], env=env) async with stdio_client(target) as (read, write): async with ClientSession(read, write) as session: await session.initialize() diff --git a/packages/flow/openadapt_flow/ir.py b/packages/flow/openadapt_flow/ir.py index cf0c251147..a1f6c06e62 100644 --- a/packages/flow/openadapt_flow/ir.py +++ b/packages/flow/openadapt_flow/ir.py @@ -2363,6 +2363,19 @@ class Step(BaseModel): " compiler.annotate.FieldLabelAnnotator)." ), ) + one_time: Optional[Literal["code", "approval"]] = Field( + default=None, + description=( + "A sign-in's second factor (see openadapt_flow.second_factor)." + " ``code``: a secret TYPE step into a one-time-code field; the" + " value comes from a person through the configured source when" + " the step runs, is typed once and is never stored. Its param is" + " not a workflow input or a secret parameter. ``approval``: a WAIT" + " step at a push-approval prompt; the run waits until a person" + " says they approved it on their device. Absent on every other" + " step, so older bundles keep their bytes." + ), + ) native_selection: Optional[NativeSelectContract] = None choice: Optional[OptionChoice] = Field( default=None, @@ -2574,12 +2587,35 @@ def _serialize_compatible(self, handler: Any) -> dict[str, Any]: data: dict[str, Any] = handler(self) if self.target_param is None: data.pop("target_param", None) + if self.one_time is None: + data.pop("one_time", None) if self.native_selection is None: data.pop("native_selection", None) if self.choice is None: data.pop("choice", None) return data + @model_validator(mode="after") + def _validate_one_time(self) -> "Step": + if self.one_time == "code" and not ( + self.action is ActionKind.TYPE + and self.secret + and self.param + and self.text is None + ): + raise ValueError( + "a one-time code step is a secret TYPE step that names its " + "param and carries no text" + ) + if self.one_time == "approval" and ( + self.action is not ActionKind.WAIT + or self.secret + or self.param is not None + or self.text is not None + ): + raise ValueError("a one-time approval step is a WAIT with no input") + return self + @model_validator(mode="after") def _validate_target_param(self) -> "Step": if self.target_param is None: diff --git a/packages/flow/openadapt_flow/recorder.py b/packages/flow/openadapt_flow/recorder.py index fcc91f4fbc..de8b290648 100644 --- a/packages/flow/openadapt_flow/recorder.py +++ b/packages/flow/openadapt_flow/recorder.py @@ -74,6 +74,7 @@ StructuralLocator, ) from openadapt_flow.native_selection_capture import demonstrated_native_choice +from openadapt_flow.second_factor import ONE_TIME_CODE_MARKER, ONE_TIME_CODE_PARAM #: Bound on waiting for a newly opened page's first navigation. _NEW_PAGE_LOAD_TIMEOUT_S = 10.0 @@ -406,6 +407,14 @@ def type_text(self, text: str, param: Optional[str] = None) -> None: field_label = self._focused_field_label() if field_label: event["field_label"] = field_label + if credential is not None and credential[0] == "one-time-code": + self._type_one_time_code(event, text, credential[1]) + return + if text == ONE_TIME_CODE_MARKER: + raise CredentialFieldError( + "the one-time code marker was typed into a field that does not " + "ask for a one-time code; nothing was typed" + ) if credential is not None and credential[0] == "unknown": if text in (self._credential_inputs or {}): raise CredentialFieldError( @@ -451,6 +460,40 @@ def type_text(self, text: str, param: Optional[str] = None) -> None: self.last_type_withheld = credential is not None self._record(event, lambda: self._backend.type_text(text)) + def _type_one_time_code( + self, event: dict[str, Any], text: str, region: tuple[int, int, int, int] + ) -> None: + """Type a code a person supplies into the focused one-time-code field. + + The agent's text is discarded (it never has the code), unless it is a + declared input, which is refused: a code field takes only a code. The + event names :data:`ONE_TIME_CODE_PARAM` and holds no value. + """ + from openadapt_flow import second_factor + + if text in (self._credential_inputs or {}): + raise CredentialFieldError( + "a one-time code field takes only a code from a person, not a " + "declared input; nothing was typed" + ) + try: + code = second_factor.obtain("code", "recording") or "" + except second_factor.SecondFactorRefused as refused: + raise CredentialFieldError( + f"a one-time code field needs a code from a person ({refused})" + ) from None + event.pop("text", None) + event.update( + param=ONE_TIME_CODE_PARAM, + secret=True, + one_time="code", + credential="one-time-code", + redacted_region=list(region), + ) + self._credential_fields.append((self._active_surface, "one-time-code", region)) + self.last_type_withheld = True + self._record(event, lambda: self._backend.type_text(code)) + def press(self, key: str) -> None: """Press a key or chord (e.g. ``'Enter'``), recording the event.""" self._record({"kind": "key", "key": key}, lambda: self._backend.press(key)) @@ -1405,6 +1448,7 @@ def _focused_credential( "password", "new-password", "username", + "one-time-code", ): # A seam that answered but could not say: fail closed. return "unknown", _WHOLE_FRAME diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 3a838b63e7..05578a4e21 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -70,6 +70,7 @@ from urllib.parse import urlsplit from openadapt_flow import sealed_set as _sealed +from openadapt_flow import second_factor as _second_factor from openadapt_flow.assurance import effect_read_wording as _effect_read_wording from openadapt_flow.backend import ( ActionDeliveryUncertain, @@ -14084,7 +14085,13 @@ def _act_without_dialog( return None if step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION): - if step.secret: + if step.secret and step.one_time == "code": + # A sign-in's one-time code: asked for now, typed once, kept + # nowhere (openadapt_flow.second_factor). + text, refusal = _second_factor.runtime_value(step, result) + if refusal is not None: + return refusal + elif step.secret: # Secret value is never in the bundle/params: inject it from # the environment, failing fast with an actionable message. env_var = getattr(self, "secret_env_overrides", {}).get( @@ -14532,6 +14539,9 @@ def _act_without_dialog( return None if step.action is ActionKind.WAIT: + if step.one_time == "approval": + # A push approval: a person approves on their own device. + return _second_factor.runtime_value(step, result)[1] # WAIT means wait_settled only; the post-action settle handles it. return None diff --git a/packages/flow/openadapt_flow/runtime/secret_frames.py b/packages/flow/openadapt_flow/runtime/secret_frames.py index 3de75243c9..1b583f940d 100644 --- a/packages/flow/openadapt_flow/runtime/secret_frames.py +++ b/packages/flow/openadapt_flow/runtime/secret_frames.py @@ -10,13 +10,19 @@ def persisted_run_frame(png: bytes, *, workflow: Workflow | None) -> bytes: - """Return a same-size black PNG when this run handles secret parameters. + """Return a same-size black PNG when this run handles secret parameters + or a one-time sign-in code. The caller retains the original pixels for in-memory verification. This control does not depend on OCR or stable page layout. """ - if workflow is None or not workflow.secret_params: + if workflow is None: return png + if not workflow.secret_params: + from openadapt_flow.second_factor import has_one_time_steps + + if not has_one_time_steps(workflow): + return png from PIL import Image with Image.open(io.BytesIO(png)) as frame: diff --git a/packages/flow/openadapt_flow/second_factor.py b/packages/flow/openadapt_flow/second_factor.py new file mode 100644 index 0000000000..a247ab69ce --- /dev/null +++ b/packages/flow/openadapt_flow/second_factor.py @@ -0,0 +1,520 @@ +"""Ask a person for a sign-in's second factor while the run waits. + +A program step can declare ``Step.one_time``: + +- ``"code"``: a TYPE step into a one-time-code field (a code sent by SMS or + email, or shown by an authenticator app). The program never holds a value. + When the step runs, the configured source supplies one code; the runtime + types it and drops it. It is never stored, logged or written to a report. +- ``"approval"``: a WAIT step at a push-approval prompt. The source tells a + person to approve the sign-in on their own device, and the run continues + once they say they did. The next step still checks the screen. + +Sources, from the environment, first match wins: + +- ``OPENADAPT_SECOND_FACTOR_URL`` with ``OPENADAPT_RUNNER_TOKEN``: the control + plane of a hosted or customer-run runner. The runtime makes a one-run P-256 + key and sends only its public half. The person's browser seals the code to + that key, so the control plane stores ciphertext it cannot read and deletes + it on the first read. +- ``OPENADAPT_SECOND_FACTOR_COMMAND``: a local command (for example a password + 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. + +With no source, or when the source fails, times out or declines, the step +stops before anything is typed, with one closed code from +:data:`REFUSAL_CODES`. +""" + +from __future__ import annotations + +import base64 +import os +import re +import shlex +import subprocess +import sys +import time +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from typing import Any, Literal, Optional, Protocol +from urllib.parse import urlsplit + +__all__ = [ + "COMMAND_ENV", + "DEFAULT_TIMEOUT_S", + "ONE_TIME_CODE_MARKER", + "ONE_TIME_CODE_PARAM", + "REFUSAL_CODES", + "SOURCE_ENV_KEYS", + "TIMEOUT_ENV", + "URL_ENV", + "CommandSource", + "HttpSource", + "SecondFactorRefused", + "has_one_time_steps", + "normalize_code", + "obtain", + "open_sealed_code", + "runtime_value", + "source_from_env", + "timeout_from_env", +] + +Kind = Literal["code", "approval"] + +URL_ENV = "OPENADAPT_SECOND_FACTOR_URL" +TOKEN_ENV = "OPENADAPT_RUNNER_TOKEN" +COMMAND_ENV = "OPENADAPT_SECOND_FACTOR_COMMAND" +TIMEOUT_ENV = "OPENADAPT_SECOND_FACTOR_TIMEOUT_S" +#: The operator configuration a run's child processes need for a source. +SOURCE_ENV_KEYS = (URL_ENV, COMMAND_ENV, TIMEOUT_ENV) + +#: How long a step waits for a person by default, and the bounds an +#: operator may set with :data:`TIMEOUT_ENV`. +DEFAULT_TIMEOUT_S = 120.0 +MIN_TIMEOUT_S = 10.0 +MAX_TIMEOUT_S = 600.0 +#: Exit status a command source uses when the person declined. +DECLINED_EXIT_CODE = 3 +#: Seconds between progress lines on stderr while waiting (a supervisor that +#: ends a silent run must not end one that is waiting for a person). +HEARTBEAT_S = 20.0 + +REFUSAL_CODES = ( + "second_factor_unavailable", + "second_factor_timeout", + "second_factor_declined", + "second_factor_invalid", +) + +#: The param a one-time code step names. It is not a task input or a secret +#: parameter, so no call and no vault supplies it. +ONE_TIME_CODE_PARAM = "one_time_code" +#: What a capture agent types into a one-time-code field; the recorder +#: discards it and types the code a person supplies. +ONE_TIME_CODE_MARKER = "\u27e6one-time-code\u27e7" + +REQUEST_SCHEMA = "openadapt.second-factor-request/v1" +SEAL_INFO = b"openadapt.second-factor/v1:" + +# Codes people get are short runs of digits or letters; some are shown in +# groups ("123 456", "ABC-123"). Spaces and hyphens are dropped. +_CODE = re.compile(r"[A-Za-z0-9]{4,16}\Z") +_STEP_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}\Z") +_REQUEST_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]{7,63}\Z") +_LOCAL_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"}) + + +class SecondFactorRefused(RuntimeError): + """The step cannot get its second factor; nothing was typed. + + ``code`` is one of :data:`REFUSAL_CODES`. The message never carries a + code value or a source's output. + """ + + def __init__(self, code: str, detail: str) -> None: + if code not in REFUSAL_CODES: + raise ValueError(f"unknown second-factor refusal {code!r}") + self.code = code + super().__init__(f"{code}: {detail}") + + +@dataclass(frozen=True) +class Request: + kind: Kind + step_id: str + timeout_s: float + + +class Source(Protocol): + """Where a step's second factor comes from.""" + + def obtain( + self, request: Request, *, heartbeat: Callable[[], None] + ) -> Optional[str]: + """The code for ``code`` requests, None once an approval is confirmed. + + Raises :class:`SecondFactorRefused` otherwise. + """ + ... + + +def normalize_code(raw: object) -> str: + """One code with group separators removed, or a refusal.""" + + if not isinstance(raw, str): + raise SecondFactorRefused("second_factor_invalid", "the code is not text") + code = re.sub(r"[\s-]", "", raw) + if not _CODE.fullmatch(code): + raise SecondFactorRefused( + "second_factor_invalid", + "the code must be 4 to 16 letters or digits", + ) + return code + + +def timeout_from_env(env: Optional[Mapping[str, str]] = None) -> float: + env = os.environ if env is None else env + raw = (env.get(TIMEOUT_ENV) or "").strip() + if not raw: + return DEFAULT_TIMEOUT_S + try: + value = float(raw) + except ValueError: + raise SecondFactorRefused( + "second_factor_unavailable", f"{TIMEOUT_ENV} is not a number" + ) from None + if not MIN_TIMEOUT_S <= value <= MAX_TIMEOUT_S: + raise SecondFactorRefused( + "second_factor_unavailable", + f"{TIMEOUT_ENV} must be between {MIN_TIMEOUT_S:g} and " + f"{MAX_TIMEOUT_S:g} seconds", + ) + return value + + +def source_from_env(env: Optional[Mapping[str, str]] = None) -> Optional[Source]: + """The configured source, or None when none is configured.""" + + env = os.environ if env is None else env + url = (env.get(URL_ENV) or "").strip() + if url: + return HttpSource(url, (env.get(TOKEN_ENV) or "").strip()) + command = (env.get(COMMAND_ENV) or "").strip() + if command: + return CommandSource(command) + return None + + +def obtain( + kind: Kind, + step_id: str, + *, + source: Optional[Source] = None, + env: Optional[Mapping[str, str]] = None, + heartbeat: Optional[Callable[[], None]] = None, +) -> Optional[str]: + """Get one second factor for ``step_id``. See the module docstring.""" + + if kind not in ("code", "approval"): + raise ValueError(f"unknown second-factor kind {kind!r}") + if not _STEP_ID.fullmatch(step_id or ""): + raise SecondFactorRefused("second_factor_unavailable", "invalid step id") + timeout_s = timeout_from_env(env) + chosen = source if source is not None else source_from_env(env) + if chosen is None: + 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", + ) + beat = heartbeat or _stderr_heartbeat() + value = chosen.obtain(Request(kind, step_id, timeout_s), heartbeat=beat) + if kind == "approval": + return None + return normalize_code(value) + + +def has_one_time_steps(workflow: Any) -> bool: + """Whether any step of ``workflow`` (linear or program graph) is one-time.""" + + steps = list(getattr(workflow, "steps", None) or []) + graphs = [getattr(workflow, "program", None)] + graphs.extend((getattr(workflow, "subflows", None) or {}).values()) + for graph in graphs: + for state in (getattr(graph, "states", None) or {}).values(): + if getattr(state, "step", None) is not None: + steps.append(state.step) + return any(getattr(step, "one_time", None) for step in steps) + + +def _stderr_heartbeat() -> Callable[[], None]: + last = [time.monotonic()] + + def beat() -> None: + now = time.monotonic() + if now - last[0] >= HEARTBEAT_S: + last[0] = now + print( + "openadapt-flow: waiting for a person (second factor)", + file=sys.stderr, + flush=True, + ) + + return beat + + +# -- command source ---------------------------------------------------------- + + +class CommandSource: + """Run a local command for each request (no shell).""" + + def __init__(self, command: str) -> None: + try: + self._argv = shlex.split(command) + except ValueError: + self._argv = [] + if not self._argv: + raise SecondFactorRefused( + "second_factor_unavailable", f"{COMMAND_ENV} is not a command" + ) + + def obtain( + self, request: Request, *, heartbeat: Callable[[], None] + ) -> Optional[str]: + heartbeat() + try: + done = subprocess.run( + [*self._argv, request.kind, request.step_id], + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + timeout=request.timeout_s, + check=False, + ) + except subprocess.TimeoutExpired: + raise SecondFactorRefused( + "second_factor_timeout", + f"no second factor within {request.timeout_s:g} s; nothing was typed", + ) from None + except OSError: + raise SecondFactorRefused( + "second_factor_unavailable", "the second-factor command could not start" + ) from None + if done.returncode == DECLINED_EXIT_CODE: + raise SecondFactorRefused( + "second_factor_declined", "the person declined; nothing was typed" + ) + if done.returncode != 0: + raise SecondFactorRefused( + "second_factor_unavailable", + f"the second-factor command exited {done.returncode}", + ) + if request.kind == "approval": + return None + try: + return done.stdout.decode("utf-8").strip() + except UnicodeDecodeError: + raise SecondFactorRefused( + "second_factor_invalid", "the code is not text" + ) from None + + +# -- control-plane source ------------------------------------------------------ + + +def _b64url(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +def _unb64url(text: object, *, size: Optional[int] = None) -> bytes: + if not isinstance(text, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,4096}", text): + raise ValueError("not base64url") + raw = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)) + if size is not None and len(raw) != size: + raise ValueError("wrong length") + return raw + + +def _sealing_key(private_key: Any, epk: bytes, request_id: str) -> bytes: + from cryptography.hazmat.primitives import hashes + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.hazmat.primitives.kdf.hkdf import HKDF + + peer = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), epk) + shared = private_key.exchange(ec.ECDH(), peer) + return HKDF( + algorithm=hashes.SHA256(), + length=32, + salt=None, + info=SEAL_INFO + request_id.encode("ascii"), + ).derive(shared) + + +def open_sealed_code(private_key: Any, request_id: str, sealed: object) -> str: + """Decrypt a code the person's browser sealed to this run's key. + + ``sealed`` is ``{"epk", "iv", "ciphertext"}``: the browser's ephemeral + P-256 public key (uncompressed point), a 12-byte nonce and the AES-256-GCM + ciphertext, each base64url. The request id is the associated data. + """ + + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + try: + if not isinstance(sealed, dict) or set(sealed) != {"epk", "iv", "ciphertext"}: + raise ValueError("shape") + epk = _unb64url(sealed["epk"], size=65) + iv = _unb64url(sealed["iv"], size=12) + ciphertext = _unb64url(sealed["ciphertext"]) + key = _sealing_key(private_key, epk, request_id) + plain = AESGCM(key).decrypt(iv, ciphertext, request_id.encode("ascii")) + return plain.decode("utf-8") + except Exception: + raise SecondFactorRefused( + "second_factor_invalid", "the sealed code could not be opened" + ) from None + + +class HttpSource: + """Ask the run's control plane; a person answers on the dashboard.""" + + poll_interval_s = 2.0 + + def __init__( + self, + url: str, + token: str, + *, + client: Any = None, + clock: Callable[[], float] = time.monotonic, + sleep: Callable[[float], None] = time.sleep, + ) -> None: + parts = urlsplit(url) + local = parts.scheme == "http" and (parts.hostname or "") in _LOCAL_HOSTS + if ( + url != url.strip() + or not (parts.scheme == "https" or local) + or not parts.hostname + or parts.username is not None + or parts.password is not None + or parts.query + or parts.fragment + ): + raise SecondFactorRefused( + "second_factor_unavailable", f"{URL_ENV} must be an HTTPS URL" + ) + if not token: + raise SecondFactorRefused( + "second_factor_unavailable", f"{TOKEN_ENV} is not set" + ) + self._url = url.rstrip("/") + self._token = token + self._client = client + self._clock = clock + self._sleep = sleep + + def _http(self) -> Any: + if self._client is None: + import httpx + + self._client = httpx.Client(timeout=15.0, follow_redirects=False) + return self._client + + def _headers(self) -> dict[str, str]: + return { + "authorization": f"Bearer {self._token}", + "content-type": "application/json", + "cache-control": "no-store", + } + + def obtain( + self, request: Request, *, heartbeat: Callable[[], None] + ) -> Optional[str]: + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import ec + + private_key = ec.generate_private_key(ec.SECP256R1()) + public = private_key.public_key().public_bytes( + serialization.Encoding.X962, + serialization.PublicFormat.UncompressedPoint, + ) + deadline = self._clock() + request.timeout_s + request_id = self._create(request, _b64url(public)) + while True: + heartbeat() + state, sealed = self._poll(request_id) + if state == "answered": + if request.kind != "code": + raise SecondFactorRefused( + "second_factor_invalid", "a code answered an approval request" + ) + return open_sealed_code(private_key, request_id, sealed) + if state == "approved": + if request.kind != "approval": + raise SecondFactorRefused( + "second_factor_invalid", "an approval answered a code request" + ) + return None + if state == "declined": + raise SecondFactorRefused( + "second_factor_declined", "the person declined; nothing was typed" + ) + if state in ("expired", "consumed") or self._clock() >= deadline: + raise SecondFactorRefused( + "second_factor_timeout", + f"no second factor within {request.timeout_s:g} s; " + "nothing was typed", + ) + self._sleep(self.poll_interval_s) + + def _create(self, request: Request, public_key: str) -> str: + body = { + "schema": REQUEST_SCHEMA, + "kind": request.kind, + "step_id": request.step_id, + "public_key": public_key, + "timeout_s": int(request.timeout_s), + } + try: + response = self._http().post(self._url, json=body, headers=self._headers()) + data = response.json() if response.status_code == 201 else None + except Exception: + data = None + request_id = data.get("request_id") if isinstance(data, dict) else None + if not isinstance(request_id, str) or not _REQUEST_ID.fullmatch(request_id): + raise SecondFactorRefused( + "second_factor_unavailable", + "the control plane did not open a second-factor request", + ) + return request_id + + def _poll(self, request_id: str) -> tuple[str, object]: + try: + response = self._http().get( + f"{self._url}/{request_id}", headers=self._headers() + ) + except Exception: + return "pending", None # transient; the deadline still applies + if response.status_code >= 500: + return "pending", None + if response.status_code != 200: + raise SecondFactorRefused( + "second_factor_unavailable", + f"the control plane refused the second-factor request " + f"({response.status_code})", + ) + try: + data = response.json() + except Exception: + return "pending", None + state = data.get("state") if isinstance(data, dict) else None + if state not in ( + "pending", + "answered", + "approved", + "declined", + "expired", + "consumed", + ): + return "pending", None + return str(state), data.get("sealed") + + +def runtime_value(step: Any, result: Any = None) -> tuple[str, Optional[str]]: + """The replayer's hook: ``(code, None)``, or ``("", refusal message)``. + + An approval returns ``("", None)`` once confirmed. A refusal marks the + step result a governed refusal; its message starts with the closed code. + """ + + try: + value = obtain(step.one_time, step.id) + except SecondFactorRefused as refused: + if result is not None: + result.failure_category = "governed_refusal" + return "", f"Step '{step.id}' ({step.intent}) {refused}" + return value or "", None diff --git a/packages/flow/openadapt_flow/teach_scope.py b/packages/flow/openadapt_flow/teach_scope.py index a4d5d4e172..ab0447af72 100644 --- a/packages/flow/openadapt_flow/teach_scope.py +++ b/packages/flow/openadapt_flow/teach_scope.py @@ -54,6 +54,7 @@ from openadapt_flow.jit.adapters import Op, UnsupportedAction from openadapt_flow.runtime.identity import normalize_structured +from openadapt_flow.second_factor import ONE_TIME_CODE_MARKER __all__ = [ "TEACH_SCOPE_SCHEMA", @@ -1013,7 +1014,10 @@ def check_ops( "the clicked control is one the authorization forbids", ) if op.kind == "type": - if (op.text or "") not in typeable: + # The one-time-code marker types only a code a person supplies, + # and only into a one-time-code field (the recorder refuses it + # anywhere else). + if (op.text or "") not in typeable and op.text != ONE_TIME_CODE_MARKER: self._raise( "typed_value_not_declared", "the agent typed text the task did not declare; only " diff --git a/packages/flow/tests/e2e/_sign_in_app.py b/packages/flow/tests/e2e/_sign_in_app.py index 6cc0b97475..c673f0e406 100644 --- a/packages/flow/tests/e2e/_sign_in_app.py +++ b/packages/flow/tests/e2e/_sign_in_app.py @@ -1,17 +1,25 @@ """A synthetic notes app behind a sign-in form, for the wrap sign-in tests. ``GET /`` shows the sign-in form until the browser holds a session cookie; -after a correct username and password it shows a notes form. ``GET +after a correct username and password it shows a notes form. With a +``totp_secret`` the password leads to a second page that asks for a +six-digit authenticator code (RFC 6238, one step either side accepted) +in a field marked ``autocomplete="one-time-code"``. ``GET /api/notes`` is an unauthenticated read of the saved notes, which the program's read-back uses. Made-up data only; it listens on 127.0.0.1. """ from __future__ import annotations +import base64 +import hashlib +import hmac import html import json import secrets +import struct import threading +import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Callable from urllib.parse import parse_qs @@ -32,10 +40,35 @@ {msg}
    {items}
""" +CODE_PAGE = """Notes sign in code + +

Notes

{msg}
Two-step sign in + + +
Sign in: enter the code from your authenticator app
Sign in: enter the code from your authenticator app
""" + + +def totp(secret_b32: str, at: float | None = None, step: int = 30) -> str: + """RFC 6238 six-digit code (HMAC-SHA1).""" + + key = base64.b32decode(secret_b32.upper() + "=" * (-len(secret_b32) % 8)) + counter = int((time.time() if at is None else at) // step) + digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest() + offset = digest[-1] & 0x0F + value = struct.unpack(">I", digest[offset : offset + 4])[0] & 0x7FFFFFFF + return f"{value % 1_000_000:06d}" + + class SignInApp: - def __init__(self, username: str, password: str) -> None: + def __init__( + self, username: str, password: str, totp_secret: str | None = None + ) -> None: self.username = username self.password = password + self.totp_secret = totp_secret + self.pending: set[str] = set() + self.codes_accepted = 0 + self.codes_rejected = 0 self.records: list[dict[str, object]] = [] self.sessions: set[str] = set() self.sign_ins = 0 @@ -65,13 +98,28 @@ def _send(self, status: int, body: str, **headers: str) -> None: self.end_headers() self.wfile.write(data) - def _signed_in(self) -> bool: + def _cookie(self, wanted: str) -> str: cookie = self.headers.get("cookie") or "" for part in cookie.split(";"): name, _, value = part.strip().partition("=") - if name == "session" and value in app.sessions: - return True - return False + if name == wanted: + return value + return "" + + def _signed_in(self) -> bool: + return self._cookie("session") in app.sessions + + def _start_session(self) -> None: + token = secrets.token_hex(16) + with app._lock: + app.sessions.add(token) + app.sign_ins += 1 + self._send( + 303, + "", + location="/", + set_cookie=f"session={token}; Path=/; HttpOnly", + ) def _form(self) -> dict[str, str]: length = int(self.headers.get("content-length") or 0) @@ -93,6 +141,8 @@ def do_GET(self) -> None: # noqa: N802 ) elif self._signed_in(): self._notes() + elif self._cookie("pending") in app.pending: + self._send(200, CODE_PAGE.format(msg="")) else: self._send(200, SIGN_IN.format(msg="")) @@ -103,21 +153,45 @@ def do_POST(self) -> None: # noqa: N802 form.get("user") == app.username and form.get("pass") == app.password ): + if app.totp_secret is None: + self._start_session() + return token = secrets.token_hex(16) with app._lock: - app.sessions.add(token) - app.sign_ins += 1 + app.pending.add(token) self._send( 303, "", location="/", - set_cookie=f"session={token}; Path=/; HttpOnly", + set_cookie=f"pending={token}; Path=/; HttpOnly", ) else: self._send( 401, SIGN_IN.format(msg="

Wrong username or password.

"), ) + elif ( + self.path == "/verify" + and app.totp_secret is not None + and self._cookie("pending") in app.pending + ): + now = time.time() + code = form.get("code", "") + valid = any( + hmac.compare_digest(code, totp(app.totp_secret, now + d)) + for d in (-30, 0, 30) + ) + if valid: + with app._lock: + app.pending.discard(self._cookie("pending")) + app.codes_accepted += 1 + self._start_session() + else: + with app._lock: + app.codes_rejected += 1 + self._send( + 401, CODE_PAGE.format(msg="

That code is not valid.

") + ) elif self.path == "/save" and self._signed_in(): note = form.get("note", "")[:200] with app._lock: @@ -136,8 +210,10 @@ def do_POST(self) -> None: # noqa: N802 return Handler -def serve(username: str, password: str) -> tuple[str, SignInApp, Callable[[], None]]: - app = SignInApp(username, password) +def serve( + username: str, password: str, totp_secret: str | None = None +) -> tuple[str, SignInApp, Callable[[], None]]: + app = SignInApp(username, password, totp_secret) server = ThreadingHTTPServer(("127.0.0.1", 0), app.handler()) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() diff --git a/packages/flow/tests/e2e/test_wrap_second_factor_e2e.py b/packages/flow/tests/e2e/test_wrap_second_factor_e2e.py new file mode 100644 index 0000000000..930a9fd354 --- /dev/null +++ b/packages/flow/tests/e2e/test_wrap_second_factor_e2e.py @@ -0,0 +1,253 @@ +"""Wrap a task whose sign-in asks for an authenticator code, headless. + +The target is the synthetic notes app with a second sign-in page +(:mod:`tests.e2e._sign_in_app` with a TOTP secret). The scripted agent types +:data:`openadapt_flow.second_factor.ONE_TIME_CODE_MARKER` into the code +field; it never has a code. A local command source plays the person: it +computes the current code from the synthetic secret. It asserts: + +* the code field (``autocomplete="one-time-code"``) becomes a one-time step + found from the page alone: no task input, no secret parameter and no vault + key name it, and publish asks no caller for it; +* no file holds a code or the TOTP secret; +* the canary and a cached run get a fresh code from the source and read + their note back VERIFIED, and a declining source stops the next run at the + code page with ``second_factor_declined`` before anything is typed there. +""" + +from __future__ import annotations + +import json +import re +import stat +import sys +from pathlib import Path +from typing import Any, Iterator + +import pytest + +from openadapt_flow import second_factor as sf +from openadapt_flow.integrations.agents.recording import load_task +from openadapt_flow.integrations.agents.skills import FrameworkAgent +from openadapt_flow.ir import Workflow +from openadapt_flow.wrap import WrappedTask +from tests.e2e._sign_in_app import serve, totp +from tests.e2e.test_wrap_sign_in_e2e import ( + INSTRUCTION, + PASSWORD, + TEST_KEY, + USERNAME, + _admitter, + _authorize, + _inputs, + _leaks, + _ref, + _why, +) + +pytest.importorskip("playwright") + +#: A synthetic authenticator secret (base32), made up for this test. +TOTP_SECRET = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP" + + +@pytest.fixture +def app() -> Iterator[tuple[str, Any]]: + base, state, stop = serve(USERNAME, PASSWORD, TOTP_SECRET) + yield base, state + stop() + + +def _source(tmp_path: Path, *, declined: bool = False) -> str: + """A command source that computes the current code (the person).""" + + path = tmp_path / ("declining.py" if declined else "authenticator.py") + flow_root = Path(__file__).resolve().parents[2] + body = ( + "raise SystemExit(3)\n" + if declined + else ( + "import sys\n" + f"sys.path.insert(0, {str(flow_root)!r})\n" + "from tests.e2e._sign_in_app import totp\n" + f"print(totp({TOTP_SECRET!r}))\n" + ) + ) + path.write_text(body) + path.chmod(path.stat().st_mode | stat.S_IEXEC) + return f"{sys.executable} {path}" + + +def _agent(seen: list[str]) -> FrameworkAgent: + def run(task: str, tools: Any) -> dict[str, Any]: + seen.append(task) + told = _inputs(task) + listing = tools.observe() + listing = tools.type_text(told["username"], _ref(listing, "Username")) + listing = tools.type_text(told["password"], _ref(listing, "Password")) + listing = tools.click(_ref(listing, "Sign in")) + seen.append(listing) + listing = tools.type_text(sf.ONE_TIME_CODE_MARKER, _ref(listing, "Code")) + listing = tools.click(_ref(listing, "Verify")) + seen.append(listing) + listing = tools.type_text(told["note"], _ref(listing, "Note")) + listing = tools.click(_ref(listing, "Save")) + tools.finish("saved") + return { + "calls": [ + { + "input_tokens": 0, + "output_tokens": 0, + "total_tokens": 0, + "cache_creation_input_tokens": 0, + "cache_read_input_tokens": 0, + } + ] + } + + return FrameworkAgent(run, principal_id="agent:scripted-two-step", model="scripted") + + +def test_an_authenticator_code_comes_from_a_person_and_never_persists( + app: tuple[str, Any], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capfd: pytest.CaptureFixture[str], +) -> None: + base, state = app + monkeypatch.setenv(sf.COMMAND_ENV, _source(tmp_path)) + admitter, key_dir = _admitter(tmp_path, monkeypatch) + task_file = tmp_path / "task.json" + task_file.write_text( + json.dumps( + { + "schema": "openadapt.wrap-task/v1", + "instruction": INSTRUCTION, + "parameters": ["username", "password", "note"], + "url": base, + "verifier": { + "kind": "rest", + "base_url": base.rstrip("/"), + "records_path": "/api/notes", + "records_key": "records", + "records_complete": True, + }, + "expect": {"list": "demo"}, + "on_screen": ["Notes"], + "canary_params": [ + { + "username": USERNAME, + "password": PASSWORD, + "note": "two-step canary note", + } + ], + "cache_dir": str(tmp_path / "cache"), + } + ) + ) + setup = load_task( + task_file, + offer=lambda proposal: "ci:two-step-reviewer", + admitter=admitter, + key_dir=key_dir, + model_key=TEST_KEY, + ) + first_values = { + "username": USERNAME, + "password": PASSWORD, + "note": "first two-step note", + } + _authorize(setup.cache, setup.instruction, first_values, base, key_dir, monkeypatch) + seen: list[str] = [] + task = WrappedTask( + cache=setup.cache, + agent=_agent(seen), + instruction=setup.instruction, + parameters=setup.parameters, + runs_dir=tmp_path / "runs", + ) + first = task.call("first-run", first_values) + assert first["status"] == "admitted" and first["verified"] is True, _why(tmp_path) + # Run 1 and the canary each typed one fresh code. + assert state.codes_accepted >= 2 and state.codes_rejected == 0 + + program = setup.cache.admitted_program( + setup.instruction, dict.fromkeys(setup.parameters, "") + ) + assert program is not None + workflow = Workflow.load(Path(program["bundle"])) + (code_step,) = [s for s in workflow.steps if s.one_time] + assert code_step.one_time == "code" and code_step.param == sf.ONE_TIME_CODE_PARAM + assert code_step.secret and code_step.text is None + assert sorted(workflow.secret_params) == ["password", "username"] + assert sf.ONE_TIME_CODE_PARAM not in workflow.params + + from openadapt_flow.wrap.publish import stage + + staged = stage(setup.cache, setup.instruction, setup.parameters, key_dir=key_dir) + assert staged.manifest["parameters"] == ["note"] + assert staged.manifest["secret_parameters"] == ["password", "username"] + assert staged.manifest["input_schema"]["required"] == ["note"] + assert _leaks(staged.staged, [TOTP_SECRET]) == [] + + from importlib.metadata import version + + if int(version("mcp").split(".")[0]) < 2: + pytest.skip("the cached web run needs mcp 2 (sync tools run in a thread)") + accepted = state.codes_accepted + second = task.call( + "second-run", + {"username": USERNAME, "password": PASSWORD, "note": "second two-step note"}, + ) + assert second.get("path") == "skill", second + assert second["verified"] is True and second["model_calls"] == 0, json.dumps(second) + assert second["receipt_outcome"] == "VERIFIED", second + assert state.codes_accepted == accepted + 1 + + monkeypatch.setenv(sf.COMMAND_ENV, _source(tmp_path, declined=True)) + saved = len(state.records) + third = task.call( + "third-run", + {"username": USERNAME, "password": PASSWORD, "note": "never saved"}, + ) + assert third["verified"] is not True and third["status"] == "HALTED", third + latest = max( + (tmp_path / "cache").rglob("runs/*/report.json"), + key=lambda path: path.stat().st_mtime, + ) + halt = json.loads(latest.read_text())["halt"] + assert halt["reason"].startswith(f"Step '{code_step.id}'"), halt + assert "second_factor_declined" in halt["reason"], halt + assert len(state.records) == saved and state.codes_rejected == 0 + + # No file and no output holds the secret or any code accepted today. + out, err = capfd.readouterr() + assert TOTP_SECRET not in out + err + hits = [ + path + for path in _leaks(tmp_path, [TOTP_SECRET]) + if not path.endswith("authenticator.py") + ] + assert hits == [], hits + _assert_no_recent_code(tmp_path) + + +def _assert_no_recent_code(root: Path) -> None: + """No run file holds a code from the last few minutes, as a token.""" + + import time + + now = time.time() + codes = {totp(TOTP_SECRET, now - 30 * i) for i in range(0, 20)} + pattern = re.compile( + rb"(? None: + for key in ENV_KEYS: + monkeypatch.delenv(key, raising=False) + + +def _b64(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode() + + +def seal(public_key_b64: str, request_id: str, code: str) -> dict[str, str]: + """What the dashboard does in the person's browser (WebCrypto).""" + + raw = base64.urlsafe_b64decode(public_key_b64 + "=" * (-len(public_key_b64) % 4)) + peer = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), raw) + ephemeral = ec.generate_private_key(ec.SECP256R1()) + shared = ephemeral.exchange(ec.ECDH(), peer) + key = HKDF( + algorithm=hashes.SHA256(), + length=32, + salt=None, + info=sf.SEAL_INFO + request_id.encode(), + ).derive(shared) + iv = os.urandom(12) + ciphertext = AESGCM(key).encrypt(iv, code.encode(), request_id.encode()) + epk = ephemeral.public_key().public_bytes( + serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint + ) + return {"epk": _b64(epk), "iv": _b64(iv), "ciphertext": _b64(ciphertext)} + + +class _Response: + def __init__(self, status_code: int, body: Any = None) -> None: + self.status_code = status_code + self._body = body + + def json(self) -> Any: + if self._body is None: + raise ValueError("no body") + return self._body + + +class FakeControlPlane: + """The Cloud second-factor routes, in memory. ``answers`` are the poll + states in order; ``"code"`` becomes an answered state with a sealed code. + """ + + request_id = "sfr-0123456789abcdef" + + def __init__(self, answers: list[Any], *, create_status: int = 201) -> None: + self.answers = list(answers) + self.create_status = create_status + self.created: list[dict[str, Any]] = [] + self.headers: list[dict[str, str]] = [] + self.polls = 0 + + def post(self, url: str, *, json: Any, headers: dict[str, str]) -> _Response: + self.created.append(json) + self.headers.append(headers) + if self.create_status != 201: + return _Response(self.create_status, {"error": "refused"}) + return _Response(201, {"request_id": self.request_id}) + + def get(self, url: str, *, headers: dict[str, str]) -> _Response: + assert url.endswith("/" + self.request_id) + self.polls += 1 + answer = self.answers.pop(0) if self.answers else "pending" + if isinstance(answer, int): + return _Response(answer, {"error": "x"}) + if answer == "code": + sealed = seal(self.created[0]["public_key"], self.request_id, CODE) + return _Response(200, {"state": "answered", "sealed": sealed}) + return _Response(200, {"state": answer}) + + +class _Clock: + def __init__(self) -> None: + self.now = 0.0 + + def __call__(self) -> float: + return self.now + + def sleep(self, seconds: float) -> None: + self.now += seconds + + +def _http(plane: FakeControlPlane, clock: Optional[_Clock] = None) -> sf.HttpSource: + clock = clock or _Clock() + return sf.HttpSource( + "https://control.example/api/runners/runs/run-1/second-factor", + "run-token", + client=plane, + clock=clock, + sleep=clock.sleep, + ) + + +# -- sources ----------------------------------------------------------------- + + +def test_a_sealed_code_reaches_the_run_and_the_control_plane_holds_no_code() -> None: + plane = FakeControlPlane(["pending", 503, "code"]) + code = sf.obtain("code", "step_004", source=_http(plane), heartbeat=lambda: None) + assert code == CODE + (created,) = plane.created + assert set(created) == {"schema", "kind", "step_id", "public_key", "timeout_s"} + assert created["kind"] == "code" and created["step_id"] == "step_004" + assert created["timeout_s"] == int(sf.DEFAULT_TIMEOUT_S) + assert plane.headers[0]["authorization"] == "Bearer run-token" + # The request carries only a public key: nothing that could recover a code. + assert CODE not in json.dumps(plane.created) + + +@pytest.mark.parametrize( + ("answers", "code"), + [ + (["declined"], "second_factor_declined"), + (["expired"], "second_factor_timeout"), + ([], "second_factor_timeout"), # pending until the local deadline + ([403], "second_factor_unavailable"), + ([404], "second_factor_unavailable"), + (["approved"], "second_factor_invalid"), # wrong kind of answer + ], +) +def test_every_other_answer_stops_the_step_with_a_closed_code( + answers: list[Any], code: str +) -> None: + with pytest.raises(sf.SecondFactorRefused) as refused: + sf.obtain("code", "step_004", source=_http(FakeControlPlane(answers))) + assert refused.value.code == code + + +def test_a_control_plane_that_opens_no_request_is_unavailable() -> None: + with pytest.raises(sf.SecondFactorRefused) as refused: + sf.obtain("code", "s1", source=_http(FakeControlPlane([], create_status=404))) + assert refused.value.code == "second_factor_unavailable" + + +def test_a_ciphertext_sealed_for_another_request_does_not_open() -> None: + key = ec.generate_private_key(ec.SECP256R1()) + public = key.public_key().public_bytes( + serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint + ) + sealed = seal(_b64(public), "sfr-aaaaaaaaaaaaaaaa", CODE) + assert sf.open_sealed_code(key, "sfr-aaaaaaaaaaaaaaaa", sealed) == CODE + with pytest.raises(sf.SecondFactorRefused) as refused: + sf.open_sealed_code(key, "sfr-bbbbbbbbbbbbbbbb", sealed) + assert refused.value.code == "second_factor_invalid" + assert CODE not in str(refused.value) + + +def test_an_approval_waits_for_the_person_and_returns_no_value() -> None: + plane = FakeControlPlane(["pending", "approved"]) + assert sf.obtain("approval", "step_002", source=_http(plane)) is None + assert plane.created[0]["kind"] == "approval" + + +def test_the_url_must_be_https_and_needs_the_run_token() -> None: + for url in ("http://control.example/x", "https://u:p@control.example/x"): + with pytest.raises(sf.SecondFactorRefused): + sf.HttpSource(url, "t") + with pytest.raises(sf.SecondFactorRefused): + sf.HttpSource("https://control.example/x", "") + sf.HttpSource("http://127.0.0.1:8765/x", "t") # local test servers only + + +def _script(tmp_path: Path, body: str) -> str: + path = tmp_path / "source.py" + path.write_text(body) + path.chmod(path.stat().st_mode | stat.S_IEXEC) + return f"{sys.executable} {path}" + + +def test_a_local_command_supplies_the_code(tmp_path: Path) -> None: + command = _script( + tmp_path, + "import sys\nassert sys.argv[1:] == ['code', 'step_004']\nprint('482 913')\n", + ) + env = {sf.COMMAND_ENV: command} + assert sf.obtain("code", "step_004", env=env) == CODE + + +@pytest.mark.parametrize( + ("body", "code"), + [ + ("raise SystemExit(3)\n", "second_factor_declined"), + ("raise SystemExit(1)\n", "second_factor_unavailable"), + ("print('not a code!')\n", "second_factor_invalid"), + ("import time\ntime.sleep(30)\n", "second_factor_timeout"), + ], +) +def test_a_local_command_that_fails_types_nothing( + tmp_path: Path, body: str, code: str +) -> None: + env = {sf.COMMAND_ENV: _script(tmp_path, body), sf.TIMEOUT_ENV: "10"} + if code == "second_factor_timeout": + source = sf.CommandSource(env[sf.COMMAND_ENV]) + with pytest.raises(sf.SecondFactorRefused) as refused: + source.obtain(sf.Request("code", "s", 0.5), heartbeat=lambda: None) + else: + with pytest.raises(sf.SecondFactorRefused) as refused: + sf.obtain("code", "s", env=env) + assert refused.value.code == code + assert "not a code" not in str(refused.value) + + +def test_no_source_and_bad_timeouts_are_refused() -> None: + with pytest.raises(sf.SecondFactorRefused) as refused: + sf.obtain("code", "s", env={}) + assert refused.value.code == "second_factor_unavailable" + for raw in ("abc", "1", "100000"): + with pytest.raises(sf.SecondFactorRefused): + sf.timeout_from_env({sf.TIMEOUT_ENV: raw}) + assert sf.timeout_from_env({sf.TIMEOUT_ENV: "45"}) == 45.0 + + +@pytest.mark.parametrize("raw", ["123", "12345678901234567", "12 34 5!", 42, ""]) +def test_only_short_codes_of_letters_and_digits_are_typed(raw: object) -> None: + with pytest.raises(sf.SecondFactorRefused): + sf.normalize_code(raw) + assert sf.normalize_code(" ab-12 34 ") == "ab1234" + + +# -- program shape ------------------------------------------------------------- + + +def _code_step(**kw: Any) -> Step: + values: dict[str, Any] = dict( + id="step_004", + intent="type the one-time sign-in code", + action=ActionKind.TYPE, + param=sf.ONE_TIME_CODE_PARAM, + secret=True, + one_time="code", + ) + values.update(kw) + return Step(**values) + + +def test_one_time_steps_have_one_shape_and_others_keep_their_bytes() -> None: + _code_step() + Step(id="s", intent="approve", action=ActionKind.WAIT, one_time="approval") + for bad in ( + dict(secret=False), + dict(text="123456", secret=True), + dict(param=None), + dict(action=ActionKind.CLICK), + ): + with pytest.raises(ValueError): + _code_step(**bad) + with pytest.raises(ValueError): + Step(id="s", intent="x", action=ActionKind.WAIT, one_time="approval", text="x") + plain = Step(id="s", intent="x", action=ActionKind.CLICK) + assert "one_time" not in plain.model_dump(mode="json") + assert _code_step().model_dump(mode="json")["one_time"] == "code" + + +def test_the_code_is_no_workflow_input_and_its_frames_are_black() -> None: + from openadapt_flow.bundle_validation import build_runtime_parameter_schema + + workflow = Workflow(name="w", steps=[_code_step()]) + assert build_runtime_parameter_schema(workflow) == [] + assert sf.has_one_time_steps(workflow) + import io + + from PIL import Image + + buf = io.BytesIO() + Image.new("RGB", (8, 8), (250, 250, 250)).save(buf, format="PNG") + saved = persisted_run_frame(buf.getvalue(), workflow=workflow) + with Image.open(io.BytesIO(saved)) as frame: + assert frame.convert("RGB").getextrema() == ((0, 0), (0, 0), (0, 0)) + + +def test_a_code_page_submit_signs_in_and_saves_nothing(monkeypatch) -> None: + from openadapt_flow.compiler import compile as compile_module + + monkeypatch.setattr(compile_module, "_is_form_save", lambda raw: True) + steps = [ + _code_step(id="step_000"), + Step(id="step_001", intent="x", action=ActionKind.CLICK), + Step(id="step_002", intent="x", action=ActionKind.TYPE, text="a note"), + Step(id="step_003", intent="x", action=ActionKind.CLICK), + ] + found = _form_submit_steps( + steps, {"step_001": {}, "step_003": {}}, {"step_000": "one-time-code"} + ) + assert [s.id for s in found] == ["step_003"] + + +# -- replay ---------------------------------------------------------------------- + + +def _replay(tmp_path: Path, workflow: Workflow) -> tuple[Any, Any]: + from tests.test_replayer import FakeBackend, FakeVision + + backend = FakeBackend() + bundle = tmp_path / "bundle" + (bundle / "templates").mkdir(parents=True) + report = Replayer(backend, vision=FakeVision()).run( + workflow, params={}, bundle_dir=bundle, run_dir=tmp_path / "run" + ) + return report, backend + + +def _run_files(tmp_path: Path) -> bytes: + return b"".join( + p.read_bytes() for p in (tmp_path / "run").rglob("*") if p.is_file() + ) + + +def test_replay_types_the_code_once_and_writes_it_nowhere( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + command = _script(tmp_path, f"print('{CODE}')\n") + monkeypatch.setenv(sf.COMMAND_ENV, command) + report, backend = _replay(tmp_path, Workflow(name="w", steps=[_code_step()])) + assert report.success, [r.error for r in report.results] + assert ("type", CODE) in backend.actions + assert CODE.encode() not in _run_files(tmp_path) + + +def test_replay_with_no_source_stops_before_typing(tmp_path: Path) -> None: + report, backend = _replay(tmp_path, Workflow(name="w", steps=[_code_step()])) + assert not report.success + (result,) = report.results + assert "second_factor_unavailable" in (result.error or "") + assert result.failure_category == "governed_refusal" + assert not any(a[0] == "type" for a in backend.actions) + + +def test_replay_waits_for_a_push_approval( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv(sf.COMMAND_ENV, _script(tmp_path, "raise SystemExit(3)\n")) + step = Step( + id="step_000", intent="approve", action=ActionKind.WAIT, one_time="approval" + ) + report, _backend = _replay(tmp_path, Workflow(name="w", steps=[step])) + assert not report.success + assert "second_factor_declined" in (report.results[0].error or "") + monkeypatch.setenv(sf.COMMAND_ENV, _script(tmp_path, "pass\n")) + report, _backend = _replay(tmp_path / "again", Workflow(name="w", steps=[step])) + assert report.success, [r.error for r in report.results] + + +# -- recording --------------------------------------------------------------------- + + +class CodePageBackend: + """A second sign-in page with a one-time-code field.""" + + BOX = (100, 100, 120, 20) + + def __init__(self) -> None: + import io + + from PIL import Image + + buf = io.BytesIO() + Image.new("RGB", (640, 400), (250, 250, 250)).save(buf, format="PNG") + self._png = buf.getvalue() + self.typed: list[str] = [] + self.focus: Optional[str] = "one-time-code" + + @property + def viewport(self) -> tuple[int, int]: + return (640, 400) + + def screenshot(self) -> bytes: + return self._png + + def click(self, x: int, y: int, *, double: bool = False) -> None: + pass + + def type_text(self, text: str) -> None: + self.typed.append(text) + + def press(self, key: str) -> None: + pass + + def scroll(self, dx: int, dy: int) -> None: + pass + + def focused_field_credential(self) -> Optional[dict[str, Any]]: + return {"kind": self.focus, "box": self.BOX} if self.focus else None + + def credential_field_at(self, x: int, y: int) -> Optional[str]: + return "one-time-code" + + +def test_recording_types_the_persons_code_and_keeps_only_the_param( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv(sf.COMMAND_ENV, _script(tmp_path, f"print('{CODE}')\n")) + backend = CodePageBackend() + rec = Recorder(backend, tmp_path / "rec", app_url="http://fake.local/") + rec.withhold_credentials({"note": "a note"}) + rec.type_text(sf.ONE_TIME_CODE_MARKER) + directory = rec.finish() + assert backend.typed == [CODE] + events = [ + json.loads(line) + for line in (directory / "events.jsonl").read_text().splitlines() + if line.strip() + ] + (typed,) = [e for e in events if e.get("kind") == "type"] + assert typed["one_time"] == "code" and typed["param"] == sf.ONE_TIME_CODE_PARAM + assert "text" not in typed + meta = json.loads((directory / "meta.json").read_text()) + assert meta["secret_params"] == [] and sf.ONE_TIME_CODE_PARAM not in meta["params"] + for path in directory.rglob("*"): + if path.is_file(): + assert CODE.encode() not in path.read_bytes() + + +def test_recording_refuses_a_code_field_without_a_source_or_with_an_input( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + backend = CodePageBackend() + rec = Recorder(backend, tmp_path / "rec", app_url="http://fake.local/") + rec.withhold_credentials({"note": "a note"}) + with pytest.raises(CredentialFieldError, match="second_factor_unavailable"): + rec.type_text(sf.ONE_TIME_CODE_MARKER) + monkeypatch.setenv(sf.COMMAND_ENV, _script(tmp_path, f"print('{CODE}')\n")) + with pytest.raises(CredentialFieldError): + rec.type_text("a note") + assert backend.typed == [] From 7a0bc70cdb3d105736ec4553100668f77b2258b7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 19:10:03 -0500 Subject: [PATCH 02/12] test(flow): pin the dashboard seal vector shared with Cloud --- .../fixtures/second_factor_seal_vector.json | 12 ++++++++++ packages/flow/tests/test_second_factor.py | 22 +++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 packages/flow/tests/fixtures/second_factor_seal_vector.json diff --git a/packages/flow/tests/fixtures/second_factor_seal_vector.json b/packages/flow/tests/fixtures/second_factor_seal_vector.json new file mode 100644 index 0000000000..1b7f03f252 --- /dev/null +++ b/packages/flow/tests/fixtures/second_factor_seal_vector.json @@ -0,0 +1,12 @@ +{ + "note": "Synthetic wire-format vector: secondFactorSeal.ts seals, openadapt_flow.second_factor.open_sealed_code opens. The run key is the P-256 scalar SHA-256(run_key_seed), a public test value.", + "run_key_seed": "openadapt second-factor synthetic test vector", + "run_public_key": "BCySf7D-DhwAQHNR2R-J_crpTxIR5qzmFOr5uvpqtaXtbuLLUELDofMbLJP3HfgNa_OpUEJCJjLU-eYvQjcMMfc", + "request_id": "00000000-0000-4000-8000-0000000000e1", + "code": "482913", + "sealed": { + "epk": "BP0xFqpAGEbwyVaGyOCc-D1ZwPlgcJX-j59awdxgeJ-WE9UaEbCL12YoEs7gONn57C5KT099YyEQcnG0oHEeBs0", + "iv": "FnClKR5AzLFoiIqJ", + "ciphertext": "VRAiPy3DGbYfhcXGb9p93137b-d7ow" + } +} diff --git a/packages/flow/tests/test_second_factor.py b/packages/flow/tests/test_second_factor.py index d990e65602..624ffec434 100644 --- a/packages/flow/tests/test_second_factor.py +++ b/packages/flow/tests/test_second_factor.py @@ -460,3 +460,25 @@ def test_recording_refuses_a_code_field_without_a_source_or_with_an_input( with pytest.raises(CredentialFieldError): rec.type_text("a note") assert backend.typed == [] + + +def test_the_dashboard_seal_vector_opens_here() -> None: + """The same vector openadapt-cloud's secondFactorSeal.ts produced.""" + + import hashlib + + vector = json.loads( + ( + Path(__file__).parent / "fixtures" / "second_factor_seal_vector.json" + ).read_text() + ) + scalar = int.from_bytes( + hashlib.sha256(vector["run_key_seed"].encode()).digest(), "big" + ) + key = ec.derive_private_key(scalar, ec.SECP256R1()) + public = key.public_key().public_bytes( + serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint + ) + assert _b64(public) == vector["run_public_key"] + opened = sf.open_sealed_code(key, vector["request_id"], vector["sealed"]) + assert sf.normalize_code(opened) == vector["code"] From 682cb3e17c6f29cbbf4142cf1e7a87a75f4d5382 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 19:20:35 -0500 Subject: [PATCH 03/12] refactor(flow): keep second-factor shape checks out of the budgeted modules Raises the replayer budget by 7 lines and ir.py by 3 for the two hooks and the Step field; lowers playwright_backend.py to its new size. --- packages/flow/docs/design/DECOMPOSITION.md | 6 ++-- .../backends/_field_metadata_js.py | 2 ++ .../backends/playwright_backend.py | 20 +++-------- packages/flow/openadapt_flow/ir.py | 34 ++----------------- .../flow/openadapt_flow/runtime/replayer.py | 7 ++-- packages/flow/openadapt_flow/second_factor.py | 21 ++++++++++++ 6 files changed, 35 insertions(+), 55 deletions(-) diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 8121b4fab0..711586a087 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -605,16 +605,16 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh | File | Line budget | |---|---:| -| `packages/flow/openadapt_flow/runtime/replayer.py` | 20131 | +| `packages/flow/openadapt_flow/runtime/replayer.py` | 20138 | | `packages/flow/openadapt_flow/__main__.py` | 14530 | | `packages/flow/openadapt_flow/qualification.py` | 5963 | -| `packages/flow/openadapt_flow/ir.py` | 6865 | +| `packages/flow/openadapt_flow/ir.py` | 6868 | | `packages/desktop/openadapt_desktop/dispatch.py` | 6524 | | `packages/capture/openadapt_capture/recorder.py` | 4836 | | `packages/flow/openadapt_flow/interactive_recorder.py` | 4808 | | `packages/flow/openadapt_flow/runtime/durable/attended.py` | 4368 | | `packages/flow/openadapt_flow/terminal_verification_v2.py` | 3673 | -| `packages/flow/openadapt_flow/backends/playwright_backend.py` | 6820 | +| `packages/flow/openadapt_flow/backends/playwright_backend.py` | 6818 | ## 7. Coordination with work in flight diff --git a/packages/flow/openadapt_flow/backends/_field_metadata_js.py b/packages/flow/openadapt_flow/backends/_field_metadata_js.py index ff59c1802d..1c2afa6314 100644 --- a/packages/flow/openadapt_flow/backends/_field_metadata_js.py +++ b/packages/flow/openadapt_flow/backends/_field_metadata_js.py @@ -13,6 +13,8 @@ # placeholder, name attribute, title. Whitespace-collapsed; null when the # element is not an editable field or carries no label evidence. PASSIVE # record-time metadata only (see openadapt_flow.backend.FieldLabelBackend). +#: The kinds ``_FIELD_CREDENTIAL_JS`` reports for a credential field. +_CREDENTIAL_KINDS = ("password", "new-password", "username", "one-time-code") #: Whether the focused element takes a sign-in credential. See #: :meth:`PlaywrightBackend.focused_field_credential` for the rules. _FIELD_CREDENTIAL_JS = r"""(el) => { diff --git a/packages/flow/openadapt_flow/backends/playwright_backend.py b/packages/flow/openadapt_flow/backends/playwright_backend.py index dc4154a755..6e835b957c 100644 --- a/packages/flow/openadapt_flow/backends/playwright_backend.py +++ b/packages/flow/openadapt_flow/backends/playwright_backend.py @@ -24,6 +24,7 @@ from openadapt_flow.backends._field_metadata_js import ( _CREDENTIAL_AT_JS, + _CREDENTIAL_KINDS, _DISPLAYED_TEXT_AT_JS, _EDITABLE_VALUE_JS, _FIELD_CREDENTIAL_JS, @@ -3280,8 +3281,7 @@ def focused_field_credential(self) -> Optional[dict[str, Any]]: password candidates in the composed form (the document when it has no form). Ambiguous controls return ``unknown``; CSS visibility is not used as evidence that a password candidate is irrelevant; - * ``one-time-code``: an input whose ``autocomplete`` names - ``one-time-code`` (a sign-in's second factor). + ``one-time-code``: ``autocomplete`` names it (a second factor). ``box`` is in top-document viewport pixels, or None when the element's box could not be read. Read-only and never raises. None @@ -3295,7 +3295,7 @@ def focused_field_credential(self) -> Optional[dict[str, Any]]: kind = self._focused_element_call(_FIELD_CREDENTIAL_JS, box_out=box) if kind == "none": return None - if kind not in ("password", "new-password", "username", "one-time-code"): + if kind not in _CREDENTIAL_KINDS: # The focused control could not be read (a frame chain that does # not verify, a failed call). The recorder refuses to type a # declared input into it. @@ -3323,19 +3323,7 @@ def credential_field_at(self, x: int, y: int) -> Optional[str]: found = self.page.evaluate(_CREDENTIAL_AT_JS, [int(x), int(y)]) except Exception: return "unknown" - return ( - found - if found - in ( - "password", - "new-password", - "username", - "one-time-code", - "frame", - "unknown", - ) - else None - ) + return found if found in (*_CREDENTIAL_KINDS, "frame", "unknown") else None def _focused_element_eval(self, js: str) -> Optional[str]: """Evaluate ``js`` on the focused element, descending nested frames. diff --git a/packages/flow/openadapt_flow/ir.py b/packages/flow/openadapt_flow/ir.py index a1f6c06e62..a08f85c890 100644 --- a/packages/flow/openadapt_flow/ir.py +++ b/packages/flow/openadapt_flow/ir.py @@ -64,6 +64,7 @@ GradeGate, ReadProof, ) +from openadapt_flow.second_factor import check_step_shape as _check_one_time_shape if TYPE_CHECKING: # Type-only import for the Step.effects forward reference. The RUNTIME @@ -2363,19 +2364,7 @@ class Step(BaseModel): " compiler.annotate.FieldLabelAnnotator)." ), ) - one_time: Optional[Literal["code", "approval"]] = Field( - default=None, - description=( - "A sign-in's second factor (see openadapt_flow.second_factor)." - " ``code``: a secret TYPE step into a one-time-code field; the" - " value comes from a person through the configured source when" - " the step runs, is typed once and is never stored. Its param is" - " not a workflow input or a secret parameter. ``approval``: a WAIT" - " step at a push-approval prompt; the run waits until a person" - " says they approved it on their device. Absent on every other" - " step, so older bundles keep their bytes." - ), - ) + one_time: Optional[Literal["code", "approval"]] = None # second_factor.py native_selection: Optional[NativeSelectContract] = None choice: Optional[OptionChoice] = Field( default=None, @@ -2597,24 +2586,7 @@ def _serialize_compatible(self, handler: Any) -> dict[str, Any]: @model_validator(mode="after") def _validate_one_time(self) -> "Step": - if self.one_time == "code" and not ( - self.action is ActionKind.TYPE - and self.secret - and self.param - and self.text is None - ): - raise ValueError( - "a one-time code step is a secret TYPE step that names its " - "param and carries no text" - ) - if self.one_time == "approval" and ( - self.action is not ActionKind.WAIT - or self.secret - or self.param is not None - or self.text is not None - ): - raise ValueError("a one-time approval step is a WAIT with no input") - return self + return _check_one_time_shape(self) @model_validator(mode="after") def _validate_target_param(self) -> "Step": diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 05578a4e21..29ab5383cc 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -14085,9 +14085,7 @@ def _act_without_dialog( return None if step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION): - if step.secret and step.one_time == "code": - # A sign-in's one-time code: asked for now, typed once, kept - # nowhere (openadapt_flow.second_factor). + if step.secret and step.one_time == "code": # asked of a person now text, refusal = _second_factor.runtime_value(step, result) if refusal is not None: return refusal @@ -14539,8 +14537,7 @@ def _act_without_dialog( return None if step.action is ActionKind.WAIT: - if step.one_time == "approval": - # A push approval: a person approves on their own device. + if step.one_time == "approval": # a person approves on their device return _second_factor.runtime_value(step, result)[1] # WAIT means wait_settled only; the post-action settle handles it. return None diff --git a/packages/flow/openadapt_flow/second_factor.py b/packages/flow/openadapt_flow/second_factor.py index a247ab69ce..1a4e1626b8 100644 --- a/packages/flow/openadapt_flow/second_factor.py +++ b/packages/flow/openadapt_flow/second_factor.py @@ -53,6 +53,7 @@ "CommandSource", "HttpSource", "SecondFactorRefused", + "check_step_shape", "has_one_time_steps", "normalize_code", "obtain", @@ -217,6 +218,26 @@ def obtain( return normalize_code(value) +def check_step_shape(step: Any) -> Any: + """``ir.Step``'s validator for ``one_time``; returns the step or raises.""" + + if step.one_time == "code" and not ( + step.action.value == "type" and step.secret and step.param and step.text is None + ): + raise ValueError( + "a one-time code step is a secret TYPE step that names its param " + "and carries no text" + ) + if step.one_time == "approval" and ( + step.action.value != "wait" + or step.secret + or step.param is not None + or step.text is not None + ): + raise ValueError("a one-time approval step is a WAIT with no input") + return step + + def has_one_time_steps(workflow: Any) -> bool: """Whether any step of ``workflow`` (linear or program graph) is one-time.""" From fe61366e1bf43a40e3efb5c91b2d1fc047634d34 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 19:36:52 -0500 Subject: [PATCH 04/12] fix(flow): give a cached run's MCP child the run token with the control-plane URL --- packages/flow/docs/SECOND_FACTOR.md | 2 +- .../integrations/agents/skills.py | 7 ++--- packages/flow/openadapt_flow/second_factor.py | 14 +++++++-- packages/flow/tests/test_second_factor.py | 31 +++++++++++++++++++ 4 files changed, 47 insertions(+), 7 deletions(-) diff --git a/packages/flow/docs/SECOND_FACTOR.md b/packages/flow/docs/SECOND_FACTOR.md index bda01f7867..839c414696 100644 --- a/packages/flow/docs/SECOND_FACTOR.md +++ b/packages/flow/docs/SECOND_FACTOR.md @@ -66,7 +66,7 @@ first match wins. stderr every 20 seconds, so a supervisor that ends silent runs doesn't end one that is waiting for a person. -A cached `openadapt wrap` run passes these three variables to the program's +A cached `openadapt wrap` run passes these variables, and `OPENADAPT_RUNNER_TOKEN` when it is set, to the program's MCP server. ### The control-plane protocol diff --git a/packages/flow/openadapt_flow/integrations/agents/skills.py b/packages/flow/openadapt_flow/integrations/agents/skills.py index 74ce503cb9..42e8650a0c 100644 --- a/packages/flow/openadapt_flow/integrations/agents/skills.py +++ b/packages/flow/openadapt_flow/integrations/agents/skills.py @@ -1090,12 +1090,11 @@ async def _call_skill(python: str, server: Path, params: dict[str, Any]) -> dict from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import get_default_environment, stdio_client - from openadapt_flow.second_factor import SOURCE_ENV_KEYS + from openadapt_flow.second_factor import source_env # The stdio client passes only a minimal environment. A sign-in's second - # factor source is operator configuration the cached run needs too. - env = get_default_environment() - env.update({k: os.environ[k] for k in SOURCE_ENV_KEYS if os.environ.get(k)}) + # factor source (and its run token) is what the cached run needs too. + env = {**get_default_environment(), **source_env()} target = StdioServerParameters(command=python, args=[str(server)], env=env) async with stdio_client(target) as (read, write): async with ClientSession(read, write) as session: diff --git a/packages/flow/openadapt_flow/second_factor.py b/packages/flow/openadapt_flow/second_factor.py index 1a4e1626b8..29e8cb3194 100644 --- a/packages/flow/openadapt_flow/second_factor.py +++ b/packages/flow/openadapt_flow/second_factor.py @@ -59,6 +59,7 @@ "obtain", "open_sealed_code", "runtime_value", + "source_env", "source_from_env", "timeout_from_env", ] @@ -69,8 +70,17 @@ TOKEN_ENV = "OPENADAPT_RUNNER_TOKEN" COMMAND_ENV = "OPENADAPT_SECOND_FACTOR_COMMAND" TIMEOUT_ENV = "OPENADAPT_SECOND_FACTOR_TIMEOUT_S" -#: The operator configuration a run's child processes need for a source. -SOURCE_ENV_KEYS = (URL_ENV, COMMAND_ENV, TIMEOUT_ENV) +#: What a run's child processes need for a source: its configuration and, +#: for the control plane, the run token that authorizes the request. +SOURCE_ENV_KEYS = (URL_ENV, TOKEN_ENV, COMMAND_ENV, TIMEOUT_ENV) + + +def source_env(environ: Optional[Mapping[str, str]] = None) -> dict[str, str]: + """The set :data:`SOURCE_ENV_KEYS` of ``environ``, for a child process.""" + + environ = os.environ if environ is None else environ + return {key: environ[key] for key in SOURCE_ENV_KEYS if environ.get(key)} + #: How long a step waits for a person by default, and the bounds an #: operator may set with :data:`TIMEOUT_ENV`. diff --git a/packages/flow/tests/test_second_factor.py b/packages/flow/tests/test_second_factor.py index 624ffec434..23cccf9d2a 100644 --- a/packages/flow/tests/test_second_factor.py +++ b/packages/flow/tests/test_second_factor.py @@ -482,3 +482,34 @@ def test_the_dashboard_seal_vector_opens_here() -> None: assert _b64(public) == vector["run_public_key"] opened = sf.open_sealed_code(key, vector["request_id"], vector["sealed"]) assert sf.normalize_code(opened) == vector["code"] + + +def test_a_cached_runs_child_gets_the_url_with_its_run_token( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import asyncio + + from openadapt_flow.integrations.agents import skills + + monkeypatch.setenv( + sf.URL_ENV, "https://control.example/api/runners/runs/r/second-factor" + ) + monkeypatch.setenv(sf.TOKEN_ENV, "run-token") + monkeypatch.setenv("UNRELATED_SECRET", "x") + seen: dict[str, Any] = {} + + class Stop(Exception): + pass + + def fake_client(target: Any) -> Any: + seen["env"] = dict(target.env) + raise Stop + + import mcp.client.stdio as stdio + + monkeypatch.setattr(stdio, "stdio_client", fake_client) + with pytest.raises(Stop): + asyncio.run(skills._call_skill(sys.executable, Path("server.py"), {})) + assert seen["env"][sf.URL_ENV].startswith("https://control.example/") + assert seen["env"][sf.TOKEN_ENV] == "run-token" + assert "UNRELATED_SECRET" not in seen["env"] From 9bbbd150fe0f39bea6935d3a23c485ff1f293d7e Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 20:10:33 -0500 Subject: [PATCH 05/12] feat(flow): ask for a sign-in's second factor at the run's own terminal An interactive run with no other source asks at its terminal (no echo for a code, the same timeout). A run without a terminal never prompts and stops before typing, as before. --- CAPABILITIES.md | 2 +- llms-full.txt | 7 +- packages/flow/CHANGELOG.md | 5 + packages/flow/docs/SECOND_FACTOR.md | 2 + packages/flow/openadapt_flow/second_factor.py | 94 ++++++++++++++++++- packages/flow/tests/test_second_factor.py | 82 ++++++++++++++++ 6 files changed, 188 insertions(+), 4 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 97eba214b7..d9e7f54fc6 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -320,7 +320,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 (draft), 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 | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | 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 step marked `one_time` (`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; the code is typed once and never stored, logged or put in a report, and frames are blacked out. No source, no answer in time, a decline or a malformed answer stops the step before typing with a closed `second_factor_*` code. 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 | 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; unit tests for both sources, the sealing format and every refusal). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, [SECOND_FACTOR.md](packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.py`, `packages/flow/tests/e2e/test_wrap_second_factor_e2e.py` | +| Sign-ins with a second factor: a step marked `one_time` (`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; the code is typed once and never stored, logged or put in a report, and frames are blacked out. No source, no answer in time, a decline or a malformed answer stops the step before typing with a closed `second_factor_*` code. 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 | 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; unit tests for both sources, the sealing format and every refusal). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, [SECOND_FACTOR.md](packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.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 | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `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 a43e4f5d4e..047ff09ba2 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -754,7 +754,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 (draft), 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 | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | 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 step marked `one_time` (`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; the code is typed once and never stored, logged or put in a report, and frames are blacked out. No source, no answer in time, a decline or a malformed answer stops the step before typing with a closed `second_factor_*` code. 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 | 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; unit tests for both sources, the sealing format and every refusal). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, [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/e2e/test_wrap_second_factor_e2e.py` | +| Sign-ins with a second factor: a step marked `one_time` (`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; the code is typed once and never stored, logged or put in a report, and frames are blacked out. No source, no answer in time, a decline or a malformed answer stops the step before typing with a closed `second_factor_*` code. 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 | 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; unit tests for both sources, the sealing format and every refusal). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, [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/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 | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GUARD_AN_AGENT.md) | @@ -2391,6 +2391,11 @@ automation into an independently certified transaction system. person's browser to a one-step P-256 key. The wrap recorder turns a field marked `autocomplete="one-time-code"` into such a step, and a code-only form's submit counts as a sign-in, not a save. 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 other source is set: the code is not + echoed, and the wait has the same timeout. A run without a terminal never + prompts and still stops before typing. `OPENADAPT_SECOND_FACTOR_PROMPT=off` + turns the prompt off. - Dropdowns, searchable selects, type-aheads and native selects are recorded, compiled and run as one model, a choice (`OptionChoice` on a `SELECT_OPTION` step, docs/CHOICES.md). A click on an option of a list the diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index e3f4b18356..d695b5ecac 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -31,6 +31,11 @@ person's browser to a one-step P-256 key. The wrap recorder turns a field marked `autocomplete="one-time-code"` into such a step, and a code-only form's submit counts as a sign-in, not a save. 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 other source is set: the code is not + echoed, and the wait has the same timeout. A run without a terminal never + prompts and still stops before typing. `OPENADAPT_SECOND_FACTOR_PROMPT=off` + turns the prompt off. - Dropdowns, searchable selects, type-aheads and native selects are recorded, compiled and run as one model, a choice (`OptionChoice` on a `SELECT_OPTION` step, docs/CHOICES.md). A click on an option of a list the diff --git a/packages/flow/docs/SECOND_FACTOR.md b/packages/flow/docs/SECOND_FACTOR.md index 839c414696..29aeff3ddb 100644 --- a/packages/flow/docs/SECOND_FACTOR.md +++ b/packages/flow/docs/SECOND_FACTOR.md @@ -61,6 +61,8 @@ 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 | + `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 stderr every 20 seconds, so a supervisor that ends silent runs doesn't end diff --git a/packages/flow/openadapt_flow/second_factor.py b/packages/flow/openadapt_flow/second_factor.py index 29e8cb3194..42762622ae 100644 --- a/packages/flow/openadapt_flow/second_factor.py +++ b/packages/flow/openadapt_flow/second_factor.py @@ -22,7 +22,12 @@ `` code|approval `` with no shell. Exit 0 prints the code (or confirms the approval), exit 3 means the person declined. -With no source, or when the source fails, times out or declines, the step +- The terminal, when the run 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. + +A run with no terminal (a service, a hosted sandbox, an MCP server) never +prompts. With no source, or when the source fails, times out or declines, the step stops before anything is typed, with one closed code from :data:`REFUSAL_CODES`. """ @@ -53,6 +58,7 @@ "CommandSource", "HttpSource", "SecondFactorRefused", + "TerminalSource", "check_step_shape", "has_one_time_steps", "normalize_code", @@ -70,9 +76,11 @@ TOKEN_ENV = "OPENADAPT_RUNNER_TOKEN" COMMAND_ENV = "OPENADAPT_SECOND_FACTOR_COMMAND" TIMEOUT_ENV = "OPENADAPT_SECOND_FACTOR_TIMEOUT_S" +#: ``off`` stops an interactive run from asking at its terminal. +PROMPT_ENV = "OPENADAPT_SECOND_FACTOR_PROMPT" #: What a run's child processes need for a source: its configuration and, #: for the control plane, the run token that authorizes the request. -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]: @@ -196,6 +204,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) + if (env.get(PROMPT_ENV) or "").strip().lower() not in ("off", "0", "false"): + terminal = TerminalSource.open() + if terminal is not None: + return terminal return None @@ -277,6 +289,84 @@ def beat() -> None: return beat +# -- terminal source --------------------------------------------------------- + + +class TerminalSource: + """Ask the person at the run's own terminal (no echo for a code).""" + + def __init__(self, tty_in: Any, tty_out: Any) -> None: + self._in = tty_in + self._out = tty_out + + @classmethod + def open(cls) -> Optional["TerminalSource"]: + try: + if not (sys.stdin.isatty() and sys.stderr.isatty()): + return None + except (AttributeError, ValueError): + return None + return cls(sys.stdin, sys.stderr) + + def _ask(self, prompt: str, *, hidden: bool, timeout_s: float) -> Optional[str]: + import getpass + import threading + + answer: list[Optional[str]] = [None] + + def read() -> None: + try: + if hidden: + answer[0] = getpass.getpass(prompt, stream=self._out) + else: + self._out.write(prompt) + self._out.flush() + answer[0] = self._in.readline() + except (EOFError, OSError, KeyboardInterrupt): + answer[0] = None + + reader = threading.Thread(target=read, daemon=True) + reader.start() + reader.join(timeout_s) + if reader.is_alive(): + self._out.write("\n") + raise SecondFactorRefused( + "second_factor_timeout", + f"no second factor within {timeout_s:g} s; nothing was typed", + ) + if answer[0] is None: + raise SecondFactorRefused( + "second_factor_unavailable", "the terminal closed; nothing was typed" + ) + return answer[0] + + def obtain( + self, request: Request, *, heartbeat: Callable[[], None] + ) -> Optional[str]: + 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, + timeout_s=request.timeout_s, + ) + if (reply or "").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, + timeout_s=request.timeout_s, + ) + if not (reply or "").strip(): + raise SecondFactorRefused( + "second_factor_declined", "the person declined; nothing was typed" + ) + return reply + + # -- command source ---------------------------------------------------------- diff --git a/packages/flow/tests/test_second_factor.py b/packages/flow/tests/test_second_factor.py index 23cccf9d2a..270fb99102 100644 --- a/packages/flow/tests/test_second_factor.py +++ b/packages/flow/tests/test_second_factor.py @@ -513,3 +513,85 @@ def fake_client(target: Any) -> Any: assert seen["env"][sf.URL_ENV].startswith("https://control.example/") assert seen["env"][sf.TOKEN_ENV] == "run-token" assert "UNRELATED_SECRET" not in seen["env"] + + +# -- terminal source ------------------------------------------------------------- + + +class _Tty: + def __init__(self, lines: list[str]) -> None: + self.lines = list(lines) + self.written: list[str] = [] + + def readline(self) -> str: + return self.lines.pop(0) if self.lines else "" + + def write(self, text: str) -> int: + self.written.append(text) + return len(text) + + def flush(self) -> None: + pass + + +def test_the_terminal_asks_without_echo_and_keeps_nothing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import getpass + + asked: list[str] = [] + monkeypatch.setattr( + getpass, + "getpass", + lambda prompt, stream=None: asked.append(prompt) or "482 913", + ) + source = sf.TerminalSource(_Tty([]), _Tty([])) + assert sf.obtain("code", "step_004", source=source) == CODE + assert asked and "not shown" in asked[0] + monkeypatch.setattr(getpass, "getpass", lambda prompt, stream=None: "") + with pytest.raises(sf.SecondFactorRefused) as refused: + sf.obtain("code", "step_004", source=source) + assert refused.value.code == "second_factor_declined" + + +def test_the_terminal_confirms_or_declines_an_approval() -> None: + assert ( + sf.obtain("approval", "s", source=sf.TerminalSource(_Tty(["\n"]), _Tty([]))) + is None + ) + with pytest.raises(sf.SecondFactorRefused) as refused: + sf.obtain("approval", "s", source=sf.TerminalSource(_Tty(["n\n"]), _Tty([]))) + assert refused.value.code == "second_factor_declined" + + +def test_a_terminal_that_does_not_answer_times_out( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import getpass + import threading + + block = threading.Event() + monkeypatch.setattr( + getpass, "getpass", lambda prompt, stream=None: block.wait(5) and "" + ) + source = sf.TerminalSource(_Tty([]), _Tty([])) + with pytest.raises(sf.SecondFactorRefused) as refused: + source.obtain(sf.Request("code", "s", 0.2), heartbeat=lambda: None) + assert refused.value.code == "second_factor_timeout" + block.set() + + +def test_a_run_without_a_terminal_never_prompts( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class NotTty: + def isatty(self) -> bool: + return False + + monkeypatch.setattr(sys, "stdin", NotTty()) + assert sf.source_from_env({}) is None + monkeypatch.setattr( + sf.TerminalSource, "open", classmethod(lambda cls: cls(None, None)) + ) + assert isinstance(sf.source_from_env({}), sf.TerminalSource) + assert sf.source_from_env({sf.PROMPT_ENV: "off"}) is None From fddab5f699c952b9227e8f6f53ae4d4decc24480 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 10:23:27 -0500 Subject: [PATCH 06/12] refactor(flow): keep ir.py and replayer.py within their size budgets Budgets no longer rise (#2430). The environment-secret lookup for a secret TYPE step moves from the replayer into secret_inputs.step_secret_text, so the one-time code branch adds no lines. ir.Step's serializer drops unset optional fields in one loop, and the one_time validator is bound beside its field. The replayer imports runtime_value itself rather than the second_factor module, so runtime/__init__'s lazy Replayer export is no new import-layer debt site. replayer.py budget lowered to 19224. --- packages/flow/docs/design/DECOMPOSITION.md | 2 +- packages/flow/openadapt_flow/ir.py | 16 +++------ .../flow/openadapt_flow/runtime/replayer.py | 34 ++++++------------- packages/flow/openadapt_flow/secret_inputs.py | 22 ++++++++++++ 4 files changed, 38 insertions(+), 36 deletions(-) diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 1509a04b87..de7fb38059 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -607,7 +607,7 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh | File | Line budget | |---|---:| -| `packages/flow/openadapt_flow/runtime/replayer.py` | 19229 | +| `packages/flow/openadapt_flow/runtime/replayer.py` | 19224 | | `packages/flow/openadapt_flow/__main__.py` | 14331 | | `packages/flow/openadapt_flow/qualification/__init__.py` | 4891 | | `packages/flow/openadapt_flow/ir.py` | 6830 | diff --git a/packages/flow/openadapt_flow/ir.py b/packages/flow/openadapt_flow/ir.py index 90fe42edeb..f83bf0fe3a 100644 --- a/packages/flow/openadapt_flow/ir.py +++ b/packages/flow/openadapt_flow/ir.py @@ -2366,6 +2366,7 @@ class Step(BaseModel): ), ) one_time: Optional[Literal["code", "approval"]] = None # second_factor.py + _validate_one_time = model_validator(mode="after")(_check_one_time_shape) native_selection: Optional[NativeSelectContract] = None choice: Optional[OptionChoice] = Field( default=None, @@ -2575,20 +2576,11 @@ def _validate_surface_contract(self) -> "Step": def _serialize_compatible(self, handler: Any) -> dict[str, Any]: """Keep steps without a selected-record parameter byte-identical.""" data: dict[str, Any] = handler(self) - if self.target_param is None: - data.pop("target_param", None) - if self.one_time is None: - data.pop("one_time", None) - if self.native_selection is None: - data.pop("native_selection", None) - if self.choice is None: - data.pop("choice", None) + for key in ("target_param", "one_time", "native_selection", "choice"): + if getattr(self, key) is None: + data.pop(key, None) return data - @model_validator(mode="after") - def _validate_one_time(self) -> "Step": - return _check_one_time_shape(self) - @model_validator(mode="after") def _validate_target_param(self) -> "Step": if self.target_param is None: diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 2d492fbaa5..328ed9dc87 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -70,7 +70,6 @@ from urllib.parse import urlsplit from openadapt_flow import sealed_set as _sealed -from openadapt_flow import second_factor as _second_factor from openadapt_flow.assurance import effect_read_wording as _effect_read_wording from openadapt_flow.backend import ( ActionDeliveryUncertain, @@ -265,11 +264,13 @@ from openadapt_flow.runtime.step_timing import timed_span from openadapt_flow.runtime.surfaces import SurfaceRouter from openadapt_flow.runtime.typed_echo import read_typed_echo +from openadapt_flow.second_factor import runtime_value as _one_time_value from openadapt_flow.secret_inputs import ( # noqa: F401 - compatibility exports SECRET_ENV_PREFIX, require_secret_sources, secret_env_var, secret_env_vars, + step_secret_text, ) from openadapt_flow.verification import ( EffectContractMutationError, @@ -13353,29 +13354,16 @@ def _act_without_dialog( return None if step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION): - if step.secret and step.one_time == "code": # asked of a person now - text, refusal = _second_factor.runtime_value(step, result) + if step.secret: # never in the bundle/params (secret_inputs.py) + text, refusal = ( + _one_time_value(step, result) + if step.one_time == "code" # asked of a person now + else step_secret_text( + step, getattr(self, "secret_env_overrides", {}) + ) + ) if refusal is not None: return refusal - elif step.secret: - # Secret value is never in the bundle/params: inject it from - # the environment, failing fast with an actionable message. - env_var = getattr(self, "secret_env_overrides", {}).get( - step.param or "" - ) or secret_env_var(step.param or "") - text = os.environ.get(env_var, "") - if not step.param: - return ( - f"Step '{step.id}' ({step.intent}) is marked secret " - "but names no parameter" - ) - if not text: - return ( - f"Step '{step.id}' ({step.intent}) requires secret " - f"parameter '{step.param}', but the environment " - f"variable {env_var} is not set — export it with the " - "secret value and re-run" - ) elif step.param is not None: if step.param not in params: return ( @@ -13810,7 +13798,7 @@ def _act_without_dialog( if step.action is ActionKind.WAIT: if step.one_time == "approval": # a person approves on their device - return _second_factor.runtime_value(step, result)[1] + return _one_time_value(step, result)[1] # WAIT means wait_settled only; the post-action settle handles it. return None diff --git a/packages/flow/openadapt_flow/secret_inputs.py b/packages/flow/openadapt_flow/secret_inputs.py index 53a1b348ab..e472958eea 100644 --- a/packages/flow/openadapt_flow/secret_inputs.py +++ b/packages/flow/openadapt_flow/secret_inputs.py @@ -79,6 +79,28 @@ def secret_env_vars(params: Sequence[str]) -> dict[str, str]: return keys +def step_secret_text(step: Any, overrides: Mapping[str, str]) -> tuple[str, str | None]: + """A secret step's value from the environment: ``(text, None)`` or a refusal. + + The value is never in the bundle or params. A missing value fails fast with + an actionable message instead of typing an empty string. + """ + env_var = overrides.get(step.param or "") or secret_env_var(step.param or "") + text = os.environ.get(env_var, "") + if not step.param: + return "", ( + f"Step '{step.id}' ({step.intent}) is marked secret but names no parameter" + ) + if not text: + return "", ( + f"Step '{step.id}' ({step.intent}) requires secret " + f"parameter '{step.param}', but the environment " + f"variable {env_var} is not set — export it with the " + "secret value and re-run" + ) + return text, None + + def require_secret_sources( params: Mapping[str, Any], secret_params: Sequence[str] ) -> None: From 2c4b0d09c6a764418495fddea98387835688524a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 20:32:00 -0500 Subject: [PATCH 07/12] fix(flow): bind, mask and type a second factor once, as its own action The Codex review at fddab5f6 found ten ways the one-time-code path could leak a code, type it twice, type it into the wrong field or be skipped. They share causes, so this replaces the per-path hooks with one handoff that the recorder and the replayer both run (openadapt_flow/runtime/second_factor_step.py): - claim the step for this run before asking (a retry or loop never asks or types again); - bind the focused element, which must be an empty autocomplete="one-time-code" input, and make the page draw it as dots (openadapt_flow/backends/one_time_field.py), so no screenshot, gate frame, transition frame or model image shows the code; - ask the source, with the deadline checked again when the answer arrives, for every source; - re-check, just before typing, that the same element still has focus, is empty and is masked; - type once through the bound element handle, never retried; - read back the length only, and halt as second_factor_unverified when it does not match. The step is now its own action, ActionKind.SECOND_FACTOR, with one_time naming code or approval. An older runtime refuses the bundle (checked against origin/main's ir.py for both kinds) instead of skipping an approval or typing an environment value. The step validator refuses any field outside a short allow-list, so an API binding, effects, an anchor, text or a param cannot route around the person. Also: - the compile agent's page listing withholds the value of one-time-code and password fields; - a code-only form's submit counts as a sign-in only right after a username-and-password sign-in; - normalize_code refuses an answer with an internal line break; - source_env forwards the run token only with the control-plane URL; - _call_skill passes the current stderr to the MCP stdio client, whose default can be a stream closed since mcp was imported (the cause of the order-dependent cached_tool_result failure in the wrap e2e); - the changelog entry moves under Unreleased, the ir schema snapshot is regenerated, and replayer.py's budget is lowered to 19219. --- CAPABILITIES.md | 2 +- llms-full.txt | 14 +- packages/flow/CHANGELOG.md | 36 +- packages/flow/docs/SECOND_FACTOR.md | 126 ++++-- packages/flow/docs/design/DECOMPOSITION.md | 2 +- .../flow/openadapt_flow/action_evidence.py | 9 +- .../openadapt_flow/backends/one_time_field.py | 224 ++++++++++ .../openadapt_flow/compile_agent/observe.py | 6 +- .../flow/openadapt_flow/compiler/codegen.py | 2 + .../flow/openadapt_flow/compiler/compile.py | 72 +-- .../flow/openadapt_flow/compiler/induction.py | 1 + packages/flow/openadapt_flow/emit/skill.py | 4 + .../flow/openadapt_flow/execution_profiles.py | 17 +- .../integrations/agents/skills.py | 5 +- packages/flow/openadapt_flow/interop/types.py | 14 +- packages/flow/openadapt_flow/ir.py | 16 +- packages/flow/openadapt_flow/recorder.py | 25 +- .../flow/openadapt_flow/runtime/replayer.py | 15 +- .../runtime/second_factor_step.py | 289 +++++++++++++ packages/flow/openadapt_flow/second_factor.py | 222 +++++++--- .../tests/e2e/test_wrap_second_factor_e2e.py | 6 +- .../schema_surface/openadapt_flow.ir.json | 126 +++++- packages/flow/tests/test_interop_types.py | 1 + packages/flow/tests/test_risk.py | 5 + packages/flow/tests/test_second_factor.py | 409 ++++++++++++++++-- .../flow/tests/test_second_factor_browser.py | 146 +++++++ 26 files changed, 1546 insertions(+), 248 deletions(-) create mode 100644 packages/flow/openadapt_flow/backends/one_time_field.py create mode 100644 packages/flow/openadapt_flow/runtime/second_factor_step.py create mode 100644 packages/flow/tests/test_second_factor_browser.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 445b45754d..a849420508 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -321,7 +321,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 (draft), 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 | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | 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 step marked `one_time` (`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; the code is typed once and never stored, logged or put in a report, and frames are blacked out. No source, no answer in time, a decline or a malformed answer stops the step before typing with a closed `second_factor_*` code. 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 | 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; unit tests for both sources, the sealing format and every refusal). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, [SECOND_FACTOR.md](packages/flow/docs/SECOND_FACTOR.md), `packages/flow/tests/test_second_factor.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 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 typed once through that element, 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` | | 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 | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `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 962f814a1c..79511dd2f5 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -761,7 +761,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 (draft), 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 | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | 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 step marked `one_time` (`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; the code is typed once and never stored, logged or put in a report, and frames are blacked out. No source, no answer in time, a decline or a malformed answer stops the step before typing with a closed `second_factor_*` code. 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 | 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; unit tests for both sources, the sealing format and every refusal). The hosted dashboard answer is in openadapt-cloud | `openadapt_flow.second_factor`, [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/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 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 typed once through that element, 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` | | 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 | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GUARD_AN_AGENT.md) | @@ -2392,18 +2392,6 @@ automation into an independently certified transaction system. ### Features -- A sign-in that asks for a second factor (a code by text message or email, - an authenticator code, or a push approval) no longer has to stop the - program. A step can carry `one_time` (`code` or `approval`). When it runs, - the run waits for a person through the configured source - (`OPENADAPT_SECOND_FACTOR_URL` for a hosted or customer-run runner's control - plane, or a local `OPENADAPT_SECOND_FACTOR_COMMAND`), types the code once - and keeps it nowhere. No source, no answer within the timeout, a decline or - a malformed answer stops the step before typing, with a closed - `second_factor_*` code. Over the control plane the code is sealed in the - person's browser to a one-step P-256 key. The wrap recorder turns a field - marked `autocomplete="one-time-code"` into such a step, and a code-only - form's submit counts as a sign-in, not a save. See docs/SECOND_FACTOR.md. - Dropdowns, searchable selects, type-aheads and native selects are recorded, compiled and run as one model, a choice (`OptionChoice` on a `SELECT_OPTION` step, docs/CHOICES.md). A click on an option of a list the diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 263fbd7dc7..8f671f394b 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -15,22 +15,36 @@ -## v3.4.0 (2026-11-21) +## Unreleased ### Features - A sign-in that asks for a second factor (a code by text message or email, an authenticator code, or a push approval) no longer has to stop the - program. A step can carry `one_time` (`code` or `approval`). When it runs, - the run waits for a person through the configured source - (`OPENADAPT_SECOND_FACTOR_URL` for a hosted or customer-run runner's control - plane, or a local `OPENADAPT_SECOND_FACTOR_COMMAND`), types the code once - and keeps it nowhere. No source, no answer within the timeout, a decline or - a malformed answer stops the step before typing, with a closed - `second_factor_*` code. Over the control plane the code is sealed in the - person's browser to a one-step P-256 key. The wrap recorder turns a field - marked `autocomplete="one-time-code"` into such a step, and a code-only - form's submit counts as a sign-in, not a save. See docs/SECOND_FACTOR.md. + program. A `second_factor` step (`one_time` is `code` or `approval`) waits + for a person through the configured source (`OPENADAPT_SECOND_FACTOR_URL` + for a hosted or customer-run runner's control plane, or a local + `OPENADAPT_SECOND_FACTOR_COMMAND`). Before anyone is asked, the focused + field must be an empty `autocomplete="one-time-code"` input, and the page + is made to draw it as dots. After the answer the same field must still have + focus and be empty. The code is then typed once through that element, never + retried, and kept nowhere: not in a model's page listing, a screenshot, a + log, a receipt or the recording. No source, an answer after the deadline, a + decline, a multi-line or malformed answer, a field that changed while the + person answered, an API binding on the step, or a backend that can't bind + the field stops the step before typing, with a closed `second_factor_*` + code. The action is new, so an older runtime refuses the bundle instead of + skipping an approval. Over the control plane the code is sealed in the + person's browser to a one-step P-256 key, and a cached run's child process + gets the run token only with the control-plane URL. The wrap recorder turns + a field marked `autocomplete="one-time-code"` into such a step. A code-only + form's submit counts as a sign-in only right after a username-and-password + sign-in. See docs/SECOND_FACTOR.md. + +## v3.4.0 (2026-11-21) + +### Features + - Dropdowns, searchable selects, type-aheads and native selects are recorded, compiled and run as one model, a choice (`OptionChoice` on a `SELECT_OPTION` step, docs/CHOICES.md). A click on an option of a list the diff --git a/packages/flow/docs/SECOND_FACTOR.md b/packages/flow/docs/SECOND_FACTOR.md index 839c414696..90f0d4b919 100644 --- a/packages/flow/docs/SECOND_FACTOR.md +++ b/packages/flow/docs/SECOND_FACTOR.md @@ -7,46 +7,86 @@ Instead the run waits at that step, a person supplies the code or approves the sign-in, and the run continues. If no one answers in time, the run stops before it types anything into the code field. -The code is used once. It is never written to the program, the recording, the -run report, the receipt or a log. +The code is typed once. It is never written to the program, the recording, +the run report, the receipt or a log, never shown to a model, and never drawn +on screen. ## In the program -A step can carry `one_time` (`openadapt_flow.ir.Step.one_time`): +A second factor is its own action, `second_factor` +(`openadapt_flow.ir.ActionKind.SECOND_FACTOR`), and `Step.one_time` names +its kind: -| Value | Step | What the run does | -| --- | --- | --- | -| `code` | A secret `TYPE` step whose param is `one_time_code` and that has no text | Asks the configured source for one code when the step runs, types it, and drops it | -| `approval` | A `WAIT` step with no input | Asks a person to approve the sign-in on their own device, and continues when they say they did. The next step still checks the screen | - -`one_time_code` is not a task input, a call parameter or a secret parameter. -No API call, params file or vault set supplies it, and the hosted parameter -schema doesn't list it. Steps without `one_time` serialize exactly as before. - -Replay saves black frames for a program with a one-time step, as it does for -a program with secret parameters. The checks still use the original pixels in -memory. - -A runtime older than this field ignores it, finds no -`OPENADAPT_FLOW_SECRET_ONE_TIME_CODE`, and stops at the code step before -typing. An older runtime given an `approval` step waits only for the page to -settle, then halts at the next step if the sign-in didn't finish. +| `one_time` | What the run does | +| --- | --- | +| `code` | Binds the focused code field, asks the configured source for one code, re-checks the field, types the code once into it, and drops the code | +| `approval` | Asks a person to approve the sign-in on their own device, and continues when they say they did. The next step still checks the screen | + +A `second_factor` step sets nothing else that could carry input or route +around the person: no anchor, text, param, secret flag, key, API binding, +effects or dialog response. The step validator refuses any field outside a +short allow-list, so a field added to `Step` later is refused by default. +The code is not a task input, a call parameter or a secret parameter. No API +call, params file or vault set supplies it, and the hosted parameter schema +doesn't list it. Other steps serialize exactly as before. + +A runtime older than this action doesn't know `second_factor`, so it refuses +to load the bundle. It can't skip an approval or type an environment value +into a code field. + +## How a code is typed + +The same handoff (`openadapt_flow.runtime.second_factor_step`) runs during +recording and replay: + +1. **Claim.** The step is claimed for this run before anyone is asked. A + retry, a loop back to the same state or a second call is refused without + asking again. +2. **Bind.** The focused element must be an `input` whose `autocomplete` + names `one-time-code`, and it must be empty. The page is made to draw + every such field as dots (`-webkit-text-security`), on the element and in + a stylesheet every later document in the browser context gets. The field + must report that it is masked. A backend that can't establish all of this + refuses; today that is every backend except the local browser. +3. **Ask.** The configured source is asked. Its deadline is checked again + when the answer arrives, so a late answer is dropped. +4. **Re-check.** Immediately before typing, the same element must still have + focus, be empty and be masked. A dialog that took focus, a field that was + filled or replaced, or a lost binding refuses, and the code is dropped + untyped. +5. **Type once.** The code is typed through the bound element, not the page + keyboard. It is never typed again. +6. **Read back.** The field must hold as many characters as the code. A page + that submits itself and removes the field counts as delivered, and the + next step checks the screen. Any other result stops the run with + `second_factor_unverified`. The code is not typed again. + +Every screenshot taken after step 2 (a recorded frame, a model-facing +screenshot, a gate check, a visual transition) shows dots, not the code. +Replay also saves black frames for a program with a second-factor step, as +it does for a program with secret parameters. A program that keeps exact +frames for a visual transition guard refuses a code step before asking. The +compile agent's page listing never includes a one-time-code or password +field's value. ## Recording it During `openadapt wrap`'s first run the recorder checks each field the agent types into, using only the page's markup. A field whose `autocomplete` names `one-time-code` is a code field. The agent never has the code. It is told to -type `⟦one-time-code⟧` there. The recorder discards that text, gets a code -from the configured source and types it instead. The recording keeps -`one_time: "code"` and the param name, and blacks out the field in every -frame that shows it. +type `⟦one-time-code⟧` there. The recorder discards that text and runs the +handoff above. The recording keeps `one_time: "code"` and a param name, and +blacks out the field in every frame that shows it. The compiler turns that +event into a `second_factor` step. A declared task input typed into a code field is refused, and so is `⟦one-time-code⟧` typed into any other field. Nothing is typed in either case. -The submit button of a form that holds only a code (or a username, password -and code together) signs in. It isn't classified as a save. +The submit button of a form that holds a username, a password and a code +signs in, and so does the submit of a form that holds only a code right after +a username-and-password sign-in. Neither is classified as a save. A form that +holds only a code anywhere else (a "Verify" button that confirms a payment) +keeps the normal submit escalation. The recorder doesn't detect push approvals yet. An `approval` step has to be added to the program by hand. @@ -66,8 +106,10 @@ first match wins. stderr every 20 seconds, so a supervisor that ends silent runs doesn't end one that is waiting for a person. -A cached `openadapt wrap` run passes these variables, and `OPENADAPT_RUNNER_TOKEN` when it is set, to the program's -MCP server. +A cached `openadapt wrap` run passes the selected source's variables to the +program's MCP server. `OPENADAPT_RUNNER_TOKEN` goes only with +`OPENADAPT_SECOND_FACTOR_URL`, never with a command source or a run with no +source. ### The control-plane protocol @@ -77,7 +119,8 @@ MCP server. `{"schema": "openadapt.second-factor-request/v1", "kind", "step_id", "public_key", "timeout_s"}`. The public key is an uncompressed point in base64url. The answer is `201 {"request_id"}`. -3. It polls `GET /` every 2 seconds. The answer is +3. It polls `GET /` every 2 seconds, and checks the deadline + before each poll and again when the poll returns. The answer is `{"state"}`, one of `pending`, `answered`, `approved`, `declined`, `expired` or `consumed`. An `answered` state also carries `"sealed": {"epk", "iv", "ciphertext"}`. @@ -92,23 +135,34 @@ non-200 answer stops the step. ## Why a step stops -Every stop happens before anything is typed into the code field. The step's -result is a governed refusal, and its error starts with one of these codes: +The step's result is a governed refusal (a safety halt for +`second_factor_unverified`), and its error starts with one of these codes. +All but the last stop before anything is typed into the code field. | Code | Meaning | | --- | --- | -| `second_factor_unavailable` | No source is set, the source isn't reachable, or the control plane refused the request | -| `second_factor_timeout` | No one answered within the timeout | +| `second_factor_unavailable` | No source is set, the source isn't reachable, the control plane refused the request, or the program keeps exact frames for a visual transition | +| `second_factor_timeout` | No one answered within the timeout, or the answer arrived after it | | `second_factor_declined` | The person declined | -| `second_factor_invalid` | The answer wasn't 4 to 16 letters or digits (spaces and hyphens are dropped), couldn't be opened, or answered a different kind of request | +| `second_factor_invalid` | The answer wasn't one line of 4 to 16 letters or digits (spaces and hyphens between groups are dropped), couldn't be opened, answered a different kind of request, or the step already asked in this run | +| `second_factor_unbound` | The backend can't bind the field, or the field wasn't an empty, masked one-time-code input with focus before the wait or just before typing | +| `second_factor_unverified` | The code was typed once, and the field doesn't hold the code's length. It is not typed again | A wrong code that the app rejects isn't retried. The next step finds the code page still showing and halts there. ## Tests -- `tests/test_second_factor.py`: both sources, every refusal, the sealing - format, the step shape, replay with and without a source, and recording. +- `tests/test_second_factor.py`: both sources, every refusal, late answers, + multi-line answers, the sealing format, the step shape and the older-runtime + 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_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 + field are refused; a page that submits itself gets the code once; the + agent's page listing never holds the code. - `tests/e2e/test_wrap_second_factor_e2e.py`: headless Chromium and a synthetic notes app with an authenticator page, through the real wrap path (first run, canary, admission, publish staging, a cached run and a declined diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index de7fb38059..cdf39dc437 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -607,7 +607,7 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh | File | Line budget | |---|---:| -| `packages/flow/openadapt_flow/runtime/replayer.py` | 19224 | +| `packages/flow/openadapt_flow/runtime/replayer.py` | 19219 | | `packages/flow/openadapt_flow/__main__.py` | 14331 | | `packages/flow/openadapt_flow/qualification/__init__.py` | 4891 | | `packages/flow/openadapt_flow/ir.py` | 6830 | diff --git a/packages/flow/openadapt_flow/action_evidence.py b/packages/flow/openadapt_flow/action_evidence.py index d21950bd86..7e50ecd264 100644 --- a/packages/flow/openadapt_flow/action_evidence.py +++ b/packages/flow/openadapt_flow/action_evidence.py @@ -434,7 +434,11 @@ def action_evidence_error( return f"drag endpoint: {error}" elif result.drag_end_resolution is not None: return "non-drag action contains a drag endpoint resolution" - if step.action in {ActionKind.TYPE, ActionKind.SELECT_OPTION}: + if step.action in { + ActionKind.TYPE, + ActionKind.SELECT_OPTION, + ActionKind.SECOND_FACTOR, + }: if strict_production and result.input_verified is not True: return "GUI input action lacks exact readback verification" if result.input_verified not in {None, True}: @@ -446,7 +450,8 @@ def action_evidence_error( if receipt_error is not None: return receipt_error elif ( - step.action in (ActionKind.WAIT, ActionKind.SWITCH_SURFACE) + step.action + in (ActionKind.WAIT, ActionKind.SWITCH_SURFACE, ActionKind.SECOND_FACTOR) and actuation is None ): if result.delivery_attempted not in {None, False}: diff --git a/packages/flow/openadapt_flow/backends/one_time_field.py b/packages/flow/openadapt_flow/backends/one_time_field.py new file mode 100644 index 0000000000..a64b5a8b7f --- /dev/null +++ b/packages/flow/openadapt_flow/backends/one_time_field.py @@ -0,0 +1,224 @@ +"""Bind a one-time code to its field in a browser page, and hide it there. + +:class:`PlaywrightOneTimeField` is the browser side of +:mod:`openadapt_flow.runtime.second_factor_step`. It never reads a field's +value, only its length: + +- :meth:`~PlaywrightOneTimeField.bind` takes the focused element, requires it + to be an ``autocomplete="one-time-code"`` input, and remembers that exact + element under a fresh nonce in its own window. +- The field is masked in the page itself (``-webkit-text-security``) before + any code reaches it, on the element and in a stylesheet that every new + document in the context gets. A screenshot taken afterwards, by the + recorder, a model-facing harness, a gate or a transition check, shows dots, + never the code. +- :meth:`~PlaywrightOneTimeField.type_once` types through the bound element + handle, not the page keyboard, so the code goes to that element even if a + dialog took focus meanwhile. +""" + +from __future__ import annotations + +import secrets +from typing import Any, Optional + +__all__ = ["MASK_CSS", "PlaywrightOneTimeField", "one_time_field_for"] + +#: Masks every one-time-code input in a document. +MASK_CSS = ( + 'input[autocomplete~="one-time-code" i] { -webkit-text-security: disc !important; }' +) + +#: Installed in every new document of the context (and its frames). +_MASK_INIT_JS = ( + "(() => { const add = () => { if (document.getElementById(" + "'__openadapt_one_time_mask')) return; const s = document.createElement(" + "'style'); s.id = '__openadapt_one_time_mask'; s.textContent = " + + repr(MASK_CSS) + + "; (document.head || document.documentElement).appendChild(s); };" + " if (document.documentElement) add();" + " else document.addEventListener('DOMContentLoaded', add); })();" +) + +_SLOT = "__openadaptOneTimeField" + +#: The state of an element: whether it is a one-time-code input, whether it +#: is empty, whether it renders masked, and its value's length. Never the +#: value itself. +_STATE_JS = r""" +const oaState = (el) => { + if (!el || el.tagName !== 'INPUT') return {kind: 'none'}; + const tokens = (el.getAttribute('autocomplete') || '').toLowerCase() + .split(/\s+/); + const style = el.ownerDocument.defaultView.getComputedStyle(el); + const security = style.getPropertyValue('-webkit-text-security') || + style.webkitTextSecurity || ''; + return { + kind: tokens.includes('one-time-code') ? 'one-time-code' : 'other', + empty: el.value === '', + length: el.value.length, + masked: ['disc', 'circle', 'square'].includes(security), + connected: el.isConnected, + }; +}; +""" + +_BIND_JS = ( + "([el, nonce, slot]) => {" + + _STATE_JS + + r""" + while (el && el.shadowRoot && el.shadowRoot.activeElement) { + el = el.shadowRoot.activeElement; + } + const state = oaState(el); + if (state.kind !== 'one-time-code') return state; + el.style.setProperty('-webkit-text-security', 'disc', 'important'); + el.ownerDocument.defaultView[slot] = {nonce: nonce, el: el}; + return oaState(el); +}""" +) + +#: The bound element's state, and whether it still has focus. +_CHECK_JS = ( + "([nonce, slot]) => {" + + _STATE_JS + + r""" + const held = window[slot]; + // A new document (the page submitted itself) holds no binding. + if (!held || held.nonce !== nonce) return {kind: 'gone', connected: false}; + const el = held.el; + let active = document.activeElement; + while (active && active.shadowRoot && active.shadowRoot.activeElement) { + active = active.shadowRoot.activeElement; + } + return Object.assign(oaState(el), {focused: active === el}); +}""" +) + +_HANDLE_JS = ( + "([nonce, slot]) => { const held = window[slot];" + " return held && held.nonce === nonce ? held.el : null; }" +) + + +class PlaywrightOneTimeField: + """The :class:`~openadapt_flow.runtime.second_factor_step.FieldBinding` + of a :class:`~openadapt_flow.backends.playwright_backend.PlaywrightBackend`. + + Every read returns None on any failure, which the handoff treats as not + checked, so it refuses. + """ + + def __init__(self, backend: Any) -> None: + self._backend = backend + self._nonce = secrets.token_hex(16) + self._frame: Any = None + + # -- masking ------------------------------------------------------------ + + def mask(self) -> None: + """Mask one-time-code inputs in this page and every later document.""" + + page = self._backend.page + if not getattr(self._backend, "_one_time_mask_installed", False): + page.context.add_init_script(script=_MASK_INIT_JS) + self._backend._one_time_mask_installed = True + for frame in page.frames: + try: + frame.evaluate(_MASK_INIT_JS) + except Exception: # noqa: BLE001 - the bound field is re-checked + continue + + # -- binding ------------------------------------------------------------ + + def bind(self) -> Optional[dict[str, Any]]: + """Bind the focused element and return its state, or None.""" + + state = self._backend._focused_element_call( + "(el, arg) => (" + _BIND_JS + ")([el, arg.nonce, arg.slot])", + arg={"nonce": self._nonce, "slot": _SLOT}, + with_arg=True, + ) + if not isinstance(state, dict): + return None + if state.get("kind") == "one-time-code": + self._frame = self._find_frame() + if self._frame is None: + return None + return state + + def check(self) -> Optional[dict[str, Any]]: + """The bound element's state now, with ``focused``; None if unread. + + A frame mid-navigation is read again once its load settles. + """ + + if self._frame is None: + return None + for attempt in range(2): + try: + state = self._frame.evaluate(_CHECK_JS, [self._nonce, _SLOT]) + except Exception: # noqa: BLE001 - not checked, so refused + if attempt: + return None + try: + self._frame.wait_for_load_state(timeout=5000) + except Exception: # noqa: BLE001 - the second read decides + pass + continue + return state if isinstance(state, dict) else None + return None + + def type_once(self, code: str) -> None: + """Type ``code`` through the bound element handle, once.""" + + handle = self._frame.evaluate_handle(_HANDLE_JS, [self._nonce, _SLOT]) + element = handle.as_element() + if element is None: + raise RuntimeError("the bound one-time-code field is gone") + self._backend._assert_qualification_environment_current() + element.type(code) + + def _find_frame(self) -> Any: + """The one frame whose window holds this binding's nonce.""" + + found = [] + for frame in self._backend.page.frames: + try: + held = frame.evaluate( + "([n, s]) => !!window[s] && window[s].nonce === n", + [self._nonce, _SLOT], + ) + except Exception: # noqa: BLE001 - a frame we cannot read + continue + if held is True: + found.append(frame) + return found[0] if len(found) == 1 else None + + +def one_time_field_for(backend: Any) -> Any: + """The field binding for ``backend``, or None when it cannot bind one. + + A local browser backend can establish which element a code goes to, that + it is empty and that it renders masked. Another backend opts in by + offering ``one_time_field()``, returning its own binding; every other + backend refuses a second-factor code step. + """ + + seam = getattr(backend, "one_time_field", None) + if callable(seam): + try: + return seam() + except Exception: # noqa: BLE001 - no binding, so refused + return None + try: + from openadapt_flow.backends.playwright_backend import PlaywrightBackend + except Exception: # noqa: BLE001 - no browser extra installed + return None + if type(backend) is not PlaywrightBackend and not isinstance( + backend, PlaywrightBackend + ): + return None + if getattr(backend, "page", None) is None: + return None + return PlaywrightOneTimeField(backend) diff --git a/packages/flow/openadapt_flow/compile_agent/observe.py b/packages/flow/openadapt_flow/compile_agent/observe.py index 196bc05bc8..2ba0a8b0b6 100644 --- a/packages/flow/openadapt_flow/compile_agent/observe.py +++ b/packages/flow/openadapt_flow/compile_agent/observe.py @@ -159,7 +159,11 @@ var r = el.getBoundingClientRect(); var value = null; if (tag === 'input' || tag === 'textarea' || tag === 'select') { - value = el.type === 'password' ? '' : String(el.value || ''); + // A password or a one-time sign-in code never enters the listing. + var secret = el.type === 'password' || + /(^|\\s)(one-time-code|current-password|new-password)(\\s|$)/i + .test(el.getAttribute('autocomplete') || ''); + value = secret ? '' : String(el.value || ''); } var cls = (el.className && el.className.baseVal === undefined) ? String(el.className) : ''; diff --git a/packages/flow/openadapt_flow/compiler/codegen.py b/packages/flow/openadapt_flow/compiler/codegen.py index 073db8edf0..9c339c9eac 100644 --- a/packages/flow/openadapt_flow/compiler/codegen.py +++ b/packages/flow/openadapt_flow/compiler/codegen.py @@ -117,6 +117,8 @@ def _step_call(step: Step) -> str: ) if step.action is ActionKind.SWITCH_SURFACE: return f" flow.switch_surface({step.surface!r})" + if step.action is ActionKind.SECOND_FACTOR: + return f" flow.second_factor({step.one_time!r}) # from a person" raise ValueError(f"unknown action {step.action!r}") diff --git a/packages/flow/openadapt_flow/compiler/compile.py b/packages/flow/openadapt_flow/compiler/compile.py index b3aee8d2ea..f1dbd24f87 100644 --- a/packages/flow/openadapt_flow/compiler/compile.py +++ b/packages/flow/openadapt_flow/compiler/compile.py @@ -3442,15 +3442,7 @@ def cached_lines(i: int, suffix: str, png: bytes) -> list[OcrLine]: int(raw_rect[3]), ), ) - one_time: Optional[Literal["code"]] = ( - "code" if secret and event.get("one_time") == "code" else None - ) - if one_time: - # A sign-in's one-time code: a person supplies it when the - # step runs (openadapt_flow.second_factor). - text = None - intent = "type the one-time sign-in code" - elif secret: + if secret: # A secret's literal value is never in the recording, so it # is never in the bundle either: the step carries only the # param name, and the value is injected from the environment @@ -3461,23 +3453,27 @@ def cached_lines(i: int, suffix: str, png: bytes) -> list[OcrLine]: intent = f"type <{param}>" else: intent = f"type '{_text_preview(text or '')}'" - pending.append( - ( - Step( - id=step_id, - intent=intent, - action=ActionKind.TYPE, - text=text, - param=param, - secret=secret, - one_time=one_time, - field_label=field_label, - ), - before_png, - after_png, - event, - ) + typed = Step( + id=step_id, + intent=intent, + action=ActionKind.TYPE, + text=text, + param=param, + secret=secret, + field_label=field_label, ) + if secret and event.get("one_time") == "code": + # A sign-in's one-time code: a person supplies it when the + # step runs, into the field the previous click focused + # (openadapt_flow.runtime.second_factor_step). + typed = Step( + id=step_id, + intent="type the one-time sign-in code", + action=ActionKind.SECOND_FACTOR, + one_time="code", + field_label=field_label, + ) + pending.append((typed, before_png, after_png, event)) elif kind == "key": key = event["key"] pending.append( @@ -4695,18 +4691,26 @@ def _form_submit_steps( A sign-in is not a save: when the fields typed since the previous such click are exactly a username and a current password the recorder withheld (``credential_kinds``, from each secret TYPE event's ``credential``), its - submit button signs in and writes no record. So does a form holding only - a one-time sign-in code, or the three together. A lone password (a PIN or a - re-authentication), a ``new-password`` field (a password change or sign-up) - or any other typed field keeps the escalation, and the keyword risk - inference still classifies the button on its own label. + submit button signs in and writes no record. So does a form holding the + three with a one-time sign-in code. A form holding only a code signs in + only when the form submitted just before it was such a sign-in: on its + own, a code with a "Verify" button can confirm a payment or a transfer. + A lone password (a PIN or a re-authentication), a ``new-password`` field + (a password change or sign-up) or any other typed field keeps the + escalation, and the keyword risk inference still classifies the button + on its own label. """ kinds = credential_kinds or {} found: list[Step] = [] typed = False typed_kinds: list[Optional[str]] = [] + signed_in = False for step in steps: + if step.action is ActionKind.SECOND_FACTOR and step.one_time == "code": + typed = True + typed_kinds.append("one-time-code") + continue if step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION): typed = True typed_kinds.append(kinds.get(step.id) if step.secret else None) @@ -4718,7 +4722,10 @@ def _form_submit_steps( and step.action in (ActionKind.CLICK, ActionKind.DOUBLE_CLICK) and _is_form_save(raw) ): - if sorted(map(str, typed_kinds)) not in _SIGN_IN_FIELD_SETS: + fields = sorted(map(str, typed_kinds)) + follows_sign_in = fields == ["one-time-code"] and signed_in + signed_in = fields in _SIGN_IN_FIELD_SETS or follows_sign_in + if not signed_in: found.append(step) typed = False typed_kinds = [] @@ -4726,10 +4733,9 @@ def _form_submit_steps( #: Typed fields whose form submit signs in and saves nothing: a username and -#: current password, a one-time code (a second sign-in page), or all three. +#: current password, alone or with a one-time code on the same form. _SIGN_IN_FIELD_SETS = ( ["password", "username"], - ["one-time-code"], ["one-time-code", "password", "username"], ) diff --git a/packages/flow/openadapt_flow/compiler/induction.py b/packages/flow/openadapt_flow/compiler/induction.py index 866f111b6a..4aa1906985 100644 --- a/packages/flow/openadapt_flow/compiler/induction.py +++ b/packages/flow/openadapt_flow/compiler/induction.py @@ -864,6 +864,7 @@ def _navigation_only(step: Step) -> bool: ActionKind.TYPE, ActionKind.SELECT_OPTION, ActionKind.READ, + ActionKind.SECOND_FACTOR, ) and not _step_consequential(step) diff --git a/packages/flow/openadapt_flow/emit/skill.py b/packages/flow/openadapt_flow/emit/skill.py index d596c92903..a89111e7ce 100644 --- a/packages/flow/openadapt_flow/emit/skill.py +++ b/packages/flow/openadapt_flow/emit/skill.py @@ -133,6 +133,10 @@ def _step_line(step: Step, literals: list[str]) -> str: return f"scroll by ({step.scroll_dx or 0}, {step.scroll_dy or 0})" if action is ActionKind.SWITCH_SURFACE: return f"switch to surface '{step.surface}'" + if action is ActionKind.SECOND_FACTOR: + if step.one_time == "approval": + return "wait for a person to approve the sign-in on their device" + return "type a one-time sign-in code a person supplies" return action.value diff --git a/packages/flow/openadapt_flow/execution_profiles.py b/packages/flow/openadapt_flow/execution_profiles.py index ceeb706779..ade6ac5614 100644 --- a/packages/flow/openadapt_flow/execution_profiles.py +++ b/packages/flow/openadapt_flow/execution_profiles.py @@ -2031,10 +2031,13 @@ def _reported_parameter_predicate_value( is not None ): return ExecutionOutcome.COMPLETED_UNVERIFIED - # WAIT and SWITCH_SURFACE deliver no input: no actuation path, no - # delivery boundary. A switch is verified by its own identity check - # and postconditions (docs/MULTI_SURFACE.md). - if step.action in (ActionKind.WAIT, ActionKind.SWITCH_SURFACE): + # WAIT, SWITCH_SURFACE and a device approval deliver no input: no + # actuation path, no delivery boundary. A switch is verified by its + # own identity check and postconditions (docs/MULTI_SURFACE.md). + no_input = step.action in (ActionKind.WAIT, ActionKind.SWITCH_SURFACE) or ( + step.action is ActionKind.SECOND_FACTOR and step.one_time == "approval" + ) + if no_input: if result.actuation is not None: return ExecutionOutcome.COMPLETED_UNVERIFIED elif result.actuation is None: @@ -2057,8 +2060,7 @@ def _reported_parameter_predicate_value( effects = effects_for_actuation(step, result.actuation) automated_gui = result.actuation in AUTOMATED_GUI_ACTUATIONS or ( - result.actuation is None - and step.action not in (ActionKind.WAIT, ActionKind.SWITCH_SURFACE) + result.actuation is None and not no_input ) if api_actuation: # The API tier bypasses the GUI resolve/settle/act/postcondition @@ -2089,7 +2091,8 @@ def _reported_parameter_predicate_value( return ExecutionOutcome.COMPLETED_UNVERIFIED if ( automated_gui - and step.action in {ActionKind.TYPE, ActionKind.SELECT_OPTION} + and step.action + in {ActionKind.TYPE, ActionKind.SELECT_OPTION, ActionKind.SECOND_FACTOR} and result.input_verified is not True ): return ExecutionOutcome.COMPLETED_UNVERIFIED diff --git a/packages/flow/openadapt_flow/integrations/agents/skills.py b/packages/flow/openadapt_flow/integrations/agents/skills.py index 42e8650a0c..47f3d6cc64 100644 --- a/packages/flow/openadapt_flow/integrations/agents/skills.py +++ b/packages/flow/openadapt_flow/integrations/agents/skills.py @@ -1096,7 +1096,10 @@ async def _call_skill(python: str, server: Path, params: dict[str, Any]) -> dict # factor source (and its run token) is what the cached run needs too. env = {**get_default_environment(), **source_env()} target = StdioServerParameters(command=python, args=[str(server)], env=env) - async with stdio_client(target) as (read, write): + # The child's stderr goes to the stderr in use now. The client's default + # is the stream bound when mcp was first imported, which a host (or a + # test capture) may have closed since; spawning then fails. + async with stdio_client(target, errlog=sys.stderr) as (read, write): async with ClientSession(read, write) as session: await session.initialize() tools = (await session.list_tools()).tools diff --git a/packages/flow/openadapt_flow/interop/types.py b/packages/flow/openadapt_flow/interop/types.py index 734ae71771..6d70f560f5 100644 --- a/packages/flow/openadapt_flow/interop/types.py +++ b/packages/flow/openadapt_flow/interop/types.py @@ -112,10 +112,16 @@ class _ActionSchemaDefaults(TypedDict, total=False): # cross-package schema can carry its commit key and field evidence without # degrading it to TYPE. SWITCH_SURFACE is a flow-only control step (it moves # the replay between bound surfaces) with no canonical ActionType. READ stays -# outside it too: the shared schema has no typed field read. +# outside it too: the shared schema has no typed field read. SECOND_FACTOR +# (a person's sign-in code or approval) has no canonical ActionType either. # :func:`step_to_action` refuses these conversions loudly. _FLOW_ONLY_ACTION_KINDS = frozenset( - {ir.ActionKind.SELECT_OPTION, ir.ActionKind.SWITCH_SURFACE, ir.ActionKind.READ} + { + ir.ActionKind.SELECT_OPTION, + ir.ActionKind.SWITCH_SURFACE, + ir.ActionKind.READ, + ir.ActionKind.SECOND_FACTOR, + } ) ACTION_KIND_TO_ACTION_TYPE: dict[ir.ActionKind, str] = { kind: kind.value for kind in ir.ActionKind if kind not in _FLOW_ONLY_ACTION_KINDS @@ -192,6 +198,10 @@ def step_to_action(step: ir.Step) -> "Action": "SWITCH_SURFACE is a flow-only control step with no openadapt-types " "ActionType" ) + if step.action is ir.ActionKind.SECOND_FACTOR: + raise ValueError( + "SECOND_FACTOR is a flow-only step with no openadapt-types ActionType" + ) action_type = ActionType(ACTION_KIND_TO_ACTION_TYPE[step.action]) # Target: canonical coordinates come from the anchor's click point. The diff --git a/packages/flow/openadapt_flow/ir.py b/packages/flow/openadapt_flow/ir.py index f83bf0fe3a..d409c0f187 100644 --- a/packages/flow/openadapt_flow/ir.py +++ b/packages/flow/openadapt_flow/ir.py @@ -59,13 +59,7 @@ validate_authoring_model_json, ) from openadapt_flow.qualification_faults import FaultMutationReceipt -from openadapt_flow.records.schema import ( - FieldRead, - FieldSpec, - GradeGate, - ReadProof, -) -from openadapt_flow.second_factor import check_step_shape as _check_one_time_shape +from openadapt_flow.records.schema import FieldRead, FieldSpec, GradeGate, ReadProof if TYPE_CHECKING: # Type-only import for the Step.effects forward reference. The RUNTIME @@ -127,6 +121,7 @@ class ActionKind(str, Enum): # does not know the value, refuses the whole bundle instead of driving the # wrong window (docs/MULTI_SURFACE.md). SWITCH_SURFACE = "switch_surface" + SECOND_FACTOR = "second_factor" # a person's sign-in code (second_factor.py) class Landmark(BaseModel): @@ -2366,7 +2361,6 @@ class Step(BaseModel): ), ) one_time: Optional[Literal["code", "approval"]] = None # second_factor.py - _validate_one_time = model_validator(mode="after")(_check_one_time_shape) native_selection: Optional[NativeSelectContract] = None choice: Optional[OptionChoice] = Field( default=None, @@ -2581,6 +2575,12 @@ def _serialize_compatible(self, handler: Any) -> dict[str, Any]: data.pop(key, None) return data + @model_validator(mode="after") + def _validate_one_time(self) -> "Step": + from openadapt_flow.second_factor import check_step_shape + + return check_step_shape(self) + @model_validator(mode="after") def _validate_target_param(self) -> "Step": if self.target_param is None: diff --git a/packages/flow/openadapt_flow/recorder.py b/packages/flow/openadapt_flow/recorder.py index 13dbcf3aca..25771d7386 100644 --- a/packages/flow/openadapt_flow/recorder.py +++ b/packages/flow/openadapt_flow/recorder.py @@ -468,21 +468,19 @@ def _type_one_time_code( The agent's text is discarded (it never has the code), unless it is a declared input, which is refused: a code field takes only a code. The - event names :data:`ONE_TIME_CODE_PARAM` and holds no value. + handoff (:mod:`openadapt_flow.runtime.second_factor_step`) binds the + field, masks it on screen, asks, re-checks and types once. The event + names :data:`ONE_TIME_CODE_PARAM` and holds no value. """ from openadapt_flow import second_factor + from openadapt_flow.backends.one_time_field import one_time_field_for + from openadapt_flow.runtime.second_factor_step import DeliveryLedger, Handoff if text in (self._credential_inputs or {}): raise CredentialFieldError( "a one-time code field takes only a code from a person, not a " "declared input; nothing was typed" ) - try: - code = second_factor.obtain("code", "recording") or "" - except second_factor.SecondFactorRefused as refused: - raise CredentialFieldError( - f"a one-time code field needs a code from a person ({refused})" - ) from None event.pop("text", None) event.update( param=ONE_TIME_CODE_PARAM, @@ -493,7 +491,18 @@ def _type_one_time_code( ) self._credential_fields.append((self._active_surface, "one-time-code", region)) self.last_type_withheld = True - self._record(event, lambda: self._backend.type_text(code)) + ledger = self.__dict__.setdefault("_second_factor_ledger", DeliveryLedger()) + handoff = Handoff(one_time_field_for(self._backend), ledger) + + def deliver() -> None: + try: + handoff.deliver_code("recording", key=f"recording:{self._i}") + except second_factor.SecondFactorRefused as refused: + raise CredentialFieldError( + f"a one-time code field needs a code from a person ({refused})" + ) from None + + self._record(event, deliver) def press(self, key: str) -> None: """Press a key or chord (e.g. ``'Enter'``), recording the event.""" diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index b675cf97c4..ec6974956c 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -188,6 +188,7 @@ from openadapt_flow.runtime import identity_census as census_mod from openadapt_flow.runtime import identity_looks as looks_mod from openadapt_flow.runtime import keyboard_delivery as keyboard_delivery_mod +from openadapt_flow.runtime import second_factor_step from openadapt_flow.runtime.authorization import ( GovernedRunAuthorization, RuntimeParamScalar, @@ -265,7 +266,6 @@ from openadapt_flow.runtime.step_timing import timed_span from openadapt_flow.runtime.surfaces import SurfaceRouter from openadapt_flow.runtime.typed_echo import read_typed_echo -from openadapt_flow.second_factor import runtime_value as _one_time_value from openadapt_flow.secret_inputs import ( # noqa: F401 - compatibility exports SECRET_ENV_PREFIX, require_secret_sources, @@ -12834,6 +12834,8 @@ def _act_without_dialog( before_png=before_png, result=result, ) + if step.action is ActionKind.SECOND_FACTOR: # bind, ask, type once + return second_factor_step.act(self, step, workflow, params, result) if step.action in (ActionKind.CLICK, ActionKind.DOUBLE_CLICK): assert resolution is not None # guaranteed by _resolve_step x, y = resolution.point @@ -13355,13 +13357,8 @@ def _act_without_dialog( if step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION): if step.secret: # never in the bundle/params (secret_inputs.py) - text, refusal = ( - _one_time_value(step, result) - if step.one_time == "code" # asked of a person now - else step_secret_text( - step, getattr(self, "secret_env_overrides", {}) - ) - ) + overrides = getattr(self, "secret_env_overrides", {}) + text, refusal = step_secret_text(step, overrides) if refusal is not None: return refusal elif step.param is not None: @@ -13797,8 +13794,6 @@ def _act_without_dialog( return None if step.action is ActionKind.WAIT: - if step.one_time == "approval": # a person approves on their device - return _one_time_value(step, result)[1] # WAIT means wait_settled only; the post-action settle handles it. return None diff --git a/packages/flow/openadapt_flow/runtime/second_factor_step.py b/packages/flow/openadapt_flow/runtime/second_factor_step.py new file mode 100644 index 0000000000..0fe4700ece --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/second_factor_step.py @@ -0,0 +1,289 @@ +"""Run a second-factor step: bind the field, ask a person, type once. + +One :class:`Handoff` serves the recorder and the replayer, so both follow the +same order and the same rules: + +1. **Claim.** The step's key is claimed in the run's :class:`DeliveryLedger` + before a person is asked. A key is claimed once per run, so a retry, a + loop back to the same state or a second call never asks again and never + types again. +2. **Bind.** The focused element must be an empty one-time-code input that + renders masked (:mod:`openadapt_flow.backends.one_time_field`). A backend + that cannot establish this refuses. +3. **Ask.** :func:`openadapt_flow.second_factor.obtain` waits for the person, + with its deadline checked again when the answer arrives. +4. **Re-check.** Immediately before typing, the same element must still be + focused, empty and masked. A dialog that took focus, a field that was + prefilled or replaced, or a lost binding refuses, and the code is dropped. +5. **Type once.** The code is typed through the bound element. It is never + typed again, whatever happens next. +6. **Read back.** The element must hold exactly the code's length (or have + left the page, which a code page that submits itself does). Anything else + stops the run as ``second_factor_unverified``; it is not retried. + +Each check has three outcomes, as in the shared verdict kernel +(``openadapt_flow.verdict``, #2476): only ``HELD`` proceeds; ``REFUTED`` and +``NOT_CHECKED`` refuse. When that kernel lands, :class:`Status` becomes an +alias of ``verdict.Status``. + +The code itself lives only in a :class:`~openadapt_flow.second_factor.OneTimeCode` +for the few calls between steps 3 and 5. No message, result field, log line, +event or receipt carries it. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from enum import Enum +from typing import TYPE_CHECKING, Any, Optional, Protocol + +from openadapt_flow.second_factor import OneTimeCode, SecondFactorRefused +from openadapt_flow.second_factor import obtain as obtain_second_factor + +if TYPE_CHECKING: + from openadapt_flow.ir import Step, Workflow + +__all__ = [ + "DeliveryLedger", + "FieldBinding", + "Handoff", + "Status", + "act", + "field_checks", +] + + +class Status(str, Enum): + """The three values a check can have (``openadapt_flow.verdict.Status``).""" + + HELD = "held" + REFUTED = "refuted" + NOT_CHECKED = "not_checked" + + +@dataclass(frozen=True) +class Check: + name: str + status: Status + + +class FieldBinding(Protocol): + """What a backend must offer to take a one-time code.""" + + def mask(self) -> None: ... + + def bind(self) -> Optional[Mapping[str, Any]]: ... + + def check(self) -> Optional[Mapping[str, Any]]: ... + + def type_once(self, code: str) -> None: ... + + +class DeliveryLedger: + """The step keys of one run that already asked for a code.""" + + def __init__(self) -> None: + self._claimed: set[str] = set() + + def claim(self, key: str) -> None: + if key in self._claimed: + raise SecondFactorRefused( + "second_factor_invalid", + "this step already asked for its second factor in this run; " + "it is never asked or typed twice", + ) + self._claimed.add(key) + + +def field_checks(state: Optional[Mapping[str, Any]], *, bound: bool) -> list[Check]: + """The checks a field must hold before a code is typed into it. + + ``bound`` adds that the bound element still has focus (step 4). + """ + + def held(name: str, ok: Callable[[Mapping[str, Any]], bool]) -> Check: + if not isinstance(state, Mapping): + return Check(name, Status.NOT_CHECKED) + try: + return Check(name, Status.HELD if ok(state) else Status.REFUTED) + except Exception: # noqa: BLE001 - an unreadable state is not checked + return Check(name, Status.NOT_CHECKED) + + checks = [ + held("one-time-code field", lambda s: s.get("kind") == "one-time-code"), + held("empty", lambda s: s.get("empty") is True and s.get("length") == 0), + held("masked", lambda s: s.get("masked") is True), + ] + if bound: + checks += [ + held("same element", lambda s: s.get("connected") is True), + held("still focused", lambda s: s.get("focused") is True), + ] + return checks + + +def _require(checks: list[Check], when: str) -> None: + failed = [check.name for check in checks if check.status is not Status.HELD] + if failed: + raise SecondFactorRefused( + "second_factor_unbound", + f"{when}, the code field did not hold: {', '.join(failed)}; " + "nothing was typed", + ) + + +class Handoff: + """One step's handoff. See the module docstring for the order.""" + + def __init__( + self, + field: Optional[FieldBinding], + ledger: DeliveryLedger, + *, + obtain: Callable[..., Any] = obtain_second_factor, + ) -> None: + self._field = field + self._ledger = ledger + self._obtain = obtain + + def approve(self, step_id: str, *, key: str) -> None: + """Wait for a person to approve the sign-in on their device.""" + + self._ledger.claim(key) + self._obtain("approval", step_id) + + def deliver_code( + self, + step_id: str, + *, + key: str, + deliver: Callable[[Callable[[], None]], Any] = lambda call: call(), + ) -> bool: + """Ask for one code and type it once into the bound field. + + ``deliver`` wraps the single typing call (the replayer's delivery + boundary). Returns True when the field reads back the code's length, + False when the page took the code and removed the field. Raises + :class:`SecondFactorRefused`; a refusal before typing drops the code + untyped. + """ + + self._ledger.claim(key) + field = self._field + if field is None: + raise SecondFactorRefused( + "second_factor_unbound", + "this backend cannot bind a code to its field, check that " + "the field is empty, or hide the code on screen; nothing was typed", + ) + try: + field.mask() + before = field.bind() + except Exception: # noqa: BLE001 - a failed bind is a refusal + before = None + _require(field_checks(before, bound=False), "before asking") + code = self._obtain("code", step_id) + if not isinstance(code, OneTimeCode): + raise SecondFactorRefused("second_factor_invalid", "no code came back") + try: + try: + now = field.check() + except Exception: # noqa: BLE001 - a failed read is not checked + now = None + _require(field_checks(now, bound=True), "after the person answered") + length = code.length + try: + deliver(lambda: field.type_once(code.consume())) + except Exception as exc: + raise SecondFactorRefused( + "second_factor_unverified", + f"typing the code raised {type(exc).__name__}; it is not " + "typed again", + ) from None + finally: + code.discard() + try: + after = field.check() + except Exception: # noqa: BLE001 - a failed read is inconclusive + after = None + if isinstance(after, Mapping) and after.get("connected") is False: + return False # the page took the code and moved on + if not ( + isinstance(after, Mapping) + and after.get("kind") == "one-time-code" + and after.get("length") == length + ): + raise SecondFactorRefused( + "second_factor_unverified", + "the code field does not hold the code's length after it was " + "typed once; it is not typed again", + ) + return True + + +# -- the replayer's step ------------------------------------------------------ + + +def _keeps_exact_frames(replayer: Any, workflow: "Workflow") -> bool: + """Whether the program retains raw frames for a visual transition guard.""" + + graphs = [workflow.program, *(workflow.subflows or {}).values()] + uses_frame = getattr(replayer, "_program_guard_uses_frame", None) + for graph in graphs: + for state in (getattr(graph, "states", None) or {}).values(): + for transition in getattr(state, "transitions", None) or (): + if not callable(uses_frame) or uses_frame(transition.guard): + return True + return False + + +def act( + replayer: Any, + step: "Step", + workflow: "Workflow", + params: Mapping[str, Any], + result: Any, +) -> Optional[str]: + """``Replayer._act_without_dialog`` for a ``second_factor`` step.""" + + from openadapt_flow.backends.one_time_field import one_time_field_for + + ledger = replayer.__dict__.setdefault("_second_factor_ledger", DeliveryLedger()) + try: + if step.one_time == "approval": + Handoff(None, ledger).approve(step.id, key=step.id) + return None + if _keeps_exact_frames(replayer, workflow): + raise SecondFactorRefused( + "second_factor_unavailable", + "this program keeps exact screen frames for a visual " + "transition, which a code could appear in; nothing was typed", + ) + refusal = replayer._delivery_authorization_refusal( + workflow, params, step, result + ) + if refusal is not None: + return str(refusal) + locale = replayer._require_locale_invariants_before_keyboard(workflow) + if locale is not None: + result.safety_halt = True + result.failure_category = "safety_halt" + return str(locale) + replayer._require_qualification_environment_current() + verified = Handoff(one_time_field_for(replayer.backend), ledger).deliver_code( + step.id, + key=step.id, + deliver=lambda call: replayer._deliver_backend_call(result, call), + ) + except SecondFactorRefused as refused: + if refused.code == "second_factor_unverified": + result.safety_halt = True + result.failure_category = "safety_halt" + else: + result.failure_category = "governed_refusal" + return f"Step '{step.id}' ({step.intent}) {refused}" + result.actuation = "dom" + if verified: + result.input_verified = True + return None diff --git a/packages/flow/openadapt_flow/second_factor.py b/packages/flow/openadapt_flow/second_factor.py index 29e8cb3194..e61b34c383 100644 --- a/packages/flow/openadapt_flow/second_factor.py +++ b/packages/flow/openadapt_flow/second_factor.py @@ -1,14 +1,17 @@ """Ask a person for a sign-in's second factor while the run waits. -A program step can declare ``Step.one_time``: - -- ``"code"``: a TYPE step into a one-time-code field (a code sent by SMS or - email, or shown by an authenticator app). The program never holds a value. - When the step runs, the configured source supplies one code; the runtime - types it and drops it. It is never stored, logged or written to a report. -- ``"approval"``: a WAIT step at a push-approval prompt. The source tells a - person to approve the sign-in on their own device, and the run continues - once they say they did. The next step still checks the screen. +A program step whose action is ``second_factor`` names its kind in +``Step.one_time``. The action is its own enum value so a runtime that predates +it refuses to load the bundle instead of running the step as something else: + +- ``"code"``: type one code into the focused one-time-code field (a code sent + by SMS or email, or shown by an authenticator app). The program never holds + a value. When the step runs, the configured source supplies one code; the + runtime types it once and drops it. It is never stored, logged, shown to a + model or written to a report (:mod:`openadapt_flow.runtime.second_factor_step`). +- ``"approval"``: wait at a push-approval prompt. The source tells a person to + approve the sign-in on their own device, and the run continues once they + say they did. The next step still checks the screen. Sources, from the environment, first match wins: @@ -22,9 +25,9 @@ `` code|approval `` with no shell. Exit 0 prints the code (or confirms the approval), exit 3 means the person declined. -With no source, or when the source fails, times out or declines, the step -stops before anything is typed, with one closed code from -:data:`REFUSAL_CODES`. +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 +code from :data:`REFUSAL_CODES`. """ from __future__ import annotations @@ -52,13 +55,14 @@ "URL_ENV", "CommandSource", "HttpSource", + "OneTimeCode", "SecondFactorRefused", "check_step_shape", + "delivers_input", "has_one_time_steps", "normalize_code", "obtain", "open_sealed_code", - "runtime_value", "source_env", "source_from_env", "timeout_from_env", @@ -70,16 +74,25 @@ TOKEN_ENV = "OPENADAPT_RUNNER_TOKEN" COMMAND_ENV = "OPENADAPT_SECOND_FACTOR_COMMAND" TIMEOUT_ENV = "OPENADAPT_SECOND_FACTOR_TIMEOUT_S" -#: What a run's child processes need for a source: its configuration and, -#: for the control plane, the run token that authorizes the request. +#: 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) def source_env(environ: Optional[Mapping[str, str]] = None) -> dict[str, str]: - """The set :data:`SOURCE_ENV_KEYS` of ``environ``, for a child process.""" + """What a run's child process needs for the selected source, and no more. + + The run token goes only with the control-plane URL that uses it; a command + source or an unconfigured run passes no token to the child. + """ environ = os.environ if environ is None else environ - return {key: environ[key] for key in SOURCE_ENV_KEYS if environ.get(key)} + keys = [TIMEOUT_ENV] + if (environ.get(URL_ENV) or "").strip(): + keys += [URL_ENV, TOKEN_ENV] + elif (environ.get(COMMAND_ENV) or "").strip(): + keys.append(COMMAND_ENV) + return {key: environ[key] for key in keys if environ.get(key)} #: How long a step waits for a person by default, and the bounds an @@ -93,15 +106,22 @@ def source_env(environ: Optional[Mapping[str, str]] = None) -> dict[str, str]: #: ends a silent run must not end one that is waiting for a person). HEARTBEAT_S = 20.0 +#: Closed refusal codes. All but ``second_factor_unverified`` stop before +#: anything is typed; that one stops after the single delivery when the field +#: does not read back the code's length (it is never typed again). REFUSAL_CODES = ( "second_factor_unavailable", "second_factor_timeout", "second_factor_declined", "second_factor_invalid", + "second_factor_unbound", + "second_factor_unverified", ) -#: The param a one-time code step names. It is not a task input or a secret -#: parameter, so no call and no vault supplies it. +#: The action value of a second-factor step (``ir.ActionKind.SECOND_FACTOR``). +ACTION = "second_factor" +#: The param a recorded one-time code event names. It is not a task input or +#: a secret parameter, so no call and no vault supplies it. ONE_TIME_CODE_PARAM = "one_time_code" #: What a capture agent types into a one-time-code field; the recorder #: discards it and types the code a person supplies. @@ -111,15 +131,19 @@ def source_env(environ: Optional[Mapping[str, str]] = None) -> dict[str, str]: SEAL_INFO = b"openadapt.second-factor/v1:" # Codes people get are short runs of digits or letters; some are shown in -# groups ("123 456", "ABC-123"). Spaces and hyphens are dropped. +# groups ("123 456", "ABC-123"). Spaces and hyphens between groups are +# dropped. A line break inside the answer is refused: two codes on two lines +# are not one longer code. _CODE = re.compile(r"[A-Za-z0-9]{4,16}\Z") +_GROUP_SEPARATORS = re.compile(r"[ \u00a0-]") +_LINE_BREAK = re.compile(r"[\r\n\v\f\x1c-\x1e\x85\u2028\u2029]") _STEP_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}\Z") _REQUEST_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]{7,63}\Z") _LOCAL_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"}) class SecondFactorRefused(RuntimeError): - """The step cannot get its second factor; nothing was typed. + """The step cannot get or deliver its second factor. ``code`` is one of :data:`REFUSAL_CODES`. The message never carries a code value or a source's output. @@ -132,6 +156,37 @@ def __init__(self, code: str, detail: str) -> None: super().__init__(f"{code}: {detail}") +class OneTimeCode: + """A code a person supplied, usable once. + + Its ``repr`` and ``str`` never show the value, it cannot be pickled or + copied, and :meth:`consume` hands the value out exactly once. + """ + + __slots__ = ("_value", "length") + + def __init__(self, value: str) -> None: + self._value: Optional[str] = value + self.length = len(value) + + def __repr__(self) -> str: + return "OneTimeCode()" + + __str__ = __repr__ + + def __reduce__(self) -> Any: + raise TypeError("a one-time code cannot be pickled or copied") + + def consume(self) -> str: + value, self._value = self._value, None + if value is None: + raise RuntimeError("this one-time code was already used") + return value + + def discard(self) -> None: + self._value = None + + @dataclass(frozen=True) class Request: kind: Kind @@ -157,7 +212,10 @@ def normalize_code(raw: object) -> str: if not isinstance(raw, str): raise SecondFactorRefused("second_factor_invalid", "the code is not text") - code = re.sub(r"[\s-]", "", raw) + line = raw.strip() + if _LINE_BREAK.search(line): + raise SecondFactorRefused("second_factor_invalid", "the code must be one line") + code = _GROUP_SEPARATORS.sub("", line) if not _CODE.fullmatch(code): raise SecondFactorRefused( "second_factor_invalid", @@ -206,8 +264,13 @@ def obtain( source: Optional[Source] = None, env: Optional[Mapping[str, str]] = None, heartbeat: Optional[Callable[[], None]] = None, -) -> Optional[str]: - """Get one second factor for ``step_id``. See the module docstring.""" + clock: Callable[[], float] = time.monotonic, +) -> Optional[OneTimeCode]: + """Get one second factor for ``step_id``. See the module docstring. + + The deadline is checked again when the source returns, whatever the + source: an answer that arrives after it is a timeout, and is dropped. + """ if kind not in ("code", "approval"): raise ValueError(f"unknown second-factor kind {kind!r}") @@ -222,32 +285,81 @@ def obtain( f"({URL_ENV} or {COMMAND_ENV}); nothing was typed", ) beat = heartbeat or _stderr_heartbeat() + started = clock() value = chosen.obtain(Request(kind, step_id, timeout_s), heartbeat=beat) + if clock() - started > timeout_s: + raise _late(timeout_s) if kind == "approval": return None - return normalize_code(value) + return OneTimeCode(normalize_code(value)) + + +def _late(timeout_s: float) -> SecondFactorRefused: + return SecondFactorRefused( + "second_factor_timeout", + f"no second factor within {timeout_s:g} s; nothing was typed", + ) + + +#: The only fields a second-factor step may set. Every other field (an +#: anchor, text, a param, an API binding, effects, a dialog response...) must +#: keep its default, so nothing can route the step around the handoff. +_STEP_FIELDS = frozenset( + { + "id", + "intent", + "action", + "one_time", + "field_label", + "expect", + "risk", + "risk_explanation", + "risk_review_required", + "wait_until", + "guard", + "timeout_s", + "identity_armed", + "identity_unarmed_reason", + "identifier_crop_missing_reason", + "surface", + "submit_binding_unbound_reason", + } +) def check_step_shape(step: Any) -> Any: - """``ir.Step``'s validator for ``one_time``; returns the step or raises.""" + """``ir.Step``'s validator for ``one_time``; returns the step or raises. + + ``one_time`` is set exactly on ``second_factor`` steps, and such a step + sets no field outside :data:`_STEP_FIELDS`. + """ - if step.one_time == "code" and not ( - step.action.value == "type" and step.secret and step.param and step.text is None - ): + second = step.action.value == ACTION + if second != (step.one_time is not None): raise ValueError( - "a one-time code step is a secret TYPE step that names its param " - "and carries no text" + "a second_factor step names its kind in one_time, and no other " + "step sets one_time" ) - if step.one_time == "approval" and ( - step.action.value != "wait" - or step.secret - or step.param is not None - or step.text is not None - ): - raise ValueError("a one-time approval step is a WAIT with no input") + if not second: + return step + for name, field in type(step).model_fields.items(): + if name in _STEP_FIELDS: + continue + default = field.get_default(call_default_factory=True) + if getattr(step, name) != default: + raise ValueError( + f"a second_factor step takes no {name}: the code or approval " + "comes only from a person" + ) return step +def delivers_input(step: Any) -> bool: + """Whether a second-factor step types (a code), not only waits.""" + + return step.action.value == ACTION and step.one_time == "code" + + def has_one_time_steps(workflow: Any) -> bool: """Whether any step of ``workflow`` (linear or program graph) is one-time.""" @@ -258,7 +370,7 @@ def has_one_time_steps(workflow: Any) -> bool: for state in (getattr(graph, "states", None) or {}).values(): if getattr(state, "step", None) is not None: steps.append(state.step) - return any(getattr(step, "one_time", None) for step in steps) + return any(getattr(step.action, "value", None) == ACTION for step in steps) def _stderr_heartbeat() -> Callable[[], None]: @@ -457,7 +569,13 @@ def obtain( request_id = self._create(request, _b64url(public)) while True: heartbeat() + if self._clock() >= deadline: + raise _late(request.timeout_s) state, sealed = self._poll(request_id) + # A poll can block; an answer that lands after the deadline is + # dropped, never accepted. + if self._clock() >= deadline: + raise _late(request.timeout_s) if state == "answered": if request.kind != "code": raise SecondFactorRefused( @@ -474,13 +592,9 @@ def obtain( raise SecondFactorRefused( "second_factor_declined", "the person declined; nothing was typed" ) - if state in ("expired", "consumed") or self._clock() >= deadline: - raise SecondFactorRefused( - "second_factor_timeout", - f"no second factor within {request.timeout_s:g} s; " - "nothing was typed", - ) - self._sleep(self.poll_interval_s) + if state in ("expired", "consumed"): + raise _late(request.timeout_s) + self._sleep(min(self.poll_interval_s, max(0.0, deadline - self._clock()))) def _create(self, request: Request, public_key: str) -> str: body = { @@ -533,19 +647,3 @@ def _poll(self, request_id: str) -> tuple[str, object]: ): return "pending", None return str(state), data.get("sealed") - - -def runtime_value(step: Any, result: Any = None) -> tuple[str, Optional[str]]: - """The replayer's hook: ``(code, None)``, or ``("", refusal message)``. - - An approval returns ``("", None)`` once confirmed. A refusal marks the - step result a governed refusal; its message starts with the closed code. - """ - - try: - value = obtain(step.one_time, step.id) - except SecondFactorRefused as refused: - if result is not None: - result.failure_category = "governed_refusal" - return "", f"Step '{step.id}' ({step.intent}) {refused}" - return value or "", None diff --git a/packages/flow/tests/e2e/test_wrap_second_factor_e2e.py b/packages/flow/tests/e2e/test_wrap_second_factor_e2e.py index 930a9fd354..3bee0c9884 100644 --- a/packages/flow/tests/e2e/test_wrap_second_factor_e2e.py +++ b/packages/flow/tests/e2e/test_wrap_second_factor_e2e.py @@ -177,8 +177,8 @@ def test_an_authenticator_code_comes_from_a_person_and_never_persists( assert program is not None workflow = Workflow.load(Path(program["bundle"])) (code_step,) = [s for s in workflow.steps if s.one_time] - assert code_step.one_time == "code" and code_step.param == sf.ONE_TIME_CODE_PARAM - assert code_step.secret and code_step.text is None + assert code_step.action.value == "second_factor" and code_step.one_time == "code" + assert code_step.param is None and not code_step.secret and code_step.text is None assert sorted(workflow.secret_params) == ["password", "username"] assert sf.ONE_TIME_CODE_PARAM not in workflow.params @@ -199,7 +199,7 @@ def test_an_authenticator_code_comes_from_a_person_and_never_persists( "second-run", {"username": USERNAME, "password": PASSWORD, "note": "second two-step note"}, ) - assert second.get("path") == "skill", second + assert second.get("path") == "skill", json.dumps(second, default=str) assert second["verified"] is True and second["model_calls"] == 0, json.dumps(second) assert second["receipt_outcome"] == "VERIFIED", second assert state.codes_accepted == accepted + 1 diff --git a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json index 8080bbc3ec..c3806dd5d9 100644 --- a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json +++ b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json @@ -7297,7 +7297,8 @@ "wait", "scroll", "read", - "switch_surface" + "switch_surface", + "second_factor" ], "title": "ActionKind", "type": "string" @@ -9372,7 +9373,8 @@ "wait", "scroll", "read", - "switch_surface" + "switch_surface", + "second_factor" ], "title": "ActionKind", "type": "string" @@ -11884,6 +11886,22 @@ "description": "TYPE/SELECT_OPTION steps only: the receiving field's best available label, captured PASSIVELY at record time (DOM