ssh_key.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. package database
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/binary"
  6. "fmt"
  7. "math/big"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/cockroachdb/errors"
  15. "github.com/unknwon/com"
  16. "golang.org/x/crypto/ssh"
  17. "gorm.io/gorm"
  18. log "unknwon.dev/clog/v2"
  19. "gogs.io/gogs/internal/conf"
  20. "gogs.io/gogs/internal/errutil"
  21. "gogs.io/gogs/internal/process"
  22. )
  23. const (
  24. tplPublicKey = `command="%s serv key-%d --config='%s'",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
  25. )
  26. var sshOpLocker sync.Mutex
  27. type KeyType int
  28. const (
  29. KeyTypeUser = iota + 1
  30. KeyTypeDeploy
  31. )
  32. // PublicKey represents a user or deploy SSH public key.
  33. type PublicKey struct {
  34. ID int64 `gorm:"primaryKey"`
  35. OwnerID int64 `gorm:"index;not null"`
  36. Name string `gorm:"not null"`
  37. Fingerprint string `gorm:"not null"`
  38. Content string `gorm:"type:text;not null"`
  39. Mode AccessMode `gorm:"not null;default:2"`
  40. Type KeyType `gorm:"not null;default:1"`
  41. Created time.Time `gorm:"-" json:"-"`
  42. CreatedUnix int64
  43. Updated time.Time `gorm:"-" json:"-"` // Note: Updated must below Created for AfterFind.
  44. UpdatedUnix int64
  45. HasRecentActivity bool `gorm:"-" json:"-"`
  46. HasUsed bool `gorm:"-" json:"-"`
  47. }
  48. func (k *PublicKey) BeforeCreate(tx *gorm.DB) error {
  49. if k.CreatedUnix == 0 {
  50. k.CreatedUnix = tx.NowFunc().Unix()
  51. }
  52. return nil
  53. }
  54. func (k *PublicKey) BeforeUpdate(tx *gorm.DB) error {
  55. k.UpdatedUnix = tx.NowFunc().Unix()
  56. return nil
  57. }
  58. func (k *PublicKey) AfterFind(tx *gorm.DB) error {
  59. k.Created = time.Unix(k.CreatedUnix, 0).Local()
  60. if k.UpdatedUnix > 0 {
  61. k.Updated = time.Unix(k.UpdatedUnix, 0).Local()
  62. k.HasUsed = k.Updated.After(k.Created)
  63. k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(tx.NowFunc())
  64. }
  65. return nil
  66. }
  67. // OmitEmail returns content of public key without email address.
  68. func (k *PublicKey) OmitEmail() string {
  69. return strings.Join(strings.Split(k.Content, " ")[:2], " ")
  70. }
  71. // AuthorizedString returns formatted public key string for authorized_keys file.
  72. func (k *PublicKey) AuthorizedString() string {
  73. return fmt.Sprintf(tplPublicKey, conf.AppPath(), k.ID, conf.CustomConf, k.Content)
  74. }
  75. // IsDeployKey returns true if the public key is used as deploy key.
  76. func (k *PublicKey) IsDeployKey() bool {
  77. return k.Type == KeyTypeDeploy
  78. }
  79. func extractTypeFromBase64Key(key string) (string, error) {
  80. b, err := base64.StdEncoding.DecodeString(key)
  81. if err != nil || len(b) < 4 {
  82. return "", errors.Newf("invalid key format: %v", err)
  83. }
  84. keyLength := int(binary.BigEndian.Uint32(b))
  85. if len(b) < 4+keyLength {
  86. return "", errors.Newf("invalid key format: not enough length %d", keyLength)
  87. }
  88. return string(b[4 : 4+keyLength]), nil
  89. }
  90. // parseKeyString parses any key string in OpenSSH or SSH2 format to clean OpenSSH string (RFC4253).
  91. func parseKeyString(content string) (string, error) {
  92. // Transform all legal line endings to a single "\n"
  93. // Replace all windows full new lines ("\r\n")
  94. content = strings.ReplaceAll(content, "\r\n", "\n")
  95. // Replace all windows half new lines ("\r"), if it happen not to match replace above
  96. content = strings.ReplaceAll(content, "\r", "\n")
  97. // Replace ending new line as its may cause unwanted behaviour (extra line means not a single line key | OpenSSH key)
  98. content = strings.TrimRight(content, "\n")
  99. // split lines
  100. lines := strings.Split(content, "\n")
  101. var keyType, keyContent, keyComment string
  102. if len(lines) == 1 {
  103. // Parse OpenSSH format.
  104. parts := strings.SplitN(lines[0], " ", 3)
  105. switch len(parts) {
  106. case 0:
  107. return "", errors.New("empty key")
  108. case 1:
  109. keyContent = parts[0]
  110. case 2:
  111. keyType = parts[0]
  112. keyContent = parts[1]
  113. default:
  114. keyType = parts[0]
  115. keyContent = parts[1]
  116. keyComment = parts[2]
  117. }
  118. // If keyType is not given, extract it from content. If given, validate it.
  119. t, err := extractTypeFromBase64Key(keyContent)
  120. if err != nil {
  121. return "", errors.Newf("extractTypeFromBase64Key: %v", err)
  122. }
  123. if keyType == "" {
  124. keyType = t
  125. } else if keyType != t {
  126. return "", errors.Newf("key type and content does not match: %s - %s", keyType, t)
  127. }
  128. } else {
  129. // Parse SSH2 file format.
  130. continuationLine := false
  131. for _, line := range lines {
  132. // Skip lines that:
  133. // 1) are a continuation of the previous line,
  134. // 2) contain ":" as that are comment lines
  135. // 3) contain "-" as that are begin and end tags
  136. if continuationLine || strings.ContainsAny(line, ":-") {
  137. continuationLine = strings.HasSuffix(line, "\\")
  138. } else {
  139. keyContent = keyContent + line
  140. }
  141. }
  142. t, err := extractTypeFromBase64Key(keyContent)
  143. if err != nil {
  144. return "", errors.Newf("extractTypeFromBase64Key: %v", err)
  145. }
  146. keyType = t
  147. }
  148. return keyType + " " + keyContent + " " + keyComment, nil
  149. }
  150. // writeTmpKeyFile writes key content to a temporary file
  151. // and returns the name of that file, along with any possible errors.
  152. func writeTmpKeyFile(content string) (string, error) {
  153. tmpFile, err := os.CreateTemp(conf.SSH.KeyTestPath, "gogs_keytest")
  154. if err != nil {
  155. return "", errors.Newf("TempFile: %v", err)
  156. }
  157. defer tmpFile.Close()
  158. if _, err = tmpFile.WriteString(content); err != nil {
  159. return "", errors.Newf("WriteString: %v", err)
  160. }
  161. return tmpFile.Name(), nil
  162. }
  163. // SSHKeyGenParsePublicKey extracts key type and length using ssh-keygen.
  164. func SSHKeyGenParsePublicKey(key string) (string, int, error) {
  165. tmpName, err := writeTmpKeyFile(key)
  166. if err != nil {
  167. return "", 0, errors.Newf("writeTmpKeyFile: %v", err)
  168. }
  169. defer os.Remove(tmpName)
  170. stdout, stderr, err := process.Exec("SSHKeyGenParsePublicKey", conf.SSH.KeygenPath, "-lf", tmpName)
  171. if err != nil {
  172. return "", 0, errors.Newf("fail to parse public key: %s - %s", err, stderr)
  173. }
  174. if strings.Contains(stdout, "is not a public key file") {
  175. return "", 0, ErrKeyUnableVerify{stdout}
  176. }
  177. fields := strings.Split(stdout, " ")
  178. if len(fields) < 4 {
  179. return "", 0, errors.Newf("invalid public key line: %s", stdout)
  180. }
  181. keyType := strings.Trim(fields[len(fields)-1], "()\r\n")
  182. return strings.ToLower(keyType), com.StrTo(fields[0]).MustInt(), nil
  183. }
  184. // SSHNativeParsePublicKey extracts the key type and length using the golang SSH library.
  185. func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
  186. fields := strings.Fields(keyLine)
  187. if len(fields) < 2 {
  188. return "", 0, errors.Newf("not enough fields in public key line: %s", keyLine)
  189. }
  190. raw, err := base64.StdEncoding.DecodeString(fields[1])
  191. if err != nil {
  192. return "", 0, err
  193. }
  194. pkey, err := ssh.ParsePublicKey(raw)
  195. if err != nil {
  196. if strings.Contains(err.Error(), "ssh: unknown key algorithm") {
  197. return "", 0, ErrKeyUnableVerify{err.Error()}
  198. }
  199. return "", 0, errors.Newf("ParsePublicKey: %v", err)
  200. }
  201. // The ssh library can parse the key, so next we find out what key exactly we have.
  202. switch pkey.Type() {
  203. case ssh.KeyAlgoDSA:
  204. rawPub := struct {
  205. Name string
  206. P, Q, G, Y *big.Int
  207. }{}
  208. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  209. return "", 0, err
  210. }
  211. // as per https://bugzilla.mindrot.org/show_bug.cgi?id=1647 we should never
  212. // see dsa keys != 1024 bit, but as it seems to work, we will not check here
  213. return "dsa", rawPub.P.BitLen(), nil // use P as per crypto/dsa/dsa.go (is L)
  214. case ssh.KeyAlgoRSA:
  215. rawPub := struct {
  216. Name string
  217. E *big.Int
  218. N *big.Int
  219. }{}
  220. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  221. return "", 0, err
  222. }
  223. return "rsa", rawPub.N.BitLen(), nil // use N as per crypto/rsa/rsa.go (is bits)
  224. case ssh.KeyAlgoECDSA256:
  225. return "ecdsa", 256, nil
  226. case ssh.KeyAlgoECDSA384:
  227. return "ecdsa", 384, nil
  228. case ssh.KeyAlgoECDSA521:
  229. return "ecdsa", 521, nil
  230. case ssh.KeyAlgoED25519:
  231. return "ed25519", 256, nil
  232. }
  233. return "", 0, errors.Newf("unsupported key length detection for type: %s", pkey.Type())
  234. }
  235. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  236. // It returns the actual public key line on success.
  237. func CheckPublicKeyString(content string) (_ string, err error) {
  238. if conf.SSH.Disabled {
  239. return "", errors.New("SSH is disabled")
  240. }
  241. content, err = parseKeyString(content)
  242. if err != nil {
  243. return "", err
  244. }
  245. content = strings.TrimRight(content, "\n\r")
  246. if strings.ContainsAny(content, "\n\r") {
  247. return "", errors.New("only a single line with a single key please")
  248. }
  249. // Remove any unnecessary whitespace
  250. content = strings.TrimSpace(content)
  251. if !conf.SSH.MinimumKeySizeCheck {
  252. return content, nil
  253. }
  254. var (
  255. fnName string
  256. keyType string
  257. length int
  258. )
  259. if conf.SSH.StartBuiltinServer {
  260. fnName = "SSHNativeParsePublicKey"
  261. keyType, length, err = SSHNativeParsePublicKey(content)
  262. } else {
  263. fnName = "SSHKeyGenParsePublicKey"
  264. keyType, length, err = SSHKeyGenParsePublicKey(content)
  265. }
  266. if err != nil {
  267. return "", errors.Newf("%s: %v", fnName, err)
  268. }
  269. log.Trace("Key info [native: %v]: %s-%d", conf.SSH.StartBuiltinServer, keyType, length)
  270. if minLen, found := conf.SSH.MinimumKeySizes[keyType]; found && length >= minLen {
  271. return content, nil
  272. } else if found && length < minLen {
  273. return "", errors.Newf("key length is not enough: got %d, needs %d", length, minLen)
  274. }
  275. return "", errors.Newf("key type is not allowed: %s", keyType)
  276. }
  277. // appendAuthorizedKeysToFile appends new SSH keys' content to authorized_keys file.
  278. func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
  279. sshOpLocker.Lock()
  280. defer sshOpLocker.Unlock()
  281. fpath := filepath.Join(conf.SSH.RootPath, "authorized_keys")
  282. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
  283. if err != nil {
  284. return err
  285. }
  286. defer f.Close()
  287. // Note: chmod command does not support in Windows.
  288. if !conf.IsWindowsRuntime() {
  289. fi, err := f.Stat()
  290. if err != nil {
  291. return err
  292. }
  293. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  294. if fi.Mode().Perm() > 0o600 {
  295. log.Error("authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  296. if err = f.Chmod(0o600); err != nil {
  297. return err
  298. }
  299. }
  300. }
  301. for _, key := range keys {
  302. if _, err = f.WriteString(key.AuthorizedString()); err != nil {
  303. return err
  304. }
  305. }
  306. return nil
  307. }
  308. // checkKeyContent onlys checks if key content has been used as public key,
  309. // it is OK to use same key as deploy key for multiple repositories/users.
  310. func checkKeyContent(content string) error {
  311. err := db.Where("content = ? AND type = ?", content, KeyTypeUser).First(&PublicKey{}).Error
  312. if err == nil {
  313. return ErrKeyAlreadyExist{0, content}
  314. } else if !errors.Is(err, gorm.ErrRecordNotFound) {
  315. return err
  316. }
  317. return nil
  318. }
  319. func addKey(tx *gorm.DB, key *PublicKey) (err error) {
  320. // Calculate fingerprint.
  321. tmpPath := strings.ReplaceAll(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()), "id_rsa.pub"), "\\", "/")
  322. _ = os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  323. if err = os.WriteFile(tmpPath, []byte(key.Content), 0o644); err != nil {
  324. return err
  325. }
  326. stdout, stderr, err := process.Exec("AddPublicKey", conf.SSH.KeygenPath, "-lf", tmpPath)
  327. if err != nil {
  328. return errors.Newf("fail to parse public key: %s - %s", err, stderr)
  329. } else if len(stdout) < 2 {
  330. return errors.New("not enough output for calculating fingerprint: " + stdout)
  331. }
  332. key.Fingerprint = strings.Split(stdout, " ")[1]
  333. // Save SSH key.
  334. if err = tx.Create(key).Error; err != nil {
  335. return err
  336. }
  337. // Don't need to rewrite this file if builtin SSH server is enabled.
  338. if conf.SSH.StartBuiltinServer {
  339. return nil
  340. }
  341. return appendAuthorizedKeysToFile(key)
  342. }
  343. // AddPublicKey adds new public key to database and authorized_keys file.
  344. func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
  345. log.Trace("Add public key: %s", content)
  346. if err := checkKeyContent(content); err != nil {
  347. return nil, err
  348. }
  349. // Key name of same user cannot be duplicated.
  350. err := db.Where("owner_id = ? AND name = ?", ownerID, name).First(new(PublicKey)).Error
  351. if err == nil {
  352. return nil, ErrKeyNameAlreadyUsed{ownerID, name}
  353. } else if !errors.Is(err, gorm.ErrRecordNotFound) {
  354. return nil, err
  355. }
  356. key := &PublicKey{
  357. OwnerID: ownerID,
  358. Name: name,
  359. Content: content,
  360. Mode: AccessModeWrite,
  361. Type: KeyTypeUser,
  362. }
  363. err = db.Transaction(func(tx *gorm.DB) error {
  364. return addKey(tx, key)
  365. })
  366. if err != nil {
  367. return nil, errors.Newf("addKey: %v", err)
  368. }
  369. return key, nil
  370. }
  371. // GetPublicKeyByID returns public key by given ID.
  372. func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
  373. key := new(PublicKey)
  374. err := db.Where("id = ?", keyID).First(key).Error
  375. if err != nil {
  376. if errors.Is(err, gorm.ErrRecordNotFound) {
  377. return nil, ErrKeyNotExist{keyID}
  378. }
  379. return nil, err
  380. }
  381. return key, nil
  382. }
  383. // SearchPublicKeyByContent searches a public key using the content as prefix
  384. // (i.e. ignore the email part). It returns ErrKeyNotExist if no such key
  385. // exists.
  386. func SearchPublicKeyByContent(content string) (*PublicKey, error) {
  387. key := new(PublicKey)
  388. err := db.Where("content LIKE ?", content+"%").First(key).Error
  389. if err != nil {
  390. if errors.Is(err, gorm.ErrRecordNotFound) {
  391. return nil, ErrKeyNotExist{}
  392. }
  393. return nil, err
  394. }
  395. return key, nil
  396. }
  397. // ListPublicKeys returns a list of public keys belongs to given user.
  398. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  399. keys := make([]*PublicKey, 0, 5)
  400. return keys, db.Where("owner_id = ?", uid).Find(&keys).Error
  401. }
  402. // UpdatePublicKey updates given public key.
  403. func UpdatePublicKey(key *PublicKey) error {
  404. return db.Model(key).Where("id = ?", key.ID).Updates(key).Error
  405. }
  406. // deletePublicKeys does the actual key deletion but does not update authorized_keys file.
  407. func deletePublicKeys(tx *gorm.DB, keyIDs ...int64) error {
  408. if len(keyIDs) == 0 {
  409. return nil
  410. }
  411. return tx.Where("id IN ?", keyIDs).Delete(new(PublicKey)).Error
  412. }
  413. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  414. func DeletePublicKey(doer *User, id int64) (err error) {
  415. key, err := GetPublicKeyByID(id)
  416. if err != nil {
  417. if IsErrKeyNotExist(err) {
  418. return nil
  419. }
  420. return errors.Newf("GetPublicKeyByID: %v", err)
  421. }
  422. // Check if user has access to delete this key.
  423. if !doer.IsAdmin && doer.ID != key.OwnerID {
  424. return ErrKeyAccessDenied{doer.ID, key.ID, "public"}
  425. }
  426. err = db.Transaction(func(tx *gorm.DB) error {
  427. return deletePublicKeys(tx, id)
  428. })
  429. if err != nil {
  430. return err
  431. }
  432. return RewriteAuthorizedKeys()
  433. }
  434. // RewriteAuthorizedKeys removes any authorized key and rewrite all keys from database again.
  435. // Note: x.Iterate does not get latest data after insert/delete, so we have to call this function
  436. // outside any session scope independently.
  437. //
  438. // Deprecated: Use PublicKeys.RewriteAuthorizedKeys instead.
  439. func RewriteAuthorizedKeys() error {
  440. sshOpLocker.Lock()
  441. defer sshOpLocker.Unlock()
  442. log.Trace("Doing: RewriteAuthorizedKeys")
  443. _ = os.MkdirAll(conf.SSH.RootPath, os.ModePerm)
  444. fpath := authorizedKeysPath()
  445. tmpPath := fpath + ".tmp"
  446. f, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
  447. if err != nil {
  448. return err
  449. }
  450. defer os.Remove(tmpPath)
  451. // Use FindInBatches to process keys in chunks to avoid memory issues with large datasets
  452. err = db.FindInBatches(&[]PublicKey{}, 100, func(tx *gorm.DB, batch int) error {
  453. var keys []PublicKey
  454. if err := tx.Find(&keys).Error; err != nil {
  455. return err
  456. }
  457. for _, key := range keys {
  458. if _, err := f.WriteString(key.AuthorizedString()); err != nil {
  459. return err
  460. }
  461. }
  462. return nil
  463. }).Error
  464. if err != nil {
  465. _ = f.Close()
  466. return err
  467. }
  468. _ = f.Close()
  469. if com.IsExist(fpath) {
  470. if err = os.Remove(fpath); err != nil {
  471. return err
  472. }
  473. }
  474. if err = os.Rename(tmpPath, fpath); err != nil {
  475. return err
  476. }
  477. return nil
  478. }
  479. // ________ .__ ____ __.
  480. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  481. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  482. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  483. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  484. // \/ \/|__| \/ \/ \/\/
  485. // DeployKey represents deploy key information and its relation with repository.
  486. type DeployKey struct {
  487. ID int64
  488. KeyID int64 `gorm:"uniqueIndex:s;index"`
  489. RepoID int64 `gorm:"uniqueIndex:s;index"`
  490. Name string
  491. Fingerprint string
  492. Content string `gorm:"-" json:"-"`
  493. Created time.Time `gorm:"-" json:"-"`
  494. CreatedUnix int64
  495. Updated time.Time `gorm:"-" json:"-"` // Note: Updated must below Created for AfterFind.
  496. UpdatedUnix int64
  497. HasRecentActivity bool `gorm:"-" json:"-"`
  498. HasUsed bool `gorm:"-" json:"-"`
  499. }
  500. func (k *DeployKey) BeforeCreate(tx *gorm.DB) error {
  501. if k.CreatedUnix == 0 {
  502. k.CreatedUnix = tx.NowFunc().Unix()
  503. }
  504. return nil
  505. }
  506. func (k *DeployKey) BeforeUpdate(tx *gorm.DB) error {
  507. k.UpdatedUnix = tx.NowFunc().Unix()
  508. return nil
  509. }
  510. func (k *DeployKey) AfterFind(tx *gorm.DB) error {
  511. k.Created = time.Unix(k.CreatedUnix, 0).Local()
  512. if k.UpdatedUnix > 0 {
  513. k.Updated = time.Unix(k.UpdatedUnix, 0).Local()
  514. k.HasUsed = k.Updated.After(k.Created)
  515. k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(tx.NowFunc())
  516. }
  517. return nil
  518. }
  519. // GetContent gets associated public key content.
  520. func (k *DeployKey) GetContent() error {
  521. pkey, err := GetPublicKeyByID(k.KeyID)
  522. if err != nil {
  523. return err
  524. }
  525. k.Content = pkey.Content
  526. return nil
  527. }
  528. func checkDeployKey(tx *gorm.DB, keyID, repoID int64, name string) error {
  529. // Note: We want error detail, not just true or false here.
  530. err := tx.Where("key_id = ? AND repo_id = ?", keyID, repoID).First(new(DeployKey)).Error
  531. if err == nil {
  532. return ErrDeployKeyAlreadyExist{keyID, repoID}
  533. } else if !errors.Is(err, gorm.ErrRecordNotFound) {
  534. return err
  535. }
  536. err = tx.Where("repo_id = ? AND name = ?", repoID, name).First(new(DeployKey)).Error
  537. if err == nil {
  538. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  539. } else if !errors.Is(err, gorm.ErrRecordNotFound) {
  540. return err
  541. }
  542. return nil
  543. }
  544. // addDeployKey adds new key-repo relation.
  545. func addDeployKey(tx *gorm.DB, keyID, repoID int64, name, fingerprint string) (*DeployKey, error) {
  546. if err := checkDeployKey(tx, keyID, repoID, name); err != nil {
  547. return nil, err
  548. }
  549. key := &DeployKey{
  550. KeyID: keyID,
  551. RepoID: repoID,
  552. Name: name,
  553. Fingerprint: fingerprint,
  554. }
  555. err := tx.Create(key).Error
  556. return key, err
  557. }
  558. // HasDeployKey returns true if public key is a deploy key of given repository.
  559. func HasDeployKey(keyID, repoID int64) bool {
  560. err := db.Where("key_id = ? AND repo_id = ?", keyID, repoID).First(new(DeployKey)).Error
  561. return err == nil
  562. }
  563. // AddDeployKey add new deploy key to database and authorized_keys file.
  564. func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
  565. if err := checkKeyContent(content); err != nil {
  566. return nil, err
  567. }
  568. pkey := &PublicKey{
  569. Content: content,
  570. Mode: AccessModeRead,
  571. Type: KeyTypeDeploy,
  572. }
  573. err := db.Where("content = ? AND mode = ? AND type = ?", content, AccessModeRead, KeyTypeDeploy).First(pkey).Error
  574. has := err == nil
  575. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  576. return nil, err
  577. }
  578. var key *DeployKey
  579. err = db.Transaction(func(tx *gorm.DB) error {
  580. // First time use this deploy key.
  581. if !has {
  582. if err := addKey(tx, pkey); err != nil {
  583. return errors.Newf("addKey: %v", err)
  584. }
  585. }
  586. var err error
  587. key, err = addDeployKey(tx, pkey.ID, repoID, name, pkey.Fingerprint)
  588. if err != nil {
  589. return errors.Newf("addDeployKey: %v", err)
  590. }
  591. return nil
  592. })
  593. if err != nil {
  594. return nil, err
  595. }
  596. return key, nil
  597. }
  598. var _ errutil.NotFound = (*ErrDeployKeyNotExist)(nil)
  599. type ErrDeployKeyNotExist struct {
  600. args map[string]any
  601. }
  602. func IsErrDeployKeyNotExist(err error) bool {
  603. _, ok := err.(ErrDeployKeyNotExist)
  604. return ok
  605. }
  606. func (err ErrDeployKeyNotExist) Error() string {
  607. return fmt.Sprintf("deploy key does not exist: %v", err.args)
  608. }
  609. func (ErrDeployKeyNotExist) NotFound() bool {
  610. return true
  611. }
  612. // GetDeployKeyByID returns deploy key by given ID.
  613. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  614. key := new(DeployKey)
  615. err := db.Where("id = ?", id).First(key).Error
  616. if err != nil {
  617. if errors.Is(err, gorm.ErrRecordNotFound) {
  618. return nil, ErrDeployKeyNotExist{args: map[string]any{"deployKeyID": id}}
  619. }
  620. return nil, err
  621. }
  622. return key, nil
  623. }
  624. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  625. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  626. key := &DeployKey{
  627. KeyID: keyID,
  628. RepoID: repoID,
  629. }
  630. err := db.Where("key_id = ? AND repo_id = ?", keyID, repoID).First(key).Error
  631. if err != nil {
  632. if errors.Is(err, gorm.ErrRecordNotFound) {
  633. return nil, ErrDeployKeyNotExist{args: map[string]any{"keyID": keyID, "repoID": repoID}}
  634. }
  635. return nil, err
  636. }
  637. return key, nil
  638. }
  639. // UpdateDeployKey updates deploy key information.
  640. func UpdateDeployKey(key *DeployKey) error {
  641. return db.Model(key).Where("id = ?", key.ID).Updates(key).Error
  642. }
  643. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  644. func DeleteDeployKey(doer *User, id int64) error {
  645. key, err := GetDeployKeyByID(id)
  646. if err != nil {
  647. if IsErrDeployKeyNotExist(err) {
  648. return nil
  649. }
  650. return errors.Newf("GetDeployKeyByID: %v", err)
  651. }
  652. // Check if user has access to delete this key.
  653. if !doer.IsAdmin {
  654. repo, err := GetRepositoryByID(key.RepoID)
  655. if err != nil {
  656. return errors.Newf("GetRepositoryByID: %v", err)
  657. }
  658. if !Handle.Permissions().Authorize(context.TODO(), doer.ID, repo.ID, AccessModeAdmin,
  659. AccessModeOptions{
  660. OwnerID: repo.OwnerID,
  661. Private: repo.IsPrivate,
  662. },
  663. ) {
  664. return ErrKeyAccessDenied{doer.ID, key.ID, "deploy"}
  665. }
  666. }
  667. return db.Transaction(func(tx *gorm.DB) error {
  668. if err := tx.Where("id = ?", key.ID).Delete(new(DeployKey)).Error; err != nil {
  669. return errors.Newf("delete deploy key [%d]: %v", key.ID, err)
  670. }
  671. // Check if this is the last reference to same key content.
  672. err := tx.Where("key_id = ?", key.KeyID).First(new(DeployKey)).Error
  673. if errors.Is(err, gorm.ErrRecordNotFound) {
  674. if err = deletePublicKeys(tx, key.KeyID); err != nil {
  675. return err
  676. }
  677. } else if err != nil {
  678. return err
  679. }
  680. return nil
  681. })
  682. }
  683. // ListDeployKeys returns all deploy keys by given repository ID.
  684. func ListDeployKeys(repoID int64) ([]*DeployKey, error) {
  685. keys := make([]*DeployKey, 0, 5)
  686. return keys, db.Where("repo_id = ?", repoID).Find(&keys).Error
  687. }