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.

777 lines
21 KiB

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