feat: git credential backend for credential storage (#371)

## Problem

Credentials were stored as plaintext JSON in
`stdpath('data')/cp-nvim.json`, with no integration with system
credential managers.

## Solution

Replace file-based credential storage with `git credential
fill/approve/reject`, delegating to whatever credential helper the user
has configured (`cache`, `store`, `libsecret`, macOS Keychain, etc.).

- New `lua/cp/git_credential.lua` module wrapping the git credential
protocol
- All credential consumers (`credentials.lua`, `submit.lua`,
`scraper.lua`) use `git_credential` directly — `cache.lua` no longer
handles credentials
- CSES API token packed into the password field (`password<TAB>token`)
so it works with helpers that ignore the `path` field
- `has_helper()` guard on `:CP login`, `:CP logout`, and `:CP submit`
with an error message if no helper is configured
- Healthcheck split into `[required]`/`[optional]` sections; git version
and credential helper status shown
- `git` checked at startup in `check_required_runtime()`
- Cache version system (`CACHE_VERSION`, v1→v2 migration) removed — the
cache file is now a plain JSON blob
- `:CP` command gets `bar = true`
This commit is contained in:
Barrett Ruth 2026-03-07 20:15:06 -05:00 committed by GitHub
parent 27d7a4e6b5
commit da4e2ebeba
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 283 additions and 150 deletions

View file

@ -42,13 +42,10 @@
local M = {}
local CACHE_VERSION = 2
local cache_file = vim.fn.stdpath('data') .. '/cp-nvim.json'
local cache_data = {}
local loaded = false
--- Load the cache from disk if not done already
---@return nil
function M.load()
if loaded then
@ -56,8 +53,11 @@ function M.load()
end
if vim.fn.filereadable(cache_file) == 0 then
vim.fn.writefile({}, cache_file)
vim.fn.setfperm(cache_file, 'rw-------')
vim.fn.mkdir(vim.fn.fnamemodify(cache_file, ':h'), 'p')
local tmpfile = vim.fn.tempname()
vim.fn.writefile({}, tmpfile)
vim.fn.setfperm(tmpfile, 'rw-------')
vim.uv.fs_rename(tmpfile, cache_file)
loaded = true
return
end
@ -70,26 +70,7 @@ function M.load()
end
local ok, decoded = pcall(vim.json.decode, table.concat(content, '\n'))
if not ok then
cache_data = {}
M.save()
loaded = true
return
end
if decoded._version == 1 then
local old_creds = decoded._credentials
decoded._credentials = nil
if old_creds then
for platform, creds in pairs(old_creds) do
decoded[platform] = decoded[platform] or {}
decoded[platform]._credentials = creds
end
end
decoded._version = CACHE_VERSION
cache_data = decoded
M.save()
elseif decoded._version == CACHE_VERSION then
if ok and type(decoded) == 'table' then
cache_data = decoded
else
cache_data = {}
@ -98,17 +79,16 @@ function M.load()
loaded = true
end
--- Save the cache to disk, overwriting existing contents
---@return nil
function M.save()
vim.schedule(function()
vim.fn.mkdir(vim.fn.fnamemodify(cache_file, ':h'), 'p')
cache_data._version = CACHE_VERSION
local encoded = vim.json.encode(cache_data)
local lines = vim.split(encoded, '\n')
vim.fn.writefile(lines, cache_file)
vim.fn.setfperm(cache_file, 'rw-------')
local tmpfile = vim.fn.tempname()
vim.fn.writefile(lines, tmpfile)
vim.fn.setfperm(tmpfile, 'rw-------')
vim.uv.fs_rename(tmpfile, cache_file)
end)
end
@ -445,31 +425,6 @@ function M.get_contest_display_name(platform, contest_id)
return cache_data[platform][contest_id].display_name
end
---@param platform string
---@return table?
function M.get_credentials(platform)
if not cache_data[platform] then
return nil
end
return cache_data[platform]._credentials
end
---@param platform string
---@param creds table
function M.set_credentials(platform, creds)
cache_data[platform] = cache_data[platform] or {}
cache_data[platform]._credentials = creds
M.save()
end
---@param platform string
function M.clear_credentials(platform)
if cache_data[platform] then
cache_data[platform]._credentials = nil
end
M.save()
end
---@return nil
function M.clear_all()
cache_data = {}

View file

@ -1,7 +1,7 @@
local M = {}
local cache = require('cp.cache')
local constants = require('cp.constants')
local git_credential = require('cp.git_credential')
local logger = require('cp.log')
local state = require('cp.state')
@ -40,14 +40,14 @@ local function prompt_and_login(platform, display)
end, function(result)
vim.schedule(function()
if result.success then
cache.set_credentials(platform, credentials)
git_credential.store(platform, credentials)
logger.log(
display .. ' login successful',
{ level = vim.log.levels.INFO, override = true }
)
else
local err = result.error or 'unknown error'
cache.clear_credentials(platform)
git_credential.reject(platform, credentials)
logger.log(
display .. ' login failed: ' .. (constants.LOGIN_ERRORS[err] or err),
{ level = vim.log.levels.ERROR }
@ -71,10 +71,17 @@ function M.login(platform)
return
end
if not git_credential.has_helper() then
logger.log(
'No git credential helper configured. See :help cp-credentials',
{ level = vim.log.levels.ERROR }
)
return
end
local display = constants.PLATFORM_DISPLAY_NAMES[platform] or platform
cache.load()
local existing = cache.get_credentials(platform) or {}
local existing = git_credential.get(platform) or {}
if existing.username and existing.password then
local scraper = require('cp.scraper')
@ -91,7 +98,7 @@ function M.login(platform)
{ level = vim.log.levels.INFO, override = true }
)
else
cache.clear_credentials(platform)
git_credential.reject(platform, existing)
prompt_and_login(platform, display)
end
end)
@ -112,16 +119,28 @@ function M.logout(platform)
)
return
end
if not git_credential.has_helper() then
logger.log(
'No git credential helper configured. See :help cp-credentials',
{ level = vim.log.levels.ERROR }
)
return
end
local display = constants.PLATFORM_DISPLAY_NAMES[platform] or platform
cache.load()
cache.clear_credentials(platform)
local existing = git_credential.get(platform)
if existing then
git_credential.reject(platform, existing)
end
local cookie_file = constants.COOKIE_FILE
if vim.fn.filereadable(cookie_file) == 1 then
local ok, data = pcall(vim.fn.json_decode, vim.fn.readfile(cookie_file, 'b'))
if ok and type(data) == 'table' then
data[platform] = nil
vim.fn.writefile({ vim.fn.json_encode(data) }, cookie_file)
vim.fn.setfperm(cookie_file, 'rw-------')
local tmpfile = vim.fn.tempname()
vim.fn.writefile({ vim.fn.json_encode(data) }, tmpfile)
vim.fn.setfperm(tmpfile, 'rw-------')
vim.uv.fs_rename(tmpfile, cookie_file)
end
end
logger.log(display .. ' credentials cleared', { level = vim.log.levels.INFO, override = true })

