云函数崩溃并出现 KeyError“project”

问题描述 投票:0回答:1

创建了一个云功能,为来自 google 支持文档的 webex 通知启用实时电子邮件和聊天通知,但功能失败。

Error Message in Test Function
Error: function terminated. Recommended action: inspect logs for termination reason. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging Details:
500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

Error in traceback
severity: "ERROR"
textPayload: "Traceback (most recent call last):
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 2073, in    wsgi_app
      response = self.full_dispatch_request()
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 1518, in full_dispatch_request
      rv = self.handle_user_exception(e)
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 1516, in full_dispatch_request
      rv = self.dispatch_request()
      File "/layers/google.python.pip/pip/lib/python3.8/site-packages/flask/app.py", line 1502, in dispatch_request
      return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
      File "/layers/google.python.pip/pip/lib/python3.8/site- packages/functions_framework/__init__.py", line 171, in view_func
      function(data, context)
      File "/workspace/main.py", line 60, in send_webex_teams_notification_2023
      project=asset["resourceProperties"]["project"],
      KeyError: 'project'"

我尝试将“项目”更改为project_id,我尝试更改requirements.txt文件以升级安全命令中心的版本。我还尝试更改安全命令中心链接。我预计正在监控的组织级别的所有项目都会出现高错误或严重错误,并向 webex 机器人发送特定警报

代码

主.py

#!/usr/bin/env python3
import base64
import json

import requests
from google.cloud import securitycenter_v1

WEBEX_TOKEN = "N2YzYjk0NmItNDAxMS00MzdlLWE4MjMtYzFlNGNkNjYxODBmNDZhNWNiOTktOTgx_PF84_e7a300f8-3aac-4db0-9c42-848488a96bf4"
ROOM_ID = "Y2lzY29zcGFyazovL3VzL1JPT00vNmE1MWEwOTAtYWM3Yy0xMWVkLTkxMDQtYzE1YzVmZDEyMTFi"

TEMPLATE = """
**Severity:** {severity}\n
**Asset:** {asset}\n
**SCC Category:** {category}\n
**Project:** {project}\n
**First observed:** {create_time}\n
**Last observed:** {event_time}\n
**Link to finding:** {finding_link}

“”“

PREFIX = "https://console.cloud.google.com/security/command-center/findings"

def get_finding_detail_page_link(finding_name):
    """Constructs a direct link to the finding detail page."""
    org_id = finding_name.split("/")[1]
    return f"{PREFIX}?organizationId={org_id}&resourceId={finding_name}"

def get_asset(parent, resource_name):
    """Retrieves the asset corresponding to `resource_name` from SCC."""
    client = securitycenter_v1.SecurityCenterClient()
    resp = client.list_assets(
        securitycenter_v1.ListAssetsRequest(
            parent=parent,
            filter=f'securityCenterProperties.resourceName="{resource_name}"',
        )
    )
    page = next(resp.pages)
    if page.total_size == 0:
        return None
    asset = page.list_assets_results[0].asset
    return json.loads(securitycenter_v1.Asset.to_json(asset))

def send_webex_teams_notification(event, context):
    """Send the notification to WebEx Teams."""
    pubsub_message = base64.b64decode(event["data"]).decode("utf-8")
    message_json = json.loads(pubsub_message)
    finding = message_json["finding"]

    parent = "/".join(finding["parent"].split("/")[0:2])
    asset = get_asset(parent, finding["resourceName"])

    requests.post(
        "https://webexapis.com/v1/messages",
        json={
            "roomId": ROOM_ID,
            "markdown": TEMPLATE.format(
                severity=finding["severity"],
                asset=asset["securityCenterProperties"]["resourceDisplayName"],
                category=finding["category"],
                project=asset["resourceProperties"]["project"],
                create_time=finding["createTime"],
                event_time=finding["eventTime"],
                finding_link=get_finding_detail_page_link(finding["name"]),
            ),
        },
        headers={"Authorization": f"Bearer {WEBEX_TOKEN}"},
    )

需求.txt

requests==2.25.1
google-cloud-securitycenter==1.1.0
python-3.x google-cloud-functions
1个回答
0
投票

我不认为这是 Cloud Functions 的问题,更重要的是 Python 的问题。

当您收到密钥错误时,这通常是由于尝试访问字典中不存在的项目所致。

所以我们看到错误发生在这一行

project=asset["resourceProperties"]["project"]

这意味着 asset['resourceProperties'] 没有项目索引。

我们可以看到Asset来自

message_json = json.loads(pubsub_message)
finding = message_json["finding"]
parent = "/".join(finding["parent"].split("/")[0:2])
asset = get_asset(parent, finding["resourceName"])

由于有数据被拉入并连接,因此数据很可能嵌套在其他内容下。你输出数据来看看它的结构吗?您能否为我们显示资产内容,也许我们可以帮助查找项目索引?

© www.soinside.com 2019 - 2024. All rights reserved.