Skip to content

Investigate possible BUG Invoke-WebRequest content type charset #19156

Closed

Description

@CarloToso

Prerequisites

Steps to reproduce

Invoke-WebRequest POST with -Body (string) and -Headers containing a content type with charset (ex. plain/text; charset="windows-1251") and no -ContentType.

Invoke-WebRequest -URI "some uri" -Method POST -Headers @{Content-Type="plain/text; charset=windows-1251"} -Body "string encoded with windows-1251 charset"

The charset in the headers are ignored be ignored and default to UTF8.
This doesn't happen if we use -ContentType

Invoke-WebRequest -URI "some uri" -Method POST -ContentType "plain/text; charset=windows-1251" -Body "string encoded with windows-1251 charset"

Both should have the same behaviour

I found this possible bug while reading the code; I haven't encountered it in the real world so I don't really know how we could test it (and if testing it is even possible)

Expected behavior

SetRequestContent should try to get the charset from the ContentType in Headers saved in the WebSession
WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType]

Actual behavior

SetRequestContent only checks for -ContentType charset

Error details

While writing some code in `WebRequestPSCmdlet.Common.cs` think I found a BUG (line 1491) it should check for `WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType]` instead of `ContentType` (this should be ok because if both are present `ContentType` overwrites `WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType]`) unfortunately I don't know how to test it (I think it would require sending a wierdily encoded string as Body), if confirmed I'll open another PR to fix it.

Environment data

Latest master
https://github.com/PowerShell/PowerShell/blob/60b4e9704fca546f76e1128e30de4077c51a3ca2/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs

Visuals

No response