107
lua/cp/git_credential.lua Normal file
View file

@ -0,0 +1,107 @@
---@class cp.Credentials
---@field username string
---@field password string
local M = {}
local HOSTS = {
atcoder = 'atcoder.jp',
codechef = 'www.codechef.com',
codeforces = 'codeforces.com',
cses = 'cses.fi',
kattis = 'open.kattis.com',
usaco = 'usaco.org',
}
local _helper_checked = false
local _helper_ok = false
---@return boolean
function M.has_helper()
if not _helper_checked then
local r = vim
.system({ 'git', 'config', 'credential.helper' }, { text = true, timeout = 5000 })
:wait()
_helper_ok = r.code == 0 and r.stdout ~= nil and vim.trim(r.stdout) ~= ''
_helper_checked = true
end
return _helper_ok
end
---@param host string
---@param extra? table<string, string>
---@return string
local function _build_input(host, extra)
local lines = { 'protocol=https', 'host=' .. host }
if extra then
for k, v in pairs(extra) do
table.insert(lines, k .. '=' .. v)
end
end
table.insert(lines, '')
table.insert(lines, '')
return table.concat(lines, '\n')
end
---@param stdout string
---@return table<string, string>
local function _parse_output(stdout)
local result = {}
for line in stdout:gmatch('[^\n]+') do
local k, v = line:match('^(%S+)=(.+)$')
if k and v then
result[k] = v
end
end
return result
end
---@param platform string
---@return cp.Credentials?
function M.get(platform)
local host = HOSTS[platform]
if not host then
return nil
end
local input = _build_input(host)
local obj = vim
.system({ 'git', 'credential', 'fill' }, { stdin = input, text = true, timeout = 5000 })
:wait()
if obj.code ~= 0 then
return nil
end
local parsed = _parse_output(obj.stdout or '')
if not parsed.username or not parsed.password then
return nil
end
return { username = parsed.username, password = parsed.password }
end
---@param platform string
---@param creds cp.Credentials
function M.store(platform, creds)
local host = HOSTS[platform]
if not host then
return
end
local input = _build_input(host, { username = creds.username, password = creds.password })
vim.system({ 'git', 'credential', 'approve' }, { stdin = input, text = true }):wait()
end
---@param platform string
---@param creds cp.Credentials
function M.reject(platform, creds)
local host = HOSTS[platform]
if not host or not creds then
return
end
local input = _build_input(host, { username = creds.username, password = creds.password })
vim.system({ 'git', 'credential', 'reject' }, { stdin = input, text = true }):wait()
end
return M

