为 mitmproxy 设置 modify-body 选项时是否可以使用捕获组代替?

Is it possible to use captured group in replacement when setting modify-body option for mitmproxy?

我想修改响应正文,一个 json 字符串来为当前用户附加额外的站点信息。例如,原始正文可能如下所示。

[
  {
    "provider_assignments":[
      {
        "user_uuid":"c2d18512-298d-4035-9068-123cabdd2cd4",
        "environment":{
          "uuid":"b4156425-1afd-40ef-a3af-00e2887f7c91",
          "name":"Flik_Test (DEV)"
        },
        "roles":[
          {
            "oid":"SITEMODE",
            "name":"Site Mode User"
          }
        ],
        "sites":[
          {
            "uuid":"c7e56fb2-d93e-4d61-9822-805643c0773e",
            "name":"Shanghai Office"
          }
        ]
      }
    ],
    ...
  }
]

我希望正文可以修改如下。

[
  {
    "provider_assignments":[
      {
        "user_uuid":"c2d18512-298d-4035-9068-123cabdd2cd4",
        "environment":{
          "uuid":"ffb520d4-09fb-45b5-a292-b31fcfdeb2e6",
          "name":"ACE-536-MDS-002"
        },
        "roles":[
          {
            "oid":"SITEMODE",
            "name":"Site Mode User"
          }
        ],
        "sites":[
          {
            "uuid":"e83ff461-756d-43e6-8129-210fa065be41",
            "name":"Cabrini Hospital"
          }
        ]
      },
      {
        "user_uuid":"c2d18512-298d-4035-9068-123cabdd2cd4",
        "environment":{
          "uuid":"b4156425-1afd-40ef-a3af-00e2887f7c91",
          "name":"Flik_Test (DEV)"
        },
        "roles":[
          {
            "oid":"SITEMODE",
            "name":"Site Mode User"
          }
        ],
        "sites":[
          {
            "uuid":"c7e56fb2-d93e-4d61-9822-805643c0773e",
            "name":"Shanghai Office"
          }
        ]
      }
    ],
    ...
  }
]

但是,当另一个用户登录时 user_uuid 会有所不同,我在添加 modify-body 选项时尝试使用正则表达式。我尝试了 </code>、<code>$1</code> 和 <code>\1,但运气不好,其中 none 有效。

--modify-body "/~d test\.com & ~bs provider_assignments/\"provider_assignments\":\[\{\"user_uuid\":\"([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\"/\"provider_assignments\":[{\"user_uuid\":\"\",\"environment\":{\"uuid\":\"ffb520d4-09fb-45b5-a292-b31fcfdeb2e6\",\"name\":\"ACE-536-MDS-002\"},\"roles\":[{\"oid\":\"SITEMODE\",\"name\":\"Site Mode User\"}],\"sites\":[{\"uuid\":\"e83ff461-756d-43e6-8129-210fa065be41\",\"name\":\"Cabrini Hospital\"}]},{\"user_uuid\":\"\""

请指教。非常感谢。

使用python regex instantly replace groups中提到的组引用语法,组引用应该像\g<1>那么它完美地解决了我的问题。

对于这个特定的用例,我建议您编写自己的插件来直接修改 JSON 内容。未经测试,但类似以下内容应该有效:

import json
from mitmproxy import http

def response(flow: http.HTTPFlow):
    data = flow.response.json()

    data["foo"] = "bar"  # modify your JSON data with custom Python code.

    flow.response.text = json.dumps(data)