Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

6.4 KB
Raw Blame
/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import fs from 'node:fs';

import { test, expect, parseResponse, consoleEntries } from './fixtures';

test('browser_type', async ({ startClient, server }) => {
  const secretsFile = test.info().outputPath('secrets.env');
  await fs.promises.writeFile(secretsFile, 'X-PASSWORD=password123');

  const { client } = await startClient({
    args: ['--secrets', secretsFile],
  });

  server.setContent('/', `
    <!DOCTYPE html>
    <html>
      <input type='keypress' onkeypress="console.log('Key pressed:', event.key, ', Text:', event.target.value)"></input>
    </html>
  `, 'text/html');

  await client.callTool({
    name: 'browser_navigate',
    arguments: {
      url: server.PREFIX,
    },
  });

  {
    const response = await client.callTool({
      name: 'browser_type',
      arguments: {
        element: 'textbox',
        target: 'e2',
        text: 'X-PASSWORD',
        submit: true,
      },
    });
    expect(response).toHaveResponse({
      code: `await page.getByRole('textbox').fill(process.env['X-PASSWORD']);
await page.getByRole('textbox').press('Enter');`,
      snapshot: expect.stringMatching(/textbox (\[active\] )?\[ref=e2\]: <secret>X-PASSWORD<\/secret>/),
    });
  }

  expect(await client.callTool({
    name: 'browser_console_messages',
  })).toHaveResponse({
    result: expect.stringContaining(`[LOG] Key pressed: Enter , Text: <secret>X-PASSWORD</secret>`),
  });
});


test('secrets are redacted in console log artifact', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/41509' } }, async ({ startClient, server }) => {
  const secretsFile = test.info().outputPath('secrets.env');
  await fs.promises.writeFile(secretsFile, 'X-PASSWORD=password123');

  const { client } = await startClient({
    args: ['--secrets', secretsFile],
  });

  server.setContent('/', `
    <!DOCTYPE html>
    <html>
      <input type='keypress' onkeypress="console.log('Key pressed:', event.key, ', Text:', event.target.value)"></input>
    </html>
  `, 'text/html');

  await client.callTool({
    name: 'browser_navigate',
    arguments: {
      url: server.PREFIX,
    },
  });

  const response = parseResponse(await client.callTool({
    name: 'browser_type',
    arguments: {
      element: 'textbox',
      target: 'e2',
      text: 'X-PASSWORD',
      submit: true,
    },
  }));

  const consoleLog = await consoleEntries(response);
  expect(consoleLog).not.toContain('password123');
  expect(consoleLog).toContain('<secret>X-PASSWORD</secret>');
});

test('browser_fill_form', async ({ startClient, server }) => {
  const secretsFile = test.info().outputPath('secrets.env');
  await fs.promises.writeFile(secretsFile, 'X-PASSWORD=password123');

  const { client } = await startClient({
    args: ['--secrets', secretsFile],
  });

  server.setContent('/', `
    <!DOCTYPE html>
    <html>
      <body>
        <form>
          <label>
            <input type="email" id="email" name="email" />
            Email
          </label>
          <label>
            <input type="password" id="name" name="password" />
            Password
          </label>
        </form>
      </body>
    </html>
  `, 'text/html');

  await client.callTool({
    name: 'browser_navigate',
    arguments: { url: server.PREFIX },
  });

  expect(await client.callTool({
    name: 'browser_fill_form',
    arguments: {
      fields: [
        {
          name: 'Email textbox',
          type: 'textbox',
          target: 'e4',
          value: 'John Doe'
        },
        {
          name: 'Password textbox',
          type: 'textbox',
          target: 'e6',
          value: 'X-PASSWORD'
        },
      ]
    },
  })).toHaveResponse({
    code: `await page.getByRole('textbox', { name: 'Email' }).fill('John Doe');
await page.getByRole('textbox', { name: 'Password' }).fill(process.env['X-PASSWORD']);`,
  });

  expect(await client.callTool({
    name: 'browser_snapshot',
    arguments: {},
  })).toHaveResponse({
    inlineSnapshot: expect.stringContaining(`- textbox \"Password\" [active] [ref=e6]: <secret>X-PASSWORD</secret>`),
  });
});

test('empty secret value is ignored', async ({ startClient, server }) => {
  const secretsFile = test.info().outputPath('secrets.env');
  await fs.promises.writeFile(secretsFile, 'EMPTY_SECRET=\nX-PASSWORD=password123');

  const { client } = await startClient({
    args: ['--secrets', secretsFile],
  });

  server.setContent('/', `
    <!DOCTYPE html>
    <html>
      <body><p>hello password123</p></body>
    </html>
  `, 'text/html');

  const response = await client.callTool({
    name: 'browser_navigate',
    arguments: { url: server.PREFIX },
  });

  // Response should not be mangled by empty secret replacement
  expect(response).toHaveResponse({
    snapshot: expect.stringContaining(`<secret>X-PASSWORD</secret>`),
  });
});

test('redacts url parameter values', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright-mcp/issues/1791' } }, async ({ startClient, server }) => {
  const { client } = await startClient({
    args: ['--redact-url-params=code,access_token'],
  });

  server.setRedirect('/login', '/app?code=abc123&state=s1#access_token=jwt.payload.sig&token_type=bearer');
  server.setContent('/app?code=abc123&state=s1', `<title>App</title><a href="/next?code=def456">Next</a>`, 'text/html');

  expect(await client.callTool({
    name: 'browser_navigate',
    arguments: { url: server.PREFIX + '/login' },
  })).toHaveResponse({
    page: `- Page URL: ${server.PREFIX}/app?code=<redacted>&state=s1#access_token=<redacted>&token_type=bearer
- Page Title: App`,
    snapshot: expect.stringContaining(`/url: /next?code=<redacted>`),
  });

  expect(await client.callTool({
    name: 'browser_tabs',
    arguments: { action: 'list' },
  })).toHaveResponse({
    result: `- 0: (current) [App](${server.PREFIX}/app?code=<redacted>&state=s1#access_token=<redacted>&token_type=bearer)`,
  });
});