python-3.x 云函数在获取KeyError“project”时崩溃

hivapdat  于 2023-03-04  发布在  Python
关注(0)|答案(1)|浏览(143)

创建了一个云功能,以启用来自谷歌支持文档的Webex通知的实时电子邮件和聊天通知,功能失败。
测试功能错误中的错误消息:函数终止。建议的操作:检查日志以查找终止原因。其他疑难解答文档可在www.example.com上找到详细信息:500内部服务器错误: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.
回溯严重性错误:"错误"文本有效载荷:"回溯(最近调用最后):文件"/layers/google. python. pip/pip/lib/python3.8/站点包/ flask /app. py ",第2073行,在wsgi_app响应= self. full_dispatch_request()文件"/layers/google. python. pip/pip/lib/python3.8/站点包/ flask /app. py",第1518行,在完整调度请求rv = self. handle_user_exception(e)文件"/layers/google. python. pip/pip/lib/python3.8/site-packages/flask/app.py "中,第1516行,在完整调度请求中rv =自我调度请求()文件"/layers/谷歌. Python. pip/pip/lib/Python 3.8/站点包/flask/app. py ",第1502行,在调度请求中返回自我确保同步(自我视图函数[规则端点])(**请求视图参数)文件"/layers/谷歌. Python. pip/pip/lib/Python 3.8/站点包/函数框架/init. py",第171行,在view_func函数(数据、上下文)文件"/工作空间/www.example.com "中,第60行,在send_webex_teams_notification_2023项目=资产["资源属性"]["项目"]中,按键错误:main.py", line 60, in send_webex_teams_notification_2023 project=asset["resourceProperties"]["project"], KeyError: 'project'"
我已尝试将"project"更改为project_id,尝试在requirements.txt文件中进行更改以升级安全命令中心的版本。我还尝试更改安全命令中心链接。我预计正在监视的组织级别中的所有项目都会出现严重错误,并向webex bot发送特定警报
代码
main.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}"},
    )

requirements.txt

requests==2.25.1
google-cloud-securitycenter==1.1.0
jslywgbw

jslywgbw1#

我不认为这是云函数的问题,更像是Python的问题。
当你得到一个键错误,这通常是由于试图访问一个字典中不存在的条目。
正如我们看到的,错误发生在这一行
project=asset["resourceProperties"]["project"]
这意味着资产['resourceProperties']没有项目索引。
我们可以看到资产来自

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

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

相关问题