如何设置缓存密码 1 小时但永不记住?

解读

面试官问的是“只把凭据在内存里放 1 小时,但绝对不要写磁盘”,也就是“临时缓存 ≠ 永久存储”。国内很多候选人把 git config --global credential.helper store 当成万能答案,结果把密码明文写死到 ~/.git-credentials,直接踩了安全红线。面试官想确认两点:

  1. 你知道 Git 凭据体系分“内存级”与“磁盘级”;
  2. 你能用“时效 + 不落地”的组合拳,既方便又安全。

知识点

  1. Git 凭据辅助工具(credential helper)优先级:
    先读 credential.helper → 再读 credential.<url>.helper → 命令行 -c 临时参数可覆盖全局。
  2. 官方自带两种常见 helper:
    cache:仅驻留内存,默认 15 min,可 --timeout <秒> 自定义。
    store:明文写 ~/.git-credentials,永久记住,不安全。
  3. 国内 Windows 用户装完 Git 后,默认被 Git-Credential-Manager(GCM)接管,会写 Windows 凭据管理器,也算“永久记住”。
  4. 面试常追问:
    “如果机器突然断电,缓存是否消失?”
    “如何针对单个仓库生效?”
    “CI 环境里无 TTY 怎么办?”

答案

在命令行给出一次性配置,既指定 1 小时缓存,又确保不落盘:

git config --global credential.helper 'cache --timeout=3600'

验证不会写入磁盘文件:

ls ~/.git-credentials        # 应提示不存在

若本机被 GCM 或 store 污染过,先显式卸载它们:

git config --global --unset-all credential.helper
git config --global credential.helper 'cache --timeout=3600'

针对单个仓库临时生效(面试加分项):

cd your_repo
git config credential.helper 'cache --timeout=3600'

这样 3600 秒内再次 git fetch / push 无需输入密码,进程退出或超时后凭据自动消失,满足“1 小时缓存 + 永不记住”。

拓展思考

  1. 多人共用跳板机场景:
    把 cache --timeout 放到 /etc/gitconfig,强制所有人不落盘,避免“某人手滑用了 store”导致密码泄漏。
  2. CI/CD 无交互:
    缓存 helper 需要 TTY,CI 里应改用 GIT_ASKPASS 脚本或一次性 token,而不是 cache。
  3. 超过 1 小时仍想免密:
    不延长 cache,而是换用 SSH + ed25519 密钥,把公钥放到代码平台,既免密又无痕。
  4. 面试反向提问:
    “贵公司安全规范是否允许凭据落盘?如果允许,采用 GCM 还是自研 Vault 插件?” 体现你对企业级合规的关注。