Red teaming web chat interfaces with PyRIT's Playwright target: when a chatbot has no API
When a chatbot exists only as a web page, PyRIT's PlaywrightTarget can still send it adversarial prompts and collect its replies by driving a browser. The target relies on an interaction function that your team writes: it navigates to the page, enters the prompt, waits for the answer and returns the response text to PyRIT. The Generic Playwright Target documentation describes this pattern, which applies to any web application you can operate in a browser, including chat products that offer no API at all. PyRIT's wider target list includes web app targets driven through Playwright, but that does not mean a ready-made connector exists for a specific chat product. Confirm that with the PyRIT documentation for your version before you plan around it.
The interaction function carries most of the engineering effort, and it is where the team should make its first decisions. Someone needs to choose the selectors for the input box, the send control and the reply container, and decide how the function knows the reply is complete, since streamed answers can still be rendering when a naive read occurs. Login, session handling, consent banners, and any content the interface loads asynchronously also belong in this function or in setup code around it. Ask the application owner which environment you may test, whether a dedicated test tenant or test account is available, and whether selectors will change during the engagement, because a fragile function will produce misleading results long before it produces a useful finding.
What you need before a browser-driven PyRIT test can run
A browser-driven test depends on more than PyRIT itself. The test host needs a supported Python runtime, a browser automation stack, test accounts that reflect real user access, a network path to the chat application, and written approval from the people who own it. Confirm each item before you write the interaction function, because a gap in any one of them tends to surface as a failed run rather than a clear finding.
Supported Python runtime
PyRIT installs with pip, and the PyPI package supports Python 3.10 up to but not including 3.15. The PyRIT documentation recommends Python 3.13, so pin that version on the test host or in its container image. Confirm the current requirement on the PyPI page before you build, since a runtime outside the supported range will fail at install or import.
PyPI package pagePlaywright and browser binaries
The PlaywrightTarget drives a real browser, so the host needs the Playwright package plus the browser engine binaries it launches. Install the browsers in the same environment that runs PyRIT, and record their exact versions. Confirm the Playwright and browser versions against the PyRIT documentation for your release, because the pairing changes between releases and mismatches often break page navigation.
Generic Playwright Target docsTest accounts with matching permissions
Create dedicated test accounts that hold the same role as the users the chatbot is meant to serve, not an administrator role. Permissions decide which tools, data sources and system prompts the bot exposes, so a test run under the wrong role can miss the paths that matter. Ask the owner for one account per role and confirm how sessions expire, since a login that times out mid-attack will distort results.
Network reachability from the test host
The test host must reach the chat page over the same path real users take, including any VPN, proxy, allowlist or single sign-on redirect. Check DNS resolution, TLS trust for internal certificates and firewall rules from the host itself, not from your laptop. Confirm with the network team whether the chat application rate limits or blocks automated traffic, since that behavior affects concurrency and retry settings.
Written authorization from the chat owner
Get written approval from the owner of the chat interface before any prompt is sent. The approval should name the environment, the accounts used, the time window, the categories of prompts planned, and who receives the findings. Automated attacks can generate large volumes of traffic, store harmful outputs and trigger incident response, so the owner's sign-off protects both the test team and the business.
Logging and data handling plan
PyRIT stores conversations and results in memory, either SQLite or Azure SQL, so decide where that data lives before the first run. Agree with the owner how transcripts containing sensitive or harmful outputs are stored, who can read them and how long they are kept. Confirm the storage location and access controls on the test host, because the memory database becomes a record of everything the test produced.
How the interaction function turns a web page into a target
The interaction function is the part of a Playwright setup that your team writes and owns. PyRIT's PlaywrightTarget handles the browser: it navigates to the chat page, hands each prompt to your function, and passes back whatever your function returns. Your function is what knows the page itself: which input box receives the prompt, which control sends it, and which element holds the reply. The Generic Playwright Target documentation describes this pattern, in which the function navigates the page, enters a prompt and retrieves the response. Before writing code, confirm the page's selectors and the way it signals that a reply has finished streaming, because a function that reads the reply too early will score a partial answer.
This function is usually the largest piece of custom work in the engagement. An HTTP target only needs a request template and a parser for the JSON or text that comes back, and a WebSocket target needs the message format and the response handler. A web chat has neither a stable API nor a fixed protocol, so the function absorbs every fragile detail of the interface: login prompts, cookie banners, rendered markdown, loading indicators, and the moment a new conversation starts. Plan for it to break when the front end changes, and agree who maintains the selectors after the first red team run. Ask whether the application team can expose stable test identifiers, since these are far more durable than class names generated by a build tool.
The browser session is state that the HTTP and WebSocket targets do not have in the same form. A multi-turn strategy such as Crescendo depends on the chat remembering earlier turns, so the function must keep the same page and conversation open between calls and must not reload the page on each prompt. Check what the application stores in the session, including cookies, local storage and any conversation identifier in the URL, and confirm how long that session stays valid. If the session expires mid-attack, the later turns will test a fresh conversation and the results will not show the escalation you intended. Record the session setup as part of the test evidence so a reviewer can reproduce the conversation.
How a PyRIT attack reaches the chat page and returns a reply
The attack starts in the attack driver on the test host, which hands each prompt to the PlaywrightTarget. The target calls its interaction function, which drives a browser to the chat page, types the prompt and reads the reply from the page. The reply then returns to the attack, which records the exchange in memory and passes it to a scorer. Check that the interaction function's selectors match the live page and that the browser session stays inside the test boundary.
Each prompt travels from the attack driver through the browser to the chat page and back.
Configuring the Playwright target step by step
This sequence takes a team from a clean PyRIT install to a working Playwright target that submits prompts to a chat page, reads replies, and runs a persisted multi-turn session against a non-production instance. Each step ends with a check that confirms the piece works before the next one is built on it.
Install PyRIT and Playwright
Create a virtual environment on a supported Python version. The PyPI package supports Python 3.10 up to but not including 3.15, and the PyRIT documentation recommends Python 3.13. Install PyRIT with pip, then install the Playwright package and its browser binaries, which are a separate download. Confirm the versions you installed against the release you plan to standardize on, since PyRIT's APIs change between releases. The step is done when a short script imports PyRIT and Playwright without error and launches a headless browser to a blank page.
Launch a browser against a non-production chat instance
Obtain a test instance of the chat application that holds no production data and uses test accounts. Open it in a Playwright browser from a small script, log in if the application requires it, and take a screenshot to confirm the page layout. Note the selectors for the prompt input, the send control and the element that holds the reply, because the interaction function depends on them. Ask the application owner to confirm that test traffic is permitted and that conversation logs from the instance are handled under your data policy. The step is done when the screenshot shows the chat page in the logged-in state you expect.
Write the interaction function
Write the interaction function that PyRIT's PlaywrightTarget calls for each turn. It should navigate to the chat page if needed, locate the input field, type the prompt, submit it, wait until the response has finished rendering, and return the reply text. Waiting is the usual failure point: streaming replies and typing indicators can make a naive read return a partial answer, so wait on a stable completion signal the page exposes. The exact function signature and the target setup are in the Generic Playwright Target documentation. The step is done when calling the function directly with a known prompt returns the full reply text.
Wire the target into a single-turn test
Create the PlaywrightTarget with your interaction function and pass it to a single-turn attack in PyRIT, using one benign prompt from a seed set you control. Run the attack and inspect the stored conversation in PyRIT memory. Confirm that the prompt sent, the reply captured and any scorer result match what you saw in the browser. The check is a known prompt that returns an expected reply, such as a fixed answer your test instance is configured to give, recorded in memory with the correct text.
Confirm reply capture on harder prompts
Run a small set of prompts that produce long, formatted or refused replies, since these are where the reader most often breaks. Compare the text stored in memory with the rendered page for each one. Look for truncated replies, missing markdown content, banner or disclaimer text captured as the answer, and replies that arrive after your wait condition fires. Adjust the wait logic and the reply selector until the stored text matches the page. The step is done when a set of varied prompts all store complete replies in a comparison you have reviewed.
Extend the target to multi-turn with a persisted session
Move from single prompts to multi-turn attacks, which need the browser session and the conversation on the page to persist across turns. Keep one browser context open for the attack, reuse the logged-in session, and confirm that each new prompt lands in the same conversation thread rather than a fresh one. Record the session state as part of the run so a failed run can be resumed or inspected. The check is a three-turn exchange in which the second and third prompts clearly refer to earlier answers and the application's own history shows the same thread.
Verify the multi-turn run and document the setup
Run a complete multi-turn test against the test instance and review the stored conversation from start to finish. Confirm that each turn was sent in the correct thread, that the session did not expire mid-run, and that failures were recorded rather than silently skipped. Write down the Playwright version, PyRIT version, selectors, wait conditions and the test account used, so the setup can be repeated after an application update. Consult the Generic Playwright Target documentation for the exact code and parameters before you finalize the script. The step is done when a second person can rerun the same test and get the same conversation structure.
Mapping prompts, replies and page elements to PyRIT objects
This table traces each element of a chat page, from the input field to the login state, through the interaction function, the conversation piece, the memory record and the scorer input. Read each row left to right to see where a page element becomes data PyRIT stores and judges. The main takeaway is that every selector and wait condition is specific to your application, so each mapping must be checked against your own page markup before any results are trusted.
| Page element | Interaction function step | PyRIT conversation piece and memory record | Scorer input and what to confirm |
|---|---|---|---|
| Input field | Locate the prompt box, clear any draft text, and type the converted prompt | Outgoing user piece holds the original objective and any converted text as sent | Scorer sees only the reply, so confirm the stored prompt matches what was typed |
| Send control | Click the button or send the Enter key, then wait for the request to finish | No separate piece; the send action defines when one user turn ends in memory | Confirm whether the control disables during generation and whether Enter submits in your UI |
| Reply container | Wait for a new message node, then read its text once streaming stops | Assistant piece stores the extracted reply text, not the full page HTML | Main scorer input; confirm that streaming, typing indicators and citations are excluded |
| Conversation reset | Click new chat or clear control between objectives to start a fresh session | A new conversation identifier separates memory records for each attack | Without a reset, later turns can be scored against earlier context; confirm it clears server-side history |
| Login state | Check for the signed-in marker before each run and re-authenticate when it is missing | Authentication failures should be recorded as errors, not as assistant replies | Confirm the session cookie lifetime and that refused or expired sessions never reach the scorer |
| Citations, tool output and banners | Decide whether to strip or keep these nodes when extracting the reply | Stored as part of the reply text if kept, so results can change silently | Decide per application and record the choice in the test plan |
Securing the test browser, credentials and test data
A Playwright run drives a real browser against a chat system that may hold sensitive data, using credentials that grant access to it. The controls below cover the browser, the accounts, the network path and the records PyRIT keeps, so the test does not create a new exposure of its own.
Keep credentials out of scripts
PyRIT reads credentials from ~/.pyrit/.env and settings from ~/.pyrit/.pyrit_conf, so the login details for the chat application should live there rather than in the attack script or a shared notebook. Check that the file is readable only by the account running the test, that it is excluded from version control, and that scripts reference variable names instead of values. Ask who else can read the machine where the file sits.
Use dedicated least-privilege test accounts
Create a test user for the chat interface that has only the permissions the chatbot needs to answer questions. Do not reuse a personal account or an administrator account, because an attack run can expose whatever that identity can see. Confirm with the application owner which data sources the test user can reach through the chat, and remove any that are not required for the test objective.
Isolate the browser profile
Run the Playwright browser with a fresh, dedicated profile that is not shared with a person's everyday browsing. Cookies, saved passwords and session tokens from other sites should not be present, and the profile should be discarded or reset between engagements. A reused profile can carry a logged-in session from a different system into the test, which makes results hard to attribute and can leak credentials.
Restrict the hosts the browser can reach
Limit outbound traffic from the test runner to the chat application's own hosts and the services it depends on, such as its identity provider. Enforce this with egress rules or a proxy rather than relying on the script alone. A browser that follows links or loads third-party content during an attack run can reach systems that were never in scope, and a prompt injection in the chat output could steer it there.
Protect memory records with sensitive output
PyRIT stores conversations and results in SQLite or Azure SQL, and chatbot replies may quote customer records, internal documents or personal data. Decide where the memory database lives, who can query it, how long it is kept, and how it is deleted at the end of the engagement. Treat exports for reviewers as sensitive documents in their own right.
Test only authorized systems
Obtain written authorization that names the chat application, its environment, the test window and the people who can approve changes before the first run. Confirm that the target is a system the organization owns or controls, and that the test accounts and data are sanctioned for use. A run against a production chatbot that customers use needs the owner's agreement on timing and load.
Report PyRIT vulnerabilities privately
If testing surfaces a suspected vulnerability in PyRIT itself, report it privately through the Microsoft Security Response Center under the project's security policy rather than in a public issue. Keep the reproduction details, memory records and browser traces within the team until the report is handled. This applies to defects in the tool, not to findings about the chatbot under test, which go to its owner.
PyRIT on GitHubVerifying the Playwright target before trusting its results
Functional checks confirm that the interaction function does what it claims: it navigates to the chat page, enters the prompt, submits it, and returns the text of the assistant's reply and nothing else. Run these checks before any attack run, and treat a failure as a blocked target rather than a finding. A reply that is empty, truncated, or contains interface text such as a "thinking" indicator or a copy button label means the function is reading the wrong element.
- Known-answer prompt: Send a prompt with a fixed, predictable answer, such as asking the bot to repeat a short phrase, and compare the returned text to the expected string.
- Multi-message check: Send two prompts in sequence and confirm each returned reply belongs to its own prompt, not the previous one.
- Reply boundaries: Confirm the function excludes the echoed user message, timestamps, avatars, and suggested follow-up buttons.
- Error path: Confirm the function raises a clear error when the input box is missing or the reply never appears, instead of returning an empty string.
- Logged output: Check that the prompt and reply stored in PyRIT memory match what you saw in the browser.
Keep the results of these checks with the run record so an auditor can see the target was working when the attack ran.
Stability checks test whether the target behaves the same way across timing variation, page reloads, and session changes. Web chat interfaces often stream replies token by token, load content lazily, or show loading states that look like finished replies. A function that works on one fast test prompt can fail on a long answer, a slow network, or after the page has been refreshed, and those failures can quietly skew attack success rates.
- Streaming completion: Use prompts that produce long answers and confirm the function waits until the reply is complete, not just until the first words appear.
- Timing variation: Repeat the same known-answer prompt several times with different waits and confirm the returned text is identical each time.
- Page reload: Reload the page between prompts and confirm the function still finds the input box and reads the new reply.
- Session expiry: Confirm what happens when the chat session times out or the login cookie expires, and that the run stops with an error rather than scoring a login page.
- Concurrency: If you run attacks in parallel, check that separate browser contexts do not share conversation state.
Record the timeout values you chose, since they affect both reliability and how long each run takes to complete.
Scoring checks confirm that the scorer evaluates the reply the target returned, and that the scorer's verdict matches what a human reviewer would decide. A scorer that receives the wrong text, such as a page footer or a disclaimer, can mark a refusal as compliant or a harmful answer as safe. Verify the scorer against replies you already know the answer to, including both clear refusals and clear compliance, before you rely on any attack success rate.
- Input check: Inspect the exact text passed to the scorer for several attacks and confirm it is the assistant's reply only.
- Labeled sample: Build a small set of replies you have labeled by hand, with both refusals and compliant answers, and check the scorer's agreement with those labels.
- Refusal wording: Test refusals phrased in several ways, since web chat products often use different wording than API models.
- Boundary cases: Include partial refusals and answers that refuse in one sentence and comply in the next.
- Score logging: Confirm the score and the scored text are stored together in memory so a reviewer can trace each verdict.
Repeat the scorer check whenever you change the scorer configuration or the chat product's response style.
Selector drift happens when a front-end release renames or restructures the elements the target depends on, such as the input box, the send button, or the reply container. The target may then return an empty string, a menu label, or stale text from an earlier turn, and an attack run can look successful or unsuccessful for reasons unrelated to the model. A small set of benign control prompts, run before each scheduled test cycle and after any release of the chat front end, detects this early without spending much of your attack budget.
- Control prompt set: Keep a few harmless prompts with predictable answers, covering a short fact, an arithmetic result, and a fixed phrase.
- Pre-run gate: Run the control set first and stop the attack run if any control fails.
- Release trigger: Re-run the controls after the web application's own changes are announced or after you notice a layout change.
- Selector inventory: Document each selector the interaction function uses, so whoever updates the target knows what to check.
- Owner contact: Confirm who on the application team receives notice of front-end releases, since the target cannot detect a change it was never told about.
Ask the application owner to confirm whether the chat product offers a test or staging environment where control runs can happen before production.
Why browser-driven PyRIT tests fail and how to fix them
This table pairs each common failure in browser-driven PyRIT runs with its usual cause and the fix to apply. Read it before a first run against a production chat UI, and again when a run produces empty, truncated or unexpected results. The main takeaway is that most failures come from the page changing underneath the interaction function, so the interaction logic and the run conditions need to be checked together.
| Failure | Usual cause | Fix |
|---|---|---|
| Selectors break | The front end changed its markup, class names or component structure after a release, so the input box or send button no longer matches. | Prefer stable attributes such as roles, labels or test IDs in the interaction function, and rerun a single prompt to confirm selectors before each campaign. |
| Reply read while still streaming | The interaction function returns as soon as the prompt is submitted or the first tokens appear, so the captured text is partial. | Wait for a completion signal in the page, such as the send button re-enabling or a stop control disappearing, before reading the reply element. |
| Login expires mid-run | The browser session has a time-limited token or cookie, and a long multi-turn attack outlasts it. | Confirm session lifetime with the application owner, reuse a saved browser state, and check for a login page in the interaction function so failures are logged clearly. |
| CAPTCHA or bot protection | The site detects automated browsing and presents a challenge or blocks the session. | Get written approval from the owner for test access, use a sanctioned test account or allowlisted environment, and do not attempt to defeat the challenge. |
| Rate limits | The chat service or its gateway throttles requests from one session or account, so replies become errors or empty. | Lower concurrency, add delays between turns, and record throttling responses as a separate outcome so they are not scored as refusals. |
| Wrong reply element captured | The selector matches a system notice, a previous message, a suggestion chip or a hidden element instead of the newest assistant reply. | Scope the selector to the latest assistant message container and check the captured text against a screenshot for a sample of turns. |
| Memory grows in long sessions | The browser keeps DOM history, media and conversation state open across many turns, and PyRIT memory accumulates each exchange. | Restart the browser context between attacks or at set intervals, close unused pages, and monitor process memory during the first long run. |
Questions buyers ask about Playwright-based red teaming
Can our internal team run Playwright-based red teaming on its own?
Yes, if your team has Python and browser automation skills, time to build and maintain the interaction function, and someone who can judge the results. PyRIT is an open-source framework that installs with pip, and its PlaywrightTarget works through an interaction function that navigates the page, enters a prompt and retrieves the reply. The hard parts are not the install. They are writing selectors that survive UI changes, handling login and streaming replies, and deciding which harms matter for your chatbot. Ask whether your team has someone who can own that code after the first run, and whether they can review scoring results against your policy. A partner can take on the build and handoff so your team keeps the working setup.
What makes a web chat interface harder or easier to test?
The effort is driven by how the interface behaves in the browser, not by the model behind it. Plan for these drivers:
- Page complexity: the number of screens, widgets and dynamic elements the script must navigate before it reaches the prompt box.
- Authentication: single sign-on, multi-factor prompts, and session expiry all need a reliable test account and a way to keep sessions alive.
- Streaming replies: responses that arrive token by token require the interaction function to wait for the reply to finish before it reads it.
- Number of attack paths: each conversation flow, such as new chats, follow-ups, file uploads or tool calls, adds code and test cases.
Ask for a walkthrough of these four items before accepting any estimate.
How long does a Playwright red teaming engagement take?
The duration depends on the scope you agree in writing, so no fixed figure applies here. The main variables are the number of pages and flows to drive, how stable the interface is, whether authentication needs special handling, and how many attack strategies and harm categories you want to run. Time also goes to reviewing results, fixing the interaction function after UI changes, and retesting after fixes. Engagements are normally fixed-scope, so request a schedule that lists build, test, reporting and retest phases separately. Confirm with the vendor which PyRIT version and Python version the schedule assumes, since the PyPI package supports Python 3.10 up to but not including 3.15 and the documentation recommends Python 3.13.
What must we provide before testing starts?
Most of the work depends on access and decisions from your side. Prepare the following before work begins:
- A test instance of the chatbot that matches production configuration as closely as possible, with a named owner.
- Test accounts with the roles and permissions your users have, plus any single sign-on or multi-factor setup the tests need.
- Written sign-off from an accountable owner on the scope, the harm categories, the rate of requests allowed and the escalation contact.
- Documentation of the interface, such as page flows, expected reply formats and known limits.
Also confirm where PyRIT's credentials and settings will be stored, since PyRIT reads them from ~/.pyrit/.env and ~/.pyrit/.pyrit_conf.
Can we run Playwright red teaming against production?
Start with a test instance. Testing against production means automated adversarial prompts reach real users' data paths, may trigger alerts or account lockouts, and may create stored chat history. Only consider production testing if your owner signs off in writing, the risk is documented, rate limits are set, and test accounts are isolated. Ask the vendor how the scope handles logging, cleanup of test conversations, and stopping the run. Confirm with your own change management policy whether production testing is permitted at all.
How is Playwright testing different from testing through an API?
An API target sends structured requests and receives structured responses, so the prompt and reply are direct. A Playwright target works through the user interface, so it must find the prompt box, submit text, wait for the page to render the reply, and read it from the screen. That adds more failure points: layout changes can break selectors, pop-ups can block input, and streaming replies can be read too early. The security question is also different. Browser testing exercises the same interface your users see, including client-side filters and display logic, which an API test may skip. If your chatbot has an API you can reach, that route is usually simpler to maintain, and the browser route is worth the extra effort when the interface is the only entry point.
What does the engagement cost, and what drives the quote?
DeployOpen does not publish a price list. A quote follows from the written scope, so the items that move it are the same ones that drive effort: page complexity, authentication, streaming behavior, the number of attack paths, the number of harm categories, the retest cycle and the reporting format. Ask for the quote to separate one-time build work from any recurring work, such as updating the interaction function after the vendor ships UI changes or running the suite on a schedule. PyRIT itself is open source under the MIT license, so the license is not the cost driver; the work to build and run the tests is. Confirm any model usage charges for the objective and scoring models separately, since they depend on your own accounts.
How DeployOpen scopes and delivers a web chat red team
DeployOpen plans and runs PyRIT red teaming against web chat interfaces as a fixed-scope engagement, with the Playwright target, interaction function and evidence agreed in writing before work starts. The result is a tested browser path, a findings report with fixes and a retest, delivered inside the client's own environment.
How we scope
- Confirm which chat pages, login flows and test accounts the Playwright target will drive, in writing.
- Agree which harm categories, datasets and attack strategies apply to the chatbot being tested.
- Define the response-reading logic, success criteria and the environment where PyRIT will run.
- Engagements are fixed-scope, and ongoing support or continuous testing is available as a retainer.
How we build
- Set up PyRIT with a browser runtime and credentials stored in the client's approved secrets location.
- Write the interaction function that navigates the page, enters the prompt and waits for the complete reply.
- Test the selectors, timeouts and session handling against the live chat interface before any attack runs.
- Configure memory storage and scoring so every prompt, reply and verdict is recorded for review.
How we hand over
- Deliver a findings report that ties each successful attack to its recorded conversation and scorer result.
- Document the interaction function, configuration and run steps so your team can repeat the test.
- Recommend fixes for the chatbot, its guardrails and the test harness, then retest the findings.
- Walk your security and engineering teams through the results and the open items.
How we support
- Update the interaction function when the chat interface changes its layout, login or streaming behavior.
- Run repeat red team passes after model, prompt or content filter changes, as agreed in the retainer.
- Upgrade PyRIT and its dependencies on a schedule you approve, with a check that the browser target still works.
- Confirm support terms, response expectations and retest scope in the written agreement before work begins.