View file

@ -5,12 +5,12 @@ local utils = require('cp.utils')
local function check()
vim.health.start('cp.nvim [required] ~')
utils.setup_python_env()
local nvim_ver = vim.version()
local nvim_str = ('%d.%d.%d'):format(nvim_ver.major, nvim_ver.minor, nvim_ver.patch)
if vim.fn.has('nvim-0.10.0') == 1 then
vim.health.ok('Neovim 0.10.0+ detected')
vim.health.ok('Neovim >= 0.10.0: ' .. nvim_str)
else
vim.health.error('cp.nvim requires Neovim 0.10.0+')
vim.health.error('Neovim >= 0.10.0 required, found ' .. nvim_str)
end
local uname = vim.uv.os_uname()
@ -18,6 +18,24 @@ local function check()
vim.health.error('Windows is not supported')
end
local time_cap = utils.time_capability()
if time_cap.ok then
vim.health.ok('GNU time found: ' .. time_cap.path)
else
vim.health.error('GNU time not found: ' .. (time_cap.reason or ''))
end
local timeout_cap = utils.timeout_capability()
if timeout_cap.ok then
vim.health.ok('GNU timeout found: ' .. timeout_cap.path)
else
vim.health.error('GNU timeout not found: ' .. (timeout_cap.reason or ''))
end
vim.health.start('cp.nvim [optional] ~')
utils.setup_python_env()
if utils.is_nix_build() then
local source = utils.is_nix_discovered() and 'runtime discovery' or 'flake install'
vim.health.ok('Nix Python environment detected (' .. source .. ')')
@ -51,18 +69,30 @@ local function check()
end
end
local time_cap = utils.time_capability()
if time_cap.ok then
vim.health.ok('GNU time found: ' .. time_cap.path)
else
vim.health.error('GNU time not found: ' .. (time_cap.reason or ''))
end
if vim.fn.executable('git') == 1 then
local r = vim.system({ 'git', '--version' }, { text = true }):wait()
if r.code == 0 then
local major, minor, patch = r.stdout:match('(%d+)%.(%d+)%.(%d+)')
major, minor, patch = tonumber(major), tonumber(minor), tonumber(patch or 0)
local ver_str = ('%d.%d.%d'):format(major or 0, minor or 0, patch or 0)
if
major
and (major > 1 or (major == 1 and minor > 7) or (major == 1 and minor == 7 and patch >= 9))
then
vim.health.ok('git >= 1.7.9: ' .. ver_str)
else
vim.health.warn('git >= 1.7.9 required for credential storage, found ' .. ver_str)
end
end
local timeout_cap = utils.timeout_capability()
if timeout_cap.ok then
vim.health.ok('GNU timeout found: ' .. timeout_cap.path)
local helper = vim.system({ 'git', 'config', 'credential.helper' }, { text = true }):wait()
if helper.code == 0 and helper.stdout and vim.trim(helper.stdout) ~= '' then
vim.health.ok('git credential helper: ' .. vim.trim(helper.stdout))
else
vim.health.warn('no git credential helper configured (required for login/submit)')
end
else
vim.health.error('GNU timeout not found: ' .. (timeout_cap.reason or ''))
vim.health.warn('git not found (required for credential storage)')
end
end

