credentials.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. package git
  2. /*
  3. credentials.go
  4. Per-user HTTPS credential storage.
  5. Tokens are encrypted with AES-256-GCM before they reach the system database.
  6. The key lives in a single 0600 file under the ArozOS system folder and is
  7. generated on first use, so a database dump alone never discloses anyone's
  8. personal access tokens.
  9. Keys are namespaced "<username>/<host>", meaning one ArozOS account can never
  10. read another's tokens even though both share the table.
  11. */
  12. import (
  13. "crypto/aes"
  14. "crypto/cipher"
  15. "crypto/rand"
  16. "encoding/base64"
  17. "encoding/json"
  18. "errors"
  19. "io"
  20. "os"
  21. "path/filepath"
  22. "sort"
  23. "strings"
  24. "sync"
  25. )
  26. // credentialTable is the system database table holding encrypted credentials.
  27. const credentialTable = "gitcredentials"
  28. // keyFileName is the AES key file created inside Options.KeyStorePath.
  29. const keyFileName = "credential.key"
  30. // CredentialDatabase is the slice of the ArozOS system database this package
  31. // needs. Declaring it as an interface keeps mod/git testable without a bolt
  32. // file and avoids a hard dependency on mod/database.
  33. type CredentialDatabase interface {
  34. NewTable(tableName string) error
  35. Write(tableName string, key string, value interface{}) error
  36. Read(tableName string, key string, assignee interface{}) error
  37. KeyExists(tableName string, key string) bool
  38. Delete(tableName string, key string) error
  39. ListTable(tableName string) ([][][]byte, error)
  40. }
  41. // storedCredential is the record persisted in the database. Only Token is
  42. // encrypted; the user name is stored in the clear so the UI can pre-fill it.
  43. type storedCredential struct {
  44. Host string `json:"host"`
  45. Username string `json:"username"`
  46. EncryptedToken string `json:"encryptedToken"` //base64(nonce || ciphertext)
  47. }
  48. // CredentialStore reads and writes encrypted git credentials.
  49. type CredentialStore struct {
  50. database CredentialDatabase
  51. key []byte
  52. mutex sync.RWMutex
  53. }
  54. // newCredentialStore prepares the table and loads (or creates) the AES key.
  55. func newCredentialStore(database CredentialDatabase, keyStorePath string) (*CredentialStore, error) {
  56. if database == nil {
  57. return nil, errors.New("credential store requires a database")
  58. }
  59. if strings.TrimSpace(keyStorePath) == "" {
  60. return nil, errors.New("credential store requires a key storage path")
  61. }
  62. if err := database.NewTable(credentialTable); err != nil {
  63. return nil, err
  64. }
  65. key, err := loadOrCreateKey(keyStorePath)
  66. if err != nil {
  67. return nil, err
  68. }
  69. return &CredentialStore{
  70. database: database,
  71. key: key,
  72. }, nil
  73. }
  74. // Save stores (or replaces) the credential for one user and host. An empty
  75. // token is rejected — the caller should call Remove instead.
  76. func (c *CredentialStore) Save(username string, host string, remoteUser string, token string) error {
  77. username = strings.TrimSpace(username)
  78. host = normaliseHost(host)
  79. if username == "" {
  80. return errors.New("credential owner cannot be empty")
  81. }
  82. if host == "" {
  83. return errors.New("credential host cannot be empty")
  84. }
  85. if strings.TrimSpace(token) == "" {
  86. return errors.New("credential token cannot be empty")
  87. }
  88. c.mutex.Lock()
  89. defer c.mutex.Unlock()
  90. encrypted, err := encryptSecret(c.key, token)
  91. if err != nil {
  92. return err
  93. }
  94. return c.database.Write(credentialTable, credentialKey(username, host), storedCredential{
  95. Host: host,
  96. Username: strings.TrimSpace(remoteUser),
  97. EncryptedToken: encrypted,
  98. })
  99. }
  100. // Get returns the stored credential for a user and host. The second return
  101. // value is false when nothing is stored.
  102. func (c *CredentialStore) Get(username string, host string) (*Credential, bool) {
  103. username = strings.TrimSpace(username)
  104. host = normaliseHost(host)
  105. if username == "" || host == "" {
  106. return nil, false
  107. }
  108. c.mutex.RLock()
  109. defer c.mutex.RUnlock()
  110. key := credentialKey(username, host)
  111. if !c.database.KeyExists(credentialTable, key) {
  112. return nil, false
  113. }
  114. record := storedCredential{}
  115. if err := c.database.Read(credentialTable, key, &record); err != nil {
  116. return nil, false
  117. }
  118. token, err := decryptSecret(c.key, record.EncryptedToken)
  119. if err != nil {
  120. //A key rotation or a corrupted record leaves an unusable entry. Report
  121. //it as missing so the UI asks for the credential again.
  122. return nil, false
  123. }
  124. return &Credential{
  125. Host: record.Host,
  126. Username: record.Username,
  127. Token: token,
  128. }, true
  129. }
  130. // List returns the hosts a user has credentials for, without any secrets.
  131. func (c *CredentialStore) List(username string) []Credential {
  132. username = strings.TrimSpace(username)
  133. results := []Credential{}
  134. if username == "" {
  135. return results
  136. }
  137. c.mutex.RLock()
  138. defer c.mutex.RUnlock()
  139. entries, err := c.database.ListTable(credentialTable)
  140. if err != nil {
  141. return results
  142. }
  143. prefix := username + "/"
  144. for _, entry := range entries {
  145. if len(entry) < 2 || !strings.HasPrefix(string(entry[0]), prefix) {
  146. continue
  147. }
  148. record := storedCredential{}
  149. if err := json.Unmarshal(entry[1], &record); err != nil {
  150. continue
  151. }
  152. results = append(results, Credential{
  153. Host: record.Host,
  154. Username: record.Username,
  155. })
  156. }
  157. sort.Slice(results, func(i, j int) bool {
  158. return results[i].Host < results[j].Host
  159. })
  160. return results
  161. }
  162. // Remove deletes a stored credential. Deleting a credential that is not there
  163. // is not an error.
  164. func (c *CredentialStore) Remove(username string, host string) error {
  165. username = strings.TrimSpace(username)
  166. host = normaliseHost(host)
  167. if username == "" || host == "" {
  168. return errors.New("owner and host are both required")
  169. }
  170. c.mutex.Lock()
  171. defer c.mutex.Unlock()
  172. key := credentialKey(username, host)
  173. if !c.database.KeyExists(credentialTable, key) {
  174. return nil
  175. }
  176. return c.database.Delete(credentialTable, key)
  177. }
  178. // ResolveForRemote looks up the credential matching a remote URL, which is what
  179. // every transport call needs before it can build an auth method.
  180. func (c *CredentialStore) ResolveForRemote(username string, remoteURL string) (*Credential, bool) {
  181. return c.Get(username, RemoteHost(remoteURL))
  182. }
  183. // credentialKey namespaces a record by its owning ArozOS account.
  184. func credentialKey(username string, host string) string {
  185. return username + "/" + host
  186. }
  187. // normaliseHost accepts either a bare host or a full remote URL and always
  188. // returns the lower-cased host, so "https://github.com/a/b.git" and "GitHub.com"
  189. // address the same record.
  190. func normaliseHost(host string) string {
  191. host = strings.TrimSpace(host)
  192. if host == "" {
  193. return ""
  194. }
  195. if strings.Contains(host, "://") || strings.Contains(host, "@") || strings.Contains(host, "/") {
  196. return RemoteHost(host)
  197. }
  198. //A bare "host:port" still needs the port dropped
  199. if index := strings.Index(host, ":"); index > 0 {
  200. host = host[:index]
  201. }
  202. return strings.ToLower(host)
  203. }
  204. // loadOrCreateKey reads the AES key from disk, generating a fresh 32-byte key
  205. // on first run.
  206. func loadOrCreateKey(keyStorePath string) ([]byte, error) {
  207. if err := os.MkdirAll(keyStorePath, 0700); err != nil {
  208. return nil, err
  209. }
  210. keyFile := filepath.Join(keyStorePath, keyFileName)
  211. if content, err := os.ReadFile(keyFile); err == nil {
  212. decoded, derr := base64.StdEncoding.DecodeString(strings.TrimSpace(string(content)))
  213. if derr == nil && len(decoded) == 32 {
  214. return decoded, nil
  215. }
  216. //Fall through and regenerate: a damaged key file only costs the user
  217. //their saved tokens, which the UI can ask for again.
  218. }
  219. key := make([]byte, 32)
  220. if _, err := rand.Read(key); err != nil {
  221. return nil, err
  222. }
  223. encoded := base64.StdEncoding.EncodeToString(key)
  224. if err := os.WriteFile(keyFile, []byte(encoded), 0600); err != nil {
  225. return nil, err
  226. }
  227. return key, nil
  228. }
  229. // encryptSecret seals plaintext with AES-GCM, returning base64(nonce||ciphertext).
  230. func encryptSecret(key []byte, plaintext string) (string, error) {
  231. block, err := aes.NewCipher(key)
  232. if err != nil {
  233. return "", err
  234. }
  235. aead, err := cipher.NewGCM(block)
  236. if err != nil {
  237. return "", err
  238. }
  239. nonce := make([]byte, aead.NonceSize())
  240. if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
  241. return "", err
  242. }
  243. sealed := aead.Seal(nonce, nonce, []byte(plaintext), nil)
  244. return base64.StdEncoding.EncodeToString(sealed), nil
  245. }
  246. // decryptSecret reverses encryptSecret.
  247. func decryptSecret(key []byte, encoded string) (string, error) {
  248. raw, err := base64.StdEncoding.DecodeString(encoded)
  249. if err != nil {
  250. return "", err
  251. }
  252. block, err := aes.NewCipher(key)
  253. if err != nil {
  254. return "", err
  255. }
  256. aead, err := cipher.NewGCM(block)
  257. if err != nil {
  258. return "", err
  259. }
  260. if len(raw) < aead.NonceSize() {
  261. return "", errors.New("stored credential is truncated")
  262. }
  263. nonce, ciphertext := raw[:aead.NonceSize()], raw[aead.NonceSize():]
  264. plaintext, err := aead.Open(nil, nonce, ciphertext, nil)
  265. if err != nil {
  266. return "", err
  267. }
  268. return string(plaintext), nil
  269. }