跳转至

清理敏感数据

Logfire SDK会先从日志和跨度中扫描并编辑可能敏感的数据,然后再导出它们。

禁用清理

要完全禁用清理,请将 scrubbing 设置为 False

import logfire

logfire.configure(scrubbing=False)

使用自定义模式进行更多清理

默认情况下,SDK 会查找一些敏感的正则表达式。要添加您自己的模式,请设置 extra_patterns 添加到正则表达式字符串列表:

import logfire

logfire.configure(scrubbing=logfire.ScrubbingOptions(extra_patterns=['my_pattern']))

logfire.info('Hello', data={
    'key_matching_my_pattern': 'This string will be redacted because its key matches',
    'other_key': 'This string will also be redacted because it matches MY_PATTERN case-insensitively',
    'password': 'This will be redacted because custom patterns are combined with the default patterns',
})

以下是默认的清理模式:

'password''passwd''mysql_pwd''secret''auth''credential''private[._ -]?key''api[._ -]?key''session''cookie''csrf''xsrf''jwt''ssn''social[._ -]?security''credit[._ -]?card'

使用回调减少清理

另一方面,如果清理是激进的,你可以将函数传递给 callback 以防止某些数据被编辑。

对于洗涤器找到的每个潜在匹配项,都将调用该函数。如果返回 None,则该值将被编辑。否则,返回的值将替换匹配的值。该函数接受 logfire.ScrubMatch

下面是一个示例:

import logfire

def scrubbing_callback(match: logfire.ScrubMatch):
    # 'my_safe_value' 通常包含字符串 'password',但它实际上并不敏感。
    if match.path == ('attributes', 'my_safe_value') and match.pattern_match.group(0) == 'password':
        # 返回原始值,防止脱敏。
        return match.value

logfire.configure(scrubbing=logfire.ScrubbingOptions(callback=scrubbing_callback))

安全提示

使用消息模板

不会清理完整的 span/log 消息,只会清理其中的字段。例如,以下:

logfire.info('用户详细信息: {user}', user=User(id=123, password='secret'))

...可能会记录如下内容:

用户详细信息:[由于“密码”而被清理]

...但是这个:

user = User(id=123, password='secret')
logfire.info('用户详细信息: ' + str(用户))

将记录:

用户详细信息:User(id=123, password='secret')

这是必要的,以便不会完全编辑“密码正确”等安全消息。

如果启用了 inspect_arguments(Python 3.11+ 中的默认值)并正常工作,则使用 f 字符串(例如 logfire.info(f'User details: {user}')))是安全的有关详细信息,请参阅此处

简而言之,不要自己设置消息的格式。出于其他原因,这通常也是一种良好做法。

将敏感数据排除在 URL 之外

OpenTelemetry 检测库记录的属性“http.url”被认为是安全的,因此不会编辑像“http://example.com/users/123/authenticate”这样的 URL。

作为一般规则,不仅针对 Logfire,还假设将记录 URL(包括查询参数),因此应将敏感数据放在请求正文或标头中。

使用参数化数据库查询

OpenTelemetry 数据库工具库记录的“db.statement”属性被认为是安全的,因此不会编辑像 “SELECT secret_value FROM table WHERE ...” 这样的 SQL 查询。

使用参数化查询(例如预准备语句),以便敏感数据不会直接插入到查询字符串中,即使您使用的插值方法不会受到 SQL 注入的影响。


本文总阅读量