drob50257447 2017-11-27 10:07
浏览 59
已采纳

不要在日志中打印秘密

I am using Zap logger and I want to limit the information that gets logged. For example , I have below code snippet

func (m *mountCommand) Execute(args []string) error {

    filelogger.Info("First log", zap.Strings("input args", args))

And the log output is as below

    {"level":"info","ts":"2017-11-16T10:04:40.225Z","msg":"First log","input args":["/var/lib/kubelet/pods/74785895-cab5-11e7-88ed-ce1c8b57856c/volumes/xyz-xandndnd",
    "{\"kubernetes.io/secret/access-key\":\"Qdfnnfbbdnsjnxni8ehh=\",\"kubernetes.io/secret/secret-key\":\"GGHNHwsffUIJMNBNBVV==\",
\"parallel-count\":\"5\",\"region\":\"iam-standard\"}"]}

How do I just prevent the access-key and secret-key values from getting added to the log due to sensitivity of the data.

I tried many string manipulation functions in Go so that I can just remove those contents before using the zap object.There seems no simple function to get this done in a straight forward simple way.

  • 写回答

1条回答 默认 最新

  • douyi3307 2017-11-27 11:50
    关注

    Your current args is a slice of the following strings:

    /var/lib/kubelet/pods/74785895-cab5-11e7-88ed-ce1c8b57856c/volumes/xyz-xandndnd
    {"kubernetes.io/secret/access-key":"Qdfnnfbbdnsjnxni8ehh=","kubernetes.io/secret/secret-key":"GGHNHwsffUIJMNBNBVV==","parallel-count":"5","region":"iam-standard"}
    

    The input argument that contains the security-sensitive data is at index 1, and it's a JSON text.

    You should not "string-manipulate" a JSON text. First you should unmarshal it into a Go value, then manipulate it, then marshal it back.

    This is how this can be done:

    // Make a copy of args:
    args2 := append([]string{}, args...)
    
    // Unmarshal:
    var m map[string]interface{}
    if err := json.Unmarshal([]byte(args2[1]), &m); err != nil {
        panic(err)
    }
    
    // Modify:
    m["kubernetes.io/secret/access-key"] = "XXX"
    m["kubernetes.io/secret/secret-key"] = "YYY"
    
    // Marshal:
    s2, err := json.Marshal(m)
    if err != nil {
        panic(err)
    }
    args2[1] = string(s2)
    
    // Verify:
    fmt.Println(args2[1])
    
    // Now use args2 to log
    filelogger.Info("First log", zap.Strings("(masked) input args", args2))
    

    The "Verify:" is obviously not needed, it's just for us to see the result. Output on the Go Playground:

    {"kubernetes.io/secret/access-key":"XXX","kubernetes.io/secret/secret-key":"YYY","parallel-count":"5","region":"iam-standard"}
    

    In your solution you should also add slice index checks to avoid run-time panic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型