防止使用排除敏感属性的通用类型记录个人身份或敏感数据
我想通过编译时安全检查来增强我的记录器,以防止我记录个人身份或敏感数据。我想象的界面可能是这样的:
logger.LogInfo(safeuser => $"Logging out sensitive data @{safeuser.lastname}", user);
// Error: SafeToLog<User> does not contain a definition for 'lastname'
此行不应编译。
常规的 User
类具有属性 id
、firstname
、lastname
、createdAt
、< code>roleId、password
等。其中一些字段完全可以记录,例如 id
和 roleId
。不安全的记录将被标记为诸如 [PersonallyIdentifying]
或 [Secret]
之类的属性。
我想要像 SafeToLog
这样的类型,它具有用于 T 的每个安全记录属性的方法,但没有用于不安全记录属性的方法。因此,SafeToLog
应该具有属性 id
、createdAt
和 roleId
。它不应该具有属性 firstname
、lastname
或 password
。
是否可以实现 SafeToLog 类型?在 Typescript 中,我可以使用 Omit
辅助类型来构造它,但我不知道如何在 C# 中执行此操作。
此外,是否可以防止记录器的意外误用?在上面的示例中,粗心的开发人员仍然可以在日志字符串中引用 user
,忽略 safeuser
并绕过安全检查。我可以以某种方式强制在日志消息中仅引用 lambda 中提供的变量吗?
I want to enhance my logger with a compile-time safety check that prevents me from logging personally-identifying or sensitive data. Here's what I imagine the interface could look like:
logger.LogInfo(safeuser => quot;Logging out sensitive data @{safeuser.lastname}", user);
// Error: SafeToLog<User> does not contain a definition for 'lastname'
This line should not compile.
The regular User
class has properties id
, firstname
, lastname
, createdAt
, roleId
, password
etc. Some of those fields are perfectly fine to log, like id
and roleId
. The ones that are unsafe to log will be marked with attributes like [PersonallyIdentifying]
or [Secret]
.
I want a type like SafeToLog<T>
that has methods for every safe-to-log property of T, but no methods for the unsafe-to-log properties. So SafeToLog<User>
should have properties id
, createdAt
, and roleId
. It should NOT have properties firstname
, lastname
or password
.
Is it possible to implement the SafeToLog
type? In Typescript I could use the Omit
helper type to construct this, but I don't know how to do it in C#.
Furthermore, would it be possible to prevent accidental misuse of the logger? In the sample above, a careless developer could still refer to user
in the log string, ignoring safeuser
and bypassing the safety check. Can I somehow enforce that only the variables provided in the lambda are referenced in the log message?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论