View file

@ -347,7 +347,9 @@ function M.login(platform, credentials, on_status, callback)
stdin = vim.json.encode(credentials),
on_event = function(ev)
if ev.credentials ~= nil and next(ev.credentials) ~= nil then
require('cp.cache').set_credentials(platform, ev.credentials)
vim.schedule(function()
require('cp.git_credential').store(platform, ev.credentials)
end)
end
if ev.status ~= nil then
if type(on_status) == 'function' then
@ -395,7 +397,9 @@ function M.submit(
stdin = vim.json.encode(credentials),
on_event = function(ev)
if ev.credentials ~= nil and next(ev.credentials) ~= nil then
require('cp.cache').set_credentials(platform, ev.credentials)
vim.schedule(function()
require('cp.git_credential').store(platform, ev.credentials)
end)
end
if ev.status ~= nil then
if type(on_status) == 'function' then

View file

@ -1,8 +1,8 @@
local M = {}
local cache = require('cp.cache')
local config = require('cp.config')
local constants = require('cp.constants')
local git_credential = require('cp.git_credential')
local logger = require('cp.log')
local state = require('cp.state')
@ -14,7 +14,7 @@ local STATUS_MSGS = {
}
local function prompt_credentials(platform, callback)
local saved = cache.get_credentials(platform)
local saved = git_credential.get(platform)
if saved and saved.username and saved.password then
callback(saved)
return
@ -42,6 +42,14 @@ end
---@param opts { language?: string }?
function M.submit(opts)
if not git_credential.has_helper() then
logger.log(
'No git credential helper configured. See :help cp-credentials',
{ level = vim.log.levels.ERROR }
)
return
end
local platform = state.get_platform()
local contest_id = state.get_contest_id()
local problem_id = state.get_problem_id()
@ -109,12 +117,12 @@ function M.submit(opts)
function(result)
vim.schedule(function()
if result and result.success then
cache.set_credentials(platform, creds)
git_credential.store(platform, creds)
logger.log('Submitted successfully', { level = vim.log.levels.INFO, override = true })
else
local err = result and result.error or 'unknown error'
if err == 'bad_credentials' or err:match('^Login failed') then
cache.clear_credentials(platform)
git_credential.reject(platform, creds)
logger.log(
'Submit failed: ' .. (constants.LOGIN_ERRORS[err] or err),
{ level = vim.log.levels.ERROR }

View file

@ -366,6 +366,10 @@ function M.check_required_runtime()
return false, timeout.reason
end
if vim.fn.executable('git') ~= 1 then
return false, 'git is required for credential storage'
end
return true
end