Activity

  1. added
    Needs-Triage
    on Feb 15, 2023
  2. iSazonov commented on Feb 15, 2023

    @iSazonov
    Collaborator

    CarloToso Please make more clear repro steps and description.

  3. mklement0 commented on Feb 17, 2023

    @mklement0
    Contributor

    If I understand correctly, the problem is that a charset value is only honored if provided via -ContentType, not also as part of -Headers.

    Source-code link:

    if (ContentType is not null)
    {
    // If Content-Type contains the encoding format (as CharSet), use this encoding format
    // to encode the Body of the WebRequest sent to the server. Default Encoding format
    // would be used if Charset is not supplied in the Content-Type property.
    try
    {
    MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(ContentType);
    if (!string.IsNullOrEmpty(mediaTypeHeaderValue.CharSet))
    {
    encoding = Encoding.GetEncoding(mediaTypeHeaderValue.CharSet);
    }
    }

  4. CarloToso commented on Feb 17, 2023

    @CarloToso
    ContributorAuthor

    Michael Klement (@mklement0) Exactly, but I don't know how to test it.

    Source-code link (which, however, suggests that this is not the case, if I read it correctly; it suggests that -ContentType is consulted first):

    No you are wrong, the code you linked checks for charset in ContentType and then uses the default encoding (UTF8) if there's no charset, it never checks the -Headers

  5. mklement0 commented on Feb 17, 2023

    @mklement0
    Contributor

    CarloToso, you're right - I misread the source code; I've edited my previous comment to remove the mistaken interpretation.

  6. mklement0 commented on Feb 20, 2023

    @mklement0
    Contributor

    rhubarb-geek-nz, without weighing in on what the right resolution is in this particular case, let me make a general point:

    • It is helpful to point out what the documented behavior is.

    • It is not helpful to proclaim that the documented behavior is ipso facto the correct one.

    Whether the current behavior ends up being deemed (a) a bug or (b) requiring improvement or (c) neither is a separate matter, which needs to be debated on the merits of the arguments made.

  7. mklement0 commented on Feb 20, 2023

    @mklement0
    Contributor

    rhubarb-geek-nz, the premise of this issue is that only -ContentType is honored, which is the (only) part covered by the documentation. As such, your comment doesn't address the specific issue being raised: why isn't an - arguably equivalent - charset definition also honored as part of the -Headers argument?
    It's fine to say, "here's what the docs say"; it's not helpful to say, "it's not a bug, it's a feature", without addressing the arguments made that describe the current behavior as deficient.

  8. mklement0 commented on Feb 20, 2023

    @mklement0
    Contributor

    rather than rely on the headers being interpreted.

    That part is your conjecture.
    And even if this was what the docs meant to say, at the very least the docs should be amended to state that explicitly, especially since it is reasonable to conceive of -ContentType as a shortcut to a Content-Type attribute in a hashtable passed to -Headers.

    Of course, a different resolution could be to implement - and document - precedence rules.

    Again: I'm not weighing in on what the correct resolution is; I'm trying to point what is required for a constructive, nuanced debate (which shouldn't require several comments just to draw out what your original comment was meant to express).

  9. CarloToso commented on Feb 26, 2023

    @CarloToso
    ContributorAuthor

    rhubarb-geek-nz what version of powershell are you using for your tests?

  10. CarloToso commented on Feb 26, 2023

    @CarloToso
    ContributorAuthor

    The default encoding for Invoke-WebRequest in 7.3 is iso-8859-1, changed to utf-8 in 7.4 preview1

  11. CarloToso commented on Feb 26, 2023

    @CarloToso
    ContributorAuthor

    There is also a special workaround (that can maybe be removed), that sets the encoding to utf8 when the body is json

    protected void InitializeContent()
    {
    string contentType = ContentHelper.GetContentType(BaseResponse);
    if (ContentHelper.IsText(contentType))
    {
    // Fill the Content buffer
    string characterSet = WebResponseHelper.GetCharacterSet(BaseResponse);
    if (string.IsNullOrEmpty(characterSet) && ContentHelper.IsJson(contentType))
    {
    characterSet = Encoding.UTF8.HeaderName;
    }
    Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out Encoding encoding);
    Encoding = encoding;
    }
    else
    {
    Content = string.Empty;
    }
    }

  12. CarloToso commented on Feb 26, 2023

    @CarloToso
    ContributorAuthor

    Maybe you could open a new issue to track that, and ask for feedback there

  13. ghost added
    In-PR
    on Feb 26, 2023
  14. mklement0 commented on Feb 26, 2023

    @mklement0
    Contributor

    CarloToso,

    Based on my summary of what I think the issue is, and your confirmation of it as correct, I'm confused by the following sentence in the initial post:

    The charset in the headers should be ignored and default to UTF8

    To reconfirm: It should not be ignored, and should instead be honored, just like it already is for -ContentType, correct?


    Proceeding on the assumption that my summary is correct:

    A simple, setup-free way to verify that -ContentType is honored, but an equivalent Content-Type header field is not is via https://httpbin.org/post, which simply echoes the body back to you:

    • Given that UTF-8 is JSON's default, and that PowerShell now uses UTF-8 encoding by the default for a [string]-based -Body argument with content type application/json, the following works as expected:
    # Output: [pscustomobject] @{ foo = 'sß' }
    (Invoke-RestMethod https://httpbin.org/post -Body '{ "foo": "sß" }' -Method POST -ContentType application/json).json
    # NO output, because the effectively ISO-8859-1-encoded body cannot be decoded *as UTF8* by https://httpbin.org/post
    (Invoke-RestMethod https://httpbin.org/post -Body '{ "foo": "sß" }' -Method POST -ContentType 'application/json; charset=iso-8859-1').json
    • Trying to make the same intentional mistake with an equivalent Content-Type header field does NOT provoke the symptom, which implies that the charset attribute was ignored by PowerShell, and that UTF-8 was sent:
    # !! Output: [pscustomobject] @{ foo = 'sß' } - despite the attempt to send broken encoding
    # !! PowerShell *ignored* the 'charset' attribute.
    (Invoke-RestMethod https://httpbin.org/post -Body '{ "foo": "sß" }' -Method POST -Headers @{ 
      'Content-Type' = 'application/json; charset=iso-8859-1' 
    }).json
  15. CarloToso commented on Feb 26, 2023

    @CarloToso
    ContributorAuthor

    Michael Klement (@mklement0) Yes exactly, I'll edit the initial post to make it clearer

  16. ghost removed
    In-PR
    on Mar 1, 2023
  17. ghost added
    Resolution-Fixed
    on Mar 1, 2023
  18. ghost removed
    Needs-Triage
    on Mar 1, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution-Fixed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions