ssh_key.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bufio"
  7. "encoding/base64"
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "os"
  14. "path"
  15. "path/filepath"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/Unknwon/com"
  20. "github.com/go-xorm/xorm"
  21. "golang.org/x/crypto/ssh"
  22. "github.com/gogits/gogs/modules/log"
  23. "github.com/gogits/gogs/modules/process"
  24. "github.com/gogits/gogs/modules/setting"
  25. )
  26. const (
  27. // "### autogenerated by gitgos, DO NOT EDIT\n"
  28. _TPL_PUBLICK_KEY = `command="%s serv key-%d --config='%s'",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
  29. )
  30. var sshOpLocker = sync.Mutex{}
  31. type KeyType int
  32. const (
  33. KEY_TYPE_USER = iota + 1
  34. KEY_TYPE_DEPLOY
  35. )
  36. // PublicKey represents a SSH or deploy key.
  37. type PublicKey struct {
  38. ID int64 `xorm:"pk autoincr"`
  39. OwnerID int64 `xorm:"INDEX NOT NULL"`
  40. Name string `xorm:"NOT NULL"`
  41. Fingerprint string `xorm:"NOT NULL"`
  42. Content string `xorm:"TEXT NOT NULL"`
  43. Mode AccessMode `xorm:"NOT NULL DEFAULT 2"`
  44. Type KeyType `xorm:"NOT NULL DEFAULT 1"`
  45. Created time.Time `xorm:"CREATED"`
  46. Updated time.Time // Note: Updated must below Created for AfterSet.
  47. HasRecentActivity bool `xorm:"-"`
  48. HasUsed bool `xorm:"-"`
  49. }
  50. func (k *PublicKey) AfterSet(colName string, _ xorm.Cell) {
  51. switch colName {
  52. case "created":
  53. k.HasUsed = k.Updated.After(k.Created)
  54. k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  55. }
  56. }
  57. // OmitEmail returns content of public key but without e-mail address.
  58. func (k *PublicKey) OmitEmail() string {
  59. return strings.Join(strings.Split(k.Content, " ")[:2], " ")
  60. }
  61. // GetAuthorizedString generates and returns formatted public key string for authorized_keys file.
  62. func (key *PublicKey) GetAuthorizedString() string {
  63. return fmt.Sprintf(_TPL_PUBLICK_KEY, setting.AppPath, key.ID, setting.CustomConf, key.Content)
  64. }
  65. func extractTypeFromBase64Key(key string) (string, error) {
  66. b, err := base64.StdEncoding.DecodeString(key)
  67. if err != nil || len(b) < 4 {
  68. return "", errors.New("Invalid key format")
  69. }
  70. keyLength := int(binary.BigEndian.Uint32(b))
  71. if len(b) < 4+keyLength {
  72. return "", errors.New("Invalid key format")
  73. }
  74. return string(b[4 : 4+keyLength]), nil
  75. }
  76. // parseKeyString parses any key string in openssh or ssh2 format to clean openssh string (rfc4253)
  77. func parseKeyString(content string) (string, error) {
  78. // Transform all legal line endings to a single "\n"
  79. s := strings.Replace(strings.Replace(strings.TrimSpace(content), "\r\n", "\n", -1), "\r", "\n", -1)
  80. lines := strings.Split(s, "\n")
  81. var keyType, keyContent, keyComment string
  82. if len(lines) == 1 {
  83. // Parse openssh format
  84. parts := strings.SplitN(lines[0], " ", 3)
  85. switch len(parts) {
  86. case 0:
  87. return "", errors.New("Empty key")
  88. case 1:
  89. keyContent = parts[0]
  90. case 2:
  91. keyType = parts[0]
  92. keyContent = parts[1]
  93. default:
  94. keyType = parts[0]
  95. keyContent = parts[1]
  96. keyComment = parts[2]
  97. }
  98. // If keyType is not given, extract it from content. If given, validate it
  99. if len(keyType) == 0 {
  100. if t, err := extractTypeFromBase64Key(keyContent); err == nil {
  101. keyType = t
  102. } else {
  103. return "", err
  104. }
  105. } else {
  106. if t, err := extractTypeFromBase64Key(keyContent); err != nil || keyType != t {
  107. return "", err
  108. }
  109. }
  110. } else {
  111. // Parse SSH2 file format.
  112. continuationLine := false
  113. for _, line := range lines {
  114. // Skip lines that:
  115. // 1) are a continuation of the previous line,
  116. // 2) contain ":" as that are comment lines
  117. // 3) contain "-" as that are begin and end tags
  118. if continuationLine || strings.ContainsAny(line, ":-") {
  119. continuationLine = strings.HasSuffix(line, "\\")
  120. } else {
  121. keyContent = keyContent + line
  122. }
  123. }
  124. if t, err := extractTypeFromBase64Key(keyContent); err == nil {
  125. keyType = t
  126. } else {
  127. return "", err
  128. }
  129. }
  130. return keyType + " " + keyContent + " " + keyComment, nil
  131. }
  132. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  133. func CheckPublicKeyString(content string) (_ string, err error) {
  134. content, err = parseKeyString(content)
  135. if err != nil {
  136. return "", err
  137. }
  138. content = strings.TrimRight(content, "\n\r")
  139. if strings.ContainsAny(content, "\n\r") {
  140. return "", errors.New("only a single line with a single key please")
  141. }
  142. fields := strings.Fields(content)
  143. if len(fields) < 2 {
  144. return "", errors.New("too less fields")
  145. }
  146. key, err := base64.StdEncoding.DecodeString(fields[1])
  147. if err != nil {
  148. return "", fmt.Errorf("StdEncoding.DecodeString: %v", err)
  149. }
  150. pkey, err := ssh.ParsePublicKey([]byte(key))
  151. if err != nil {
  152. return "", fmt.Errorf("ParsePublicKey: %v", err)
  153. }
  154. log.Trace("Key type: %s", pkey.Type())
  155. return content, nil
  156. }
  157. // saveAuthorizedKeyFile writes SSH key content to authorized_keys file.
  158. func saveAuthorizedKeyFile(keys ...*PublicKey) error {
  159. sshOpLocker.Lock()
  160. defer sshOpLocker.Unlock()
  161. fpath := filepath.Join(setting.SSHRootPath, "authorized_keys")
  162. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  163. if err != nil {
  164. return err
  165. }
  166. defer f.Close()
  167. fi, err := f.Stat()
  168. if err != nil {
  169. return err
  170. }
  171. // FIXME: following command does not support in Windows.
  172. if !setting.IsWindows {
  173. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  174. if fi.Mode().Perm() > 0600 {
  175. log.Error(4, "authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  176. if err = f.Chmod(0600); err != nil {
  177. return err
  178. }
  179. }
  180. }
  181. for _, key := range keys {
  182. if _, err = f.WriteString(key.GetAuthorizedString()); err != nil {
  183. return err
  184. }
  185. }
  186. return nil
  187. }
  188. // checkKeyContent onlys checks if key content has been used as public key,
  189. // it is OK to use same key as deploy key for multiple repositories/users.
  190. func checkKeyContent(content string) error {
  191. has, err := x.Get(&PublicKey{
  192. Content: content,
  193. Type: KEY_TYPE_USER,
  194. })
  195. if err != nil {
  196. return err
  197. } else if has {
  198. return ErrKeyAlreadyExist{0, content}
  199. }
  200. return nil
  201. }
  202. func addKey(e Engine, key *PublicKey) (err error) {
  203. // Calculate fingerprint.
  204. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  205. "id_rsa.pub"), "\\", "/", -1)
  206. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  207. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), 0644); err != nil {
  208. return err
  209. }
  210. stdout, stderr, err := process.Exec("AddPublicKey", "ssh-keygen", "-lf", tmpPath)
  211. if err != nil {
  212. return errors.New("ssh-keygen -lf: " + stderr)
  213. } else if len(stdout) < 2 {
  214. return errors.New("not enough output for calculating fingerprint: " + stdout)
  215. }
  216. key.Fingerprint = strings.Split(stdout, " ")[1]
  217. // Save SSH key.
  218. if _, err = e.Insert(key); err != nil {
  219. return err
  220. }
  221. // Don't need to rewrite this file if builtin SSH server is enabled.
  222. if setting.StartSSHServer {
  223. return nil
  224. }
  225. return saveAuthorizedKeyFile(key)
  226. }
  227. // AddPublicKey adds new public key to database and authorized_keys file.
  228. func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
  229. if err := checkKeyContent(content); err != nil {
  230. return nil, err
  231. }
  232. // Key name of same user cannot be duplicated.
  233. has, err := x.Where("owner_id=? AND name=?", ownerID, name).Get(new(PublicKey))
  234. if err != nil {
  235. return nil, err
  236. } else if has {
  237. return nil, ErrKeyNameAlreadyUsed{ownerID, name}
  238. }
  239. sess := x.NewSession()
  240. defer sessionRelease(sess)
  241. if err = sess.Begin(); err != nil {
  242. return nil, err
  243. }
  244. key := &PublicKey{
  245. OwnerID: ownerID,
  246. Name: name,
  247. Content: content,
  248. Mode: ACCESS_MODE_WRITE,
  249. Type: KEY_TYPE_USER,
  250. }
  251. if err = addKey(sess, key); err != nil {
  252. return nil, fmt.Errorf("addKey: %v", err)
  253. }
  254. return key, sess.Commit()
  255. }
  256. // GetPublicKeyByID returns public key by given ID.
  257. func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
  258. key := new(PublicKey)
  259. has, err := x.Id(keyID).Get(key)
  260. if err != nil {
  261. return nil, err
  262. } else if !has {
  263. return nil, ErrKeyNotExist{keyID}
  264. }
  265. return key, nil
  266. }
  267. // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
  268. // and returns public key found.
  269. func SearchPublicKeyByContent(content string) (*PublicKey, error) {
  270. key := new(PublicKey)
  271. has, err := x.Where("content like ?", content+"%").Get(key)
  272. if err != nil {
  273. return nil, err
  274. } else if !has {
  275. return nil, ErrKeyNotExist{}
  276. }
  277. return key, nil
  278. }
  279. // ListPublicKeys returns a list of public keys belongs to given user.
  280. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  281. keys := make([]*PublicKey, 0, 5)
  282. return keys, x.Where("owner_id=?", uid).Find(&keys)
  283. }
  284. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  285. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  286. fr, err := os.Open(p)
  287. if err != nil {
  288. return err
  289. }
  290. defer fr.Close()
  291. fw, err := os.OpenFile(tmpP, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  292. if err != nil {
  293. return err
  294. }
  295. defer fw.Close()
  296. isFound := false
  297. keyword := fmt.Sprintf("key-%d", key.ID)
  298. buf := bufio.NewReader(fr)
  299. for {
  300. line, errRead := buf.ReadString('\n')
  301. line = strings.TrimSpace(line)
  302. if errRead != nil {
  303. if errRead != io.EOF {
  304. return errRead
  305. }
  306. // Reached end of file, if nothing to read then break,
  307. // otherwise handle the last line.
  308. if len(line) == 0 {
  309. break
  310. }
  311. }
  312. // Found the line and copy rest of file.
  313. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  314. isFound = true
  315. continue
  316. }
  317. // Still finding the line, copy the line that currently read.
  318. if _, err = fw.WriteString(line + "\n"); err != nil {
  319. return err
  320. }
  321. if errRead == io.EOF {
  322. break
  323. }
  324. }
  325. if !isFound {
  326. log.Warn("SSH key %d not found in authorized_keys file for deletion", key.ID)
  327. }
  328. return nil
  329. }
  330. // UpdatePublicKey updates given public key.
  331. func UpdatePublicKey(key *PublicKey) error {
  332. _, err := x.Id(key.ID).AllCols().Update(key)
  333. return err
  334. }
  335. func deletePublicKey(e *xorm.Session, keyID int64) error {
  336. sshOpLocker.Lock()
  337. defer sshOpLocker.Unlock()
  338. key := &PublicKey{ID: keyID}
  339. has, err := e.Get(key)
  340. if err != nil {
  341. return err
  342. } else if !has {
  343. return nil
  344. }
  345. if _, err = e.Id(key.ID).Delete(new(PublicKey)); err != nil {
  346. return err
  347. }
  348. // Don't need to rewrite this file if builtin SSH server is enabled.
  349. if setting.StartSSHServer {
  350. return nil
  351. }
  352. fpath := filepath.Join(setting.SSHRootPath, "authorized_keys")
  353. tmpPath := filepath.Join(setting.SSHRootPath, "authorized_keys.tmp")
  354. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  355. return err
  356. } else if err = os.Remove(fpath); err != nil {
  357. return err
  358. }
  359. return os.Rename(tmpPath, fpath)
  360. }
  361. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  362. func DeletePublicKey(doer *User, id int64) (err error) {
  363. key, err := GetPublicKeyByID(id)
  364. if err != nil {
  365. if IsErrKeyNotExist(err) {
  366. return nil
  367. }
  368. return fmt.Errorf("GetPublicKeyByID: %v", err)
  369. }
  370. // Check if user has access to delete this key.
  371. if !doer.IsAdmin && doer.Id != key.OwnerID {
  372. return ErrKeyAccessDenied{doer.Id, key.ID, "public"}
  373. }
  374. sess := x.NewSession()
  375. defer sessionRelease(sess)
  376. if err = sess.Begin(); err != nil {
  377. return err
  378. }
  379. if err = deletePublicKey(sess, id); err != nil {
  380. return err
  381. }
  382. return sess.Commit()
  383. }
  384. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
  385. func RewriteAllPublicKeys() error {
  386. sshOpLocker.Lock()
  387. defer sshOpLocker.Unlock()
  388. tmpPath := filepath.Join(setting.SSHRootPath, "authorized_keys.tmp")
  389. f, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  390. if err != nil {
  391. return err
  392. }
  393. defer os.Remove(tmpPath)
  394. err = x.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  395. _, err = f.WriteString((bean.(*PublicKey)).GetAuthorizedString())
  396. return err
  397. })
  398. f.Close()
  399. if err != nil {
  400. return err
  401. }
  402. fpath := filepath.Join(setting.SSHRootPath, "authorized_keys")
  403. if com.IsExist(fpath) {
  404. if err = os.Remove(fpath); err != nil {
  405. return err
  406. }
  407. }
  408. if err = os.Rename(tmpPath, fpath); err != nil {
  409. return err
  410. }
  411. return nil
  412. }
  413. // ________ .__ ____ __.
  414. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  415. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  416. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  417. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  418. // \/ \/|__| \/ \/ \/\/
  419. // DeployKey represents deploy key information and its relation with repository.
  420. type DeployKey struct {
  421. ID int64 `xorm:"pk autoincr"`
  422. KeyID int64 `xorm:"UNIQUE(s) INDEX"`
  423. RepoID int64 `xorm:"UNIQUE(s) INDEX"`
  424. Name string
  425. Fingerprint string
  426. Content string `xorm:"-"`
  427. Created time.Time `xorm:"CREATED"`
  428. Updated time.Time // Note: Updated must below Created for AfterSet.
  429. HasRecentActivity bool `xorm:"-"`
  430. HasUsed bool `xorm:"-"`
  431. }
  432. func (k *DeployKey) AfterSet(colName string, _ xorm.Cell) {
  433. switch colName {
  434. case "created":
  435. k.HasUsed = k.Updated.After(k.Created)
  436. k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  437. }
  438. }
  439. // GetContent gets associated public key content.
  440. func (k *DeployKey) GetContent() error {
  441. pkey, err := GetPublicKeyByID(k.KeyID)
  442. if err != nil {
  443. return err
  444. }
  445. k.Content = pkey.Content
  446. return nil
  447. }
  448. func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
  449. // Note: We want error detail, not just true or false here.
  450. has, err := e.Where("key_id=? AND repo_id=?", keyID, repoID).Get(new(DeployKey))
  451. if err != nil {
  452. return err
  453. } else if has {
  454. return ErrDeployKeyAlreadyExist{keyID, repoID}
  455. }
  456. has, err = e.Where("repo_id=? AND name=?", repoID, name).Get(new(DeployKey))
  457. if err != nil {
  458. return err
  459. } else if has {
  460. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  461. }
  462. return nil
  463. }
  464. // addDeployKey adds new key-repo relation.
  465. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string) (*DeployKey, error) {
  466. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  467. return nil, err
  468. }
  469. key := &DeployKey{
  470. KeyID: keyID,
  471. RepoID: repoID,
  472. Name: name,
  473. Fingerprint: fingerprint,
  474. }
  475. _, err := e.Insert(key)
  476. return key, err
  477. }
  478. // HasDeployKey returns true if public key is a deploy key of given repository.
  479. func HasDeployKey(keyID, repoID int64) bool {
  480. has, _ := x.Where("key_id=? AND repo_id=?", keyID, repoID).Get(new(DeployKey))
  481. return has
  482. }
  483. // AddDeployKey add new deploy key to database and authorized_keys file.
  484. func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
  485. if err := checkKeyContent(content); err != nil {
  486. return nil, err
  487. }
  488. pkey := &PublicKey{
  489. Content: content,
  490. Mode: ACCESS_MODE_READ,
  491. Type: KEY_TYPE_DEPLOY,
  492. }
  493. has, err := x.Get(pkey)
  494. if err != nil {
  495. return nil, err
  496. }
  497. sess := x.NewSession()
  498. defer sessionRelease(sess)
  499. if err = sess.Begin(); err != nil {
  500. return nil, err
  501. }
  502. // First time use this deploy key.
  503. if !has {
  504. if err = addKey(sess, pkey); err != nil {
  505. return nil, fmt.Errorf("addKey: %v", err)
  506. }
  507. }
  508. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint)
  509. if err != nil {
  510. return nil, fmt.Errorf("addDeployKey: %v", err)
  511. }
  512. return key, sess.Commit()
  513. }
  514. // GetDeployKeyByID returns deploy key by given ID.
  515. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  516. key := new(DeployKey)
  517. has, err := x.Id(id).Get(key)
  518. if err != nil {
  519. return nil, err
  520. } else if !has {
  521. return nil, ErrDeployKeyNotExist{id, 0, 0}
  522. }
  523. return key, nil
  524. }
  525. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  526. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  527. key := &DeployKey{
  528. KeyID: keyID,
  529. RepoID: repoID,
  530. }
  531. has, err := x.Get(key)
  532. if err != nil {
  533. return nil, err
  534. } else if !has {
  535. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  536. }
  537. return key, nil
  538. }
  539. // UpdateDeployKey updates deploy key information.
  540. func UpdateDeployKey(key *DeployKey) error {
  541. _, err := x.Id(key.ID).AllCols().Update(key)
  542. return err
  543. }
  544. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  545. func DeleteDeployKey(doer *User, id int64) error {
  546. key, err := GetDeployKeyByID(id)
  547. if err != nil {
  548. if IsErrDeployKeyNotExist(err) {
  549. return nil
  550. }
  551. return fmt.Errorf("GetDeployKeyByID: %v", err)
  552. }
  553. // Check if user has access to delete this key.
  554. if !doer.IsAdmin {
  555. repo, err := GetRepositoryByID(key.RepoID)
  556. if err != nil {
  557. return fmt.Errorf("GetRepositoryByID: %v", err)
  558. }
  559. yes, err := HasAccess(doer, repo, ACCESS_MODE_ADMIN)
  560. if err != nil {
  561. return fmt.Errorf("HasAccess: %v", err)
  562. } else if !yes {
  563. return ErrKeyAccessDenied{doer.Id, key.ID, "deploy"}
  564. }
  565. }
  566. sess := x.NewSession()
  567. defer sessionRelease(sess)
  568. if err = sess.Begin(); err != nil {
  569. return err
  570. }
  571. if _, err = sess.Id(key.ID).Delete(new(DeployKey)); err != nil {
  572. return fmt.Errorf("delete deploy key[%d]: %v", key.ID, err)
  573. }
  574. // Check if this is the last reference to same key content.
  575. has, err := sess.Where("key_id=?", key.KeyID).Get(new(DeployKey))
  576. if err != nil {
  577. return err
  578. } else if !has {
  579. if err = deletePublicKey(sess, key.KeyID); err != nil {
  580. return err
  581. }
  582. }
  583. return sess.Commit()
  584. }
  585. // ListDeployKeys returns all deploy keys by given repository ID.
  586. func ListDeployKeys(repoID int64) ([]*DeployKey, error) {
  587. keys := make([]*DeployKey, 0, 5)
  588. return keys, x.Where("repo_id=?", repoID).Find(&keys)
  589. }