From cc8f5add6e811cc340e676f0d969a4b1dd551d89 Mon Sep 17 00:00:00 2001 From: Unknwon Date: Thu, 3 Dec 2015 00:24:37 -0500 Subject: [PATCH] fix #976 --- README.md | 2 +- cmd/web.go | 25 +++++-- gogs.go | 2 +- models/error.go | 16 +++++ models/publickey.go | 58 +++++++++++------ routers/api/v1/miscellaneous.go | 4 +- routers/api/v1/repo.go | 4 ++ routers/api/v1/repo_file.go | 2 + routers/api/v1/repo_keys.go | 53 +++++++++------ routers/api/v1/user.go | 3 +- routers/api/v1/user_app.go | 4 +- routers/api/v1/user_keys.go | 111 ++++++++++++++++++++++++++++++++ routers/repo/setting.go | 2 +- routers/user/setting.go | 4 +- templates/.VERSION | 2 +- 15 files changed, 235 insertions(+), 57 deletions(-) create mode 100644 routers/api/v1/user_keys.go diff --git a/README.md b/README.md index ffc3559dd8..faef7915f2 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Gogs - Go Git Service [![Build Status](https://travis-ci.org/gogits/gogs.svg?bra ![](public/img/gogs-large-resize.png) -##### Current version: 0.7.27 Beta +##### Current version: 0.7.28 Beta diff --git a/cmd/web.go b/cmd/web.go index 33fe8fa75d..899b733297 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -197,14 +197,14 @@ func runWeb(ctx *cli.Context) { m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues) // ***** START: API ***** - // FIXME: custom form error response. + // FIXME: custom form error response m.Group("/api", func() { m.Group("/v1", func() { - // Miscellaneous. + // Miscellaneous m.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown) m.Post("/markdown/raw", v1.MarkdownRaw) - // Users. + // Users m.Group("/users", func() { m.Get("/search", v1.SearchUsers) @@ -218,7 +218,22 @@ func runWeb(ctx *cli.Context) { }) }) - // Repositories. + m.Group("/users", func() { + m.Group("/:username", func() { + m.Get("/keys", v1.ListUserPublicKeys) + }) + }, middleware.ApiReqToken()) + + m.Group("/user", func() { + m.Group("/keys", func() { + m.Combo("").Get(v1.ListMyPublicKeys). + Post(bind(api.CreateKeyOption{}), v1.CreateUserPublicKey) + m.Combo("/:id").Get(v1.GetUserPublicKey). + Delete(v1.DeleteUserPublicKey) + }) + }, middleware.ApiReqToken()) + + // Repositories m.Combo("/user/repos", middleware.ApiReqToken()).Get(v1.ListMyRepos). Post(bind(api.CreateRepoOption{}), v1.CreateRepo) m.Post("/org/:org/repos", middleware.ApiReqToken(), bind(api.CreateRepoOption{}), v1.CreateOrgRepo) @@ -241,7 +256,7 @@ func runWeb(ctx *cli.Context) { m.Group("/keys", func() { m.Combo("").Get(v1.ListRepoDeployKeys). - Post(bind(api.CreateDeployKeyOption{}), v1.CreateRepoDeployKey) + Post(bind(api.CreateKeyOption{}), v1.CreateRepoDeployKey) m.Combo("/:id").Get(v1.GetRepoDeployKey). Delete(v1.DeleteRepoDeploykey) }) diff --git a/gogs.go b/gogs.go index 0cd6026451..cb4ea9e2ef 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.7.27.1202 Beta" +const APP_VER = "0.7.28.1203 Beta" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/models/error.go b/models/error.go index d005b9af73..561252e84a 100644 --- a/models/error.go +++ b/models/error.go @@ -188,6 +188,22 @@ func (err ErrKeyNameAlreadyUsed) Error() string { return fmt.Sprintf("public key already exists [owner_id: %d, name: %s]", err.OwnerID, err.Name) } +type ErrKeyAccessDenied struct { + UserID int64 + KeyID int64 + Note string +} + +func IsErrKeyAccessDenied(err error) bool { + _, ok := err.(ErrKeyAccessDenied) + return ok +} + +func (err ErrKeyAccessDenied) Error() string { + return fmt.Sprintf("user does not have access to the key [user_id: %d, key_id: %d, note: %s]", + err.UserID, err.KeyID, err.Note) +} + type ErrDeployKeyNotExist struct { ID int64 KeyID int64 diff --git a/models/publickey.go b/models/publickey.go index b5646a55b5..ac0ec71f44 100644 --- a/models/publickey.go +++ b/models/publickey.go @@ -303,23 +303,23 @@ func addKey(e Engine, key *PublicKey) (err error) { } // AddPublicKey adds new public key to database and authorized_keys file. -func AddPublicKey(ownerID int64, name, content string) (err error) { - if err = checkKeyContent(content); err != nil { - return err +func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) { + if err := checkKeyContent(content); err != nil { + return nil, err } // Key name of same user cannot be duplicated. has, err := x.Where("owner_id=? AND name=?", ownerID, name).Get(new(PublicKey)) if err != nil { - return err + return nil, err } else if has { - return ErrKeyNameAlreadyUsed{ownerID, name} + return nil, ErrKeyNameAlreadyUsed{ownerID, name} } sess := x.NewSession() defer sessionRelease(sess) if err = sess.Begin(); err != nil { - return err + return nil, err } key := &PublicKey{ @@ -330,10 +330,10 @@ func AddPublicKey(ownerID int64, name, content string) (err error) { Type: KEY_TYPE_USER, } if err = addKey(sess, key); err != nil { - return fmt.Errorf("addKey: %v", err) + return nil, fmt.Errorf("addKey: %v", err) } - return sess.Commit() + return key, sess.Commit() } // GetPublicKeyByID returns public key by given ID. @@ -450,12 +450,18 @@ func deletePublicKey(e *xorm.Session, keyID int64) error { } // DeletePublicKey deletes SSH key information both in database and authorized_keys file. -func DeletePublicKey(id int64) (err error) { - has, err := x.Id(id).Get(new(PublicKey)) +func DeletePublicKey(doer *User, id int64) (err error) { + key, err := GetPublicKeyByID(id) if err != nil { - return err - } else if !has { - return nil + if IsErrKeyNotExist(err) { + return nil + } + return fmt.Errorf("GetPublicKeyByID: %v", err) + } + + // Check if user has access to delete this key. + if doer.Id != key.OwnerID { + return ErrKeyAccessDenied{doer.Id, key.ID, "public"} } sess := x.NewSession() @@ -656,13 +662,25 @@ func UpdateDeployKey(key *DeployKey) error { } // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed. -func DeleteDeployKey(id int64) error { - key := &DeployKey{ID: id} - has, err := x.Id(key.ID).Get(key) +func DeleteDeployKey(doer *User, id int64) error { + key, err := GetDeployKeyByID(id) if err != nil { - return err - } else if !has { - return nil + if IsErrDeployKeyNotExist(err) { + return nil + } + return fmt.Errorf("GetDeployKeyByID: %v", err) + } + + // Check if user has access to delete this key. + repo, err := GetRepositoryByID(key.RepoID) + if err != nil { + return fmt.Errorf("GetRepositoryByID: %v", err) + } + yes, err := HasAccess(doer, repo, ACCESS_MODE_ADMIN) + if err != nil { + return fmt.Errorf("HasAccess: %v", err) + } else if !yes { + return ErrKeyAccessDenied{doer.Id, key.ID, "deploy"} } sess := x.NewSession() @@ -676,7 +694,7 @@ func DeleteDeployKey(id int64) error { } // Check if this is the last reference to same key content. - has, err = sess.Where("key_id=?", key.KeyID).Get(new(DeployKey)) + has, err := sess.Where("key_id=?", key.KeyID).Get(new(DeployKey)) if err != nil { return err } else if !has { diff --git a/routers/api/v1/miscellaneous.go b/routers/api/v1/miscellaneous.go index dd611b2e70..a382e34951 100644 --- a/routers/api/v1/miscellaneous.go +++ b/routers/api/v1/miscellaneous.go @@ -10,7 +10,7 @@ import ( "github.com/gogits/gogs/modules/middleware" ) -// Render an arbitrary Markdown document. +// https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-an-arbitrary-markdown-document func Markdown(ctx *middleware.Context, form apiv1.MarkdownForm) { if ctx.HasApiError() { ctx.APIError(422, "", ctx.GetErrMsg()) @@ -30,7 +30,7 @@ func Markdown(ctx *middleware.Context, form apiv1.MarkdownForm) { } } -// Render a Markdown document in raw mode. +// https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-a-markdown-document-in-raw-mode func MarkdownRaw(ctx *middleware.Context) { body, err := ctx.Req.Body().Bytes() if err != nil { diff --git a/routers/api/v1/repo.go b/routers/api/v1/repo.go index 62eb965d85..119a52b441 100644 --- a/routers/api/v1/repo.go +++ b/routers/api/v1/repo.go @@ -34,6 +34,7 @@ func ToApiRepository(owner *models.User, repo *models.Repository, permission api } } +// https://github.com/gogits/go-gogs-client/wiki/Repositories#search-repositories func SearchRepos(ctx *middleware.Context) { opt := models.SearchOption{ Keyword: path.Base(ctx.Query("q")), @@ -184,6 +185,7 @@ func CreateOrgRepo(ctx *middleware.Context, opt api.CreateRepoOption) { createRepo(ctx, org, opt) } +// https://github.com/gogits/go-gogs-client/wiki/Repositories#migrate func MigrateRepo(ctx *middleware.Context, form auth.MigrateRepoForm) { ctxUser := ctx.User // Not equal means context user is an organization, @@ -279,6 +281,7 @@ func parseOwnerAndRepo(ctx *middleware.Context) (*models.User, *models.Repositor return owner, repo } +// https://github.com/gogits/go-gogs-client/wiki/Repositories#get func GetRepo(ctx *middleware.Context) { owner, repo := parseOwnerAndRepo(ctx) if ctx.Written() { @@ -288,6 +291,7 @@ func GetRepo(ctx *middleware.Context) { ctx.JSON(200, ToApiRepository(owner, repo, api.Permission{true, true, true})) } +// https://github.com/gogits/go-gogs-client/wiki/Repositories#delete func DeleteRepo(ctx *middleware.Context) { owner, repo := parseOwnerAndRepo(ctx) if ctx.Written() { diff --git a/routers/api/v1/repo_file.go b/routers/api/v1/repo_file.go index 3b2225e669..8cf36aefd9 100644 --- a/routers/api/v1/repo_file.go +++ b/routers/api/v1/repo_file.go @@ -11,6 +11,7 @@ import ( "github.com/gogits/gogs/routers/repo" ) +// https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-raw-content func GetRepoRawFile(ctx *middleware.Context) { if !ctx.Repo.HasAccess() { ctx.Error(404) @@ -31,6 +32,7 @@ func GetRepoRawFile(ctx *middleware.Context) { } } +// https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-archive func GetRepoArchive(ctx *middleware.Context) { repoPath := models.RepoPath(ctx.Params(":username"), ctx.Params(":reponame")) gitRepo, err := git.OpenRepository(repoPath) diff --git a/routers/api/v1/repo_keys.go b/routers/api/v1/repo_keys.go index 7016c55ed4..d8371b5a90 100644 --- a/routers/api/v1/repo_keys.go +++ b/routers/api/v1/repo_keys.go @@ -31,7 +31,7 @@ func composeDeployKeysAPILink(repoPath string) string { return setting.AppUrl + "api/v1/repos/" + repoPath + "/keys/" } -// https://github.com/gogits/go-gogs-client/wiki/Repositories---Deploy-Keys#list-deploy-keys +// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#list-deploy-keys func ListRepoDeployKeys(ctx *middleware.Context) { keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID) if err != nil { @@ -52,7 +52,7 @@ func ListRepoDeployKeys(ctx *middleware.Context) { ctx.JSON(200, &apiKeys) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories---Deploy-Keys#get-a-deploy-key +// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#get-a-deploy-key func GetRepoDeployKey(ctx *middleware.Context) { key, err := models.GetDeployKeyByID(ctx.ParamsInt64(":id")) if err != nil { @@ -73,29 +73,36 @@ func GetRepoDeployKey(ctx *middleware.Context) { ctx.JSON(200, ToApiDeployKey(apiLink, key)) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories---Deploy-Keys#add-a-new-deploy-key -func CreateRepoDeployKey(ctx *middleware.Context, form api.CreateDeployKeyOption) { +func handleCheckKeyStringError(ctx *middleware.Context, err error) { + if models.IsErrKeyUnableVerify(err) { + ctx.APIError(422, "", "Unable to verify key content") + } else { + ctx.APIError(422, "", fmt.Errorf("Invalid key content: %v", err)) + } +} + +func handleAddKeyError(ctx *middleware.Context, err error) { + switch { + case models.IsErrKeyAlreadyExist(err): + ctx.APIError(422, "", "Key content has been used as non-deploy key") + case models.IsErrKeyNameAlreadyUsed(err): + ctx.APIError(422, "", "Key title has been used") + default: + ctx.APIError(500, "AddKey", err) + } +} + +// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#add-a-new-deploy-key +func CreateRepoDeployKey(ctx *middleware.Context, form api.CreateKeyOption) { content, err := models.CheckPublicKeyString(form.Key) if err != nil { - if models.IsErrKeyUnableVerify(err) { - ctx.APIError(422, "", "Unable to verify key content") - } else { - ctx.APIError(422, "", fmt.Errorf("Invalid key content: %v", err)) - } + handleCheckKeyStringError(ctx, err) return } key, err := models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content) if err != nil { - ctx.Data["HasError"] = true - switch { - case models.IsErrKeyAlreadyExist(err): - ctx.APIError(422, "", "Key content has been used as non-deploy key") - case models.IsErrKeyNameAlreadyUsed(err): - ctx.APIError(422, "", "Key title has been used") - default: - ctx.APIError(500, "AddDeployKey", err) - } + handleAddKeyError(ctx, err) return } @@ -104,10 +111,14 @@ func CreateRepoDeployKey(ctx *middleware.Context, form api.CreateDeployKeyOption ctx.JSON(201, ToApiDeployKey(apiLink, key)) } -// https://github.com/gogits/go-gogs-client/wiki/Repositories---Deploy-Keys#remove-a-deploy-key +// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#remove-a-deploy-key func DeleteRepoDeploykey(ctx *middleware.Context) { - if err := models.DeleteDeployKey(ctx.ParamsInt64(":id")); err != nil { - ctx.APIError(500, "DeleteDeployKey", err) + if err := models.DeleteDeployKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { + if models.IsErrKeyAccessDenied(err) { + ctx.APIError(403, "", "You do not have access to this key") + } else { + ctx.APIError(500, "DeleteDeployKey", err) + } return } diff --git a/routers/api/v1/user.go b/routers/api/v1/user.go index ec4f720cb6..36a1872b95 100644 --- a/routers/api/v1/user.go +++ b/routers/api/v1/user.go @@ -24,6 +24,7 @@ func ToApiUser(u *models.User) *api.User { } } +// https://github.com/gogits/go-gogs-client/wiki/Users#search-users func SearchUsers(ctx *middleware.Context) { opt := models.SearchOption{ Keyword: ctx.Query("q"), @@ -61,7 +62,7 @@ func SearchUsers(ctx *middleware.Context) { }) } -// GET /users/:username +// https://github.com/gogits/go-gogs-client/wiki/Users#get-a-single-user func GetUserInfo(ctx *middleware.Context) { u, err := models.GetUserByName(ctx.Params(":username")) if err != nil { diff --git a/routers/api/v1/user_app.go b/routers/api/v1/user_app.go index 590d187e53..c1b83d60a0 100644 --- a/routers/api/v1/user_app.go +++ b/routers/api/v1/user_app.go @@ -11,7 +11,7 @@ import ( "github.com/gogits/gogs/modules/middleware" ) -// GET /users/:username/tokens +// https://github.com/gogits/go-gogs-client/wiki/Users#list-access-tokens-for-a-user func ListAccessTokens(ctx *middleware.Context) { tokens, err := models.ListAccessTokens(ctx.User.Id) if err != nil { @@ -30,7 +30,7 @@ type CreateAccessTokenForm struct { Name string `json:"name" binding:"Required"` } -// POST /users/:username/tokens +// https://github.com/gogits/go-gogs-client/wiki/Users#create-a-access-token func CreateAccessToken(ctx *middleware.Context, form CreateAccessTokenForm) { t := &models.AccessToken{ UID: ctx.User.Id, diff --git a/routers/api/v1/user_keys.go b/routers/api/v1/user_keys.go new file mode 100644 index 0000000000..54a51ef3f3 --- /dev/null +++ b/routers/api/v1/user_keys.go @@ -0,0 +1,111 @@ +// Copyright 2015 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package v1 + +import ( + "github.com/Unknwon/com" + + api "github.com/gogits/go-gogs-client" + + "github.com/gogits/gogs/models" + "github.com/gogits/gogs/modules/middleware" + "github.com/gogits/gogs/modules/setting" +) + +func ToApiPublicKey(apiLink string, key *models.PublicKey) *api.PublicKey { + return &api.PublicKey{ + ID: key.ID, + Key: key.Content, + URL: apiLink + com.ToStr(key.ID), + Title: key.Name, + Created: key.Created, + } +} + +func composePublicKeysAPILink() string { + return setting.AppUrl + "api/v1/user/keys/" +} + +func listUserPublicKeys(ctx *middleware.Context, uid int64) { + keys, err := models.ListPublicKeys(uid) + if err != nil { + ctx.APIError(500, "ListPublicKeys", err) + return + } + + apiLink := composePublicKeysAPILink() + apiKeys := make([]*api.PublicKey, len(keys)) + for i := range keys { + apiKeys[i] = ToApiPublicKey(apiLink, keys[i]) + } + + ctx.JSON(200, &apiKeys) +} + +// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-public-keys-for-a-user +func ListUserPublicKeys(ctx *middleware.Context) { + user, err := models.GetUserByName(ctx.Params(":username")) + if err != nil { + if models.IsErrUserNotExist(err) { + ctx.Error(404) + } else { + ctx.APIError(500, "GetUserByName", err) + } + return + } + listUserPublicKeys(ctx, user.Id) +} + +// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-your-public-keys +func ListMyPublicKeys(ctx *middleware.Context) { + listUserPublicKeys(ctx, ctx.User.Id) +} + +// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#get-a-single-public-key +func GetUserPublicKey(ctx *middleware.Context) { + key, err := models.GetPublicKeyByID(ctx.ParamsInt64(":id")) + if err != nil { + if models.IsErrKeyNotExist(err) { + ctx.Error(404) + } else { + ctx.Handle(500, "GetPublicKeyByID", err) + } + return + } + + apiLink := composePublicKeysAPILink() + ctx.JSON(200, ToApiPublicKey(apiLink, key)) +} + +// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#create-a-public-key +func CreateUserPublicKey(ctx *middleware.Context, form api.CreateKeyOption) { + content, err := models.CheckPublicKeyString(form.Key) + if err != nil { + handleCheckKeyStringError(ctx, err) + return + } + + key, err := models.AddPublicKey(ctx.User.Id, form.Title, content) + if err != nil { + handleAddKeyError(ctx, err) + return + } + apiLink := composePublicKeysAPILink() + ctx.JSON(201, ToApiPublicKey(apiLink, key)) +} + +// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#delete-a-public-key +func DeleteUserPublicKey(ctx *middleware.Context) { + if err := models.DeletePublicKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { + if models.IsErrKeyAccessDenied(err) { + ctx.APIError(403, "", "You do not have access to this key") + } else { + ctx.APIError(500, "DeletePublicKey", err) + } + return + } + + ctx.Status(204) +} diff --git a/routers/repo/setting.go b/routers/repo/setting.go index 2d686cdd34..ec285234c4 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -717,7 +717,7 @@ func DeployKeysPost(ctx *middleware.Context, form auth.AddSSHKeyForm) { } func DeleteDeployKey(ctx *middleware.Context) { - if err := models.DeleteDeployKey(ctx.QueryInt64("id")); err != nil { + if err := models.DeleteDeployKey(ctx.User, ctx.QueryInt64("id")); err != nil { ctx.Flash.Error("DeleteDeployKey: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success")) diff --git a/routers/user/setting.go b/routers/user/setting.go index 2e825cf56f..f9704ba946 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -295,7 +295,7 @@ func SettingsSSHKeysPost(ctx *middleware.Context, form auth.AddSSHKeyForm) { } } - if err = models.AddPublicKey(ctx.User.Id, form.Title, content); err != nil { + if _, err = models.AddPublicKey(ctx.User.Id, form.Title, content); err != nil { ctx.Data["HasError"] = true switch { case models.IsErrKeyAlreadyExist(err): @@ -315,7 +315,7 @@ func SettingsSSHKeysPost(ctx *middleware.Context, form auth.AddSSHKeyForm) { } func DeleteSSHKey(ctx *middleware.Context) { - if err := models.DeletePublicKey(ctx.QueryInt64("id")); err != nil { + if err := models.DeletePublicKey(ctx.User, ctx.QueryInt64("id")); err != nil { ctx.Flash.Error("DeletePublicKey: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("settings.ssh_key_deletion_success")) diff --git a/templates/.VERSION b/templates/.VERSION index 70244eae42..c817bbcabe 100644 --- a/templates/.VERSION +++ b/templates/.VERSION @@ -1 +1 @@ -0.7.27.1202 Beta \ No newline at end of file +0.7.28.1203 Beta \ No newline at end of file