You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

725 lines
19 KiB

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