capricorn86 / happy-dom

A JavaScript implementation of a web browser without its graphical user interface
MIT License
3.31k stars 200 forks source link

document.cookie does not support `Secure;` #1162

Open motss opened 11 months ago

motss commented 11 months ago

Describe the bug When setting a document.cookie with Secure;, document.cookie will become an empty string.

To Reproduce The following reduced test case shows that Secure; is not supported:

describe('test cookie', () => {
  it('test', () => {
    document.cookie = 'a=a; Secure; SameSite=Strict; path=/';

    expect(document.cookie).toBe('a=a'); // This fails due to document.cookie returns '';
  });
});

Expected behavior When running document.cookie = 'a=a; Secure; SameSite=Strict; path=/';, document.cookie should return a=a instead of ''.

Screenshots N/A

Device:

Additional context N/A

lsanwick commented 8 months ago

I'm seeing the same issue, is there any way to resolve this?

HiroshiOHSUGA commented 4 months ago

I met the same and I could fix it.

My cases is vitest. I could fix by configuring url to https url.

    environmentOptions: {
      happyDOM: {
        url: "https://localhost:3000",
      },
    },

Possibly your tests are running on not https:// location. If a cookie was marked secure on http:// page, it is ignored by browser. This isn't happy-dom issue.

motss commented 4 months ago

A cookie with the Secure attribute is only sent to the server with an encrypted request over the HTTPS protocol. It's never sent with unsecured HTTP (except on localhost), which means man-in-the-middle attackers can't access it easily. Insecure sites (with http: in the URL) can't set cookies with the Secure attribute. However, don't assume that Secure prevents all access to sensitive information in cookies. For example, someone with access to the client's hard disk (or JavaScript if the HttpOnly attribute isn't set) can read and modify the information.

That's a happy-dom issue because localhost is a secure context.