forgejo/routers/api/v1/user/key.go
Mathieu Fenniak 99984dac4d feat: remove admin-level permissions from repo-specific & public-only access tokens (#11468)
This PR is part of a series (#11311).

If the user authenticating to an API call is a Forgejo site administrator, or a Forgejo repo administrator, a wide variety of permission and ownership checks in the API are either bypassed, or are bypassable.  If a user has created an access token with restricted resources, I understand the intent of the user is to create a token which has a layer of risk reduction in the event that the token is lost/leaked to an attacker.  For this reason, it makes sense to me that restricted scope access tokens shouldn't inherit the owner's administrator access.

My intent is that repo-specific access tokens [will only be able to access specific authorization scopes](https://codeberg.org/forgejo/design/issues/50#issuecomment-11093951), probably: `repository:read`, `repository:write`, `issue:read`, `issue:write`, (`organization:read` / `user:read` maybe).  This means that *most* admin access is not intended to be affected by this because repo-specific access tokens won't have, for example, `admin:write` scope.  However, administrative access still grants elevated permissions in some areas that are relevant to these scopes, and need to be restricted:

- The `?sudo=otheruser` query parameter allows site administrators to impersonate other users in the API.
- Repository management rules are different for a site administrator, allowing them to create repos for another user, create repos in another organization, migrate a repository to an arbitrary owner, and transfer a repository to a prviate organization.
- Administrators have access to extra data through some APIs which would be in scope: the detailed configuration of branch protection rules, the some details of repository deploy keys (which repo, and which scope -- seems odd), (user:read -- user SSH keys, activity feeds of private users, user profiles of private users, user webhook configurations).
- Pull request reviews have additional perms for repo administrators, including the ability to dismiss PR reviews, delete PR reviews, and view draft PR reviews.
- Repo admins and site admins can comment on locked issues, and related to comments can edit or delete other user's comments and attachments.
- Repo admins can manage and view logged time on behalf of other users.

A handful of these permissions may make sense for repo-specific access tokens, but most of them clearly exceed the risk that would be expected from creating a limited scope access token.  I'd generally prefer to take a restrictive approach, and we can relax it if real-world use-cases come in -- users will have a workaround of creating an access token without repo-specific restrictions if they are blocked from needed access.

**Breaking:** The administration restrictions introduced in this PR affect both repo-specific access tokens, and existing public-only access tokens.

## Checklist

The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org).

### Tests for Go changes

(can be removed for JavaScript changes)

- I added test coverage for Go changes...
  - [x] in their respective `*_test.go` for unit tests.
  - [x] in the `tests/integration` directory if it involves interactions with a live Forgejo server.
- I ran...
  - [x] `make pr-go` before pushing

### Documentation

- [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change.
- [x] I did not document these changes and I do not expect someone else to do it.

### Release notes

- [x] This change will be noticed by a Forgejo user or admin (feature, bug fix, performance, etc.). I suggest to include a release note for this change.
    - Although repo-specific access tokens are not yet exposed to end users, the breaking changes to public-only tokens will be visible to users and require release notes.
- [ ] This change is not visible to a Forgejo user or admin (refactor, dependency upgrade, etc.). I think there is no need to add a release note for this change.

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/11468
Reviewed-by: Andreas Ahlenstorf <aahlenst@noreply.codeberg.org>
Co-authored-by: Mathieu Fenniak <mathieu@fenniak.net>
Co-committed-by: Mathieu Fenniak <mathieu@fenniak.net>
2026-03-04 16:17:41 +01:00

318 lines
8.5 KiB
Go

// Copyright 2015 The Gogs Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package user
import (
std_ctx "context"
"errors"
"net/http"
asymkey_model "forgejo.org/models/asymkey"
"forgejo.org/models/db"
"forgejo.org/models/perm"
user_model "forgejo.org/models/user"
"forgejo.org/modules/setting"
api "forgejo.org/modules/structs"
"forgejo.org/modules/web"
"forgejo.org/routers/api/v1/repo"
"forgejo.org/routers/api/v1/utils"
asymkey_service "forgejo.org/services/asymkey"
"forgejo.org/services/context"
"forgejo.org/services/convert"
)
// appendPrivateInformation appends the owner and key type information to api.PublicKey
func appendPrivateInformation(ctx std_ctx.Context, apiKey *api.PublicKey, key *asymkey_model.PublicKey, defaultUser *user_model.User) (*api.PublicKey, error) {
switch key.Type {
case asymkey_model.KeyTypeDeploy:
apiKey.KeyType = "deploy"
case asymkey_model.KeyTypeUser:
apiKey.KeyType = "user"
if defaultUser.ID == key.OwnerID {
apiKey.Owner = convert.ToUser(ctx, defaultUser, defaultUser)
} else {
user, err := user_model.GetUserByID(ctx, key.OwnerID)
if err != nil {
return apiKey, err
}
apiKey.Owner = convert.ToUser(ctx, user, user)
}
default:
apiKey.KeyType = "unknown"
}
apiKey.ReadOnly = key.Mode == perm.AccessModeRead
return apiKey, nil
}
func composePublicKeysAPILink() string {
return setting.AppURL + "api/v1/user/keys/"
}
func listPublicKeys(ctx *context.APIContext, user *user_model.User) {
var keys []*asymkey_model.PublicKey
var err error
var count int
fingerprint := ctx.FormString("fingerprint")
username := ctx.Params("username")
if fingerprint != "" {
var userID int64 // Unrestricted
// Querying not just listing
if username != "" {
// Restrict to provided uid
userID = user.ID
}
keys, err = db.Find[asymkey_model.PublicKey](ctx, asymkey_model.FindPublicKeyOptions{
OwnerID: userID,
Fingerprint: fingerprint,
})
count = len(keys)
} else {
var total int64
// Use ListPublicKeys
keys, total, err = db.FindAndCount[asymkey_model.PublicKey](ctx, asymkey_model.FindPublicKeyOptions{
ListOptions: utils.GetListOptions(ctx),
OwnerID: user.ID,
NotKeytype: asymkey_model.KeyTypePrincipal,
})
count = int(total)
}
if err != nil {
ctx.Error(http.StatusInternalServerError, "ListPublicKeys", err)
return
}
apiLink := composePublicKeysAPILink()
apiKeys := make([]*api.PublicKey, len(keys))
for i := range keys {
apiKeys[i] = convert.ToPublicKey(apiLink, keys[i])
if ctx.IsUserSiteAdmin() || ctx.Doer.ID == keys[i].OwnerID {
apiKeys[i], _ = appendPrivateInformation(ctx, apiKeys[i], keys[i], user)
}
}
ctx.SetTotalCountHeader(int64(count))
ctx.JSON(http.StatusOK, &apiKeys)
}
// ListMyPublicKeys list all of the authenticated user's public keys
func ListMyPublicKeys(ctx *context.APIContext) {
// swagger:operation GET /user/keys user userCurrentListKeys
// ---
// summary: List the authenticated user's public keys
// parameters:
// - name: fingerprint
// in: query
// description: fingerprint of the key
// type: string
// - name: page
// in: query
// description: page number of results to return (1-based)
// type: integer
// - name: limit
// in: query
// description: page size of results
// type: integer
// produces:
// - application/json
// responses:
// "200":
// "$ref": "#/responses/PublicKeyList"
// "401":
// "$ref": "#/responses/unauthorized"
// "403":
// "$ref": "#/responses/forbidden"
listPublicKeys(ctx, ctx.Doer)
}
// ListPublicKeys list the given user's public keys
func ListPublicKeys(ctx *context.APIContext) {
// swagger:operation GET /users/{username}/keys user userListKeys
// ---
// summary: List the given user's public keys
// produces:
// - application/json
// parameters:
// - name: username
// in: path
// description: username of user
// type: string
// required: true
// - name: fingerprint
// in: query
// description: fingerprint of the key
// type: string
// - name: page
// in: query
// description: page number of results to return (1-based)
// type: integer
// - name: limit
// in: query
// description: page size of results
// type: integer
// responses:
// "200":
// "$ref": "#/responses/PublicKeyList"
// "404":
// "$ref": "#/responses/notFound"
listPublicKeys(ctx, ctx.ContextUser)
}
// GetPublicKey get a public key
func GetPublicKey(ctx *context.APIContext) {
// swagger:operation GET /user/keys/{id} user userCurrentGetKey
// ---
// summary: Get a public key
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id of key to get
// type: integer
// format: int64
// required: true
// responses:
// "200":
// "$ref": "#/responses/PublicKey"
// "401":
// "$ref": "#/responses/unauthorized"
// "403":
// "$ref": "#/responses/forbidden"
// "404":
// "$ref": "#/responses/notFound"
key, err := asymkey_model.GetPublicKeyByID(ctx, ctx.ParamsInt64(":id"))
if err != nil {
if asymkey_model.IsErrKeyNotExist(err) {
ctx.NotFound()
} else {
ctx.Error(http.StatusInternalServerError, "GetPublicKeyByID", err)
}
return
}
apiLink := composePublicKeysAPILink()
apiKey := convert.ToPublicKey(apiLink, key)
if ctx.IsUserSiteAdmin() || ctx.Doer.ID == key.OwnerID {
apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Doer)
}
ctx.JSON(http.StatusOK, apiKey)
}
// CreateUserPublicKey creates new public key to given user by ID.
func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid int64) {
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys) {
ctx.NotFound("Not Found", errors.New("ssh keys setting is not allowed to be visited"))
return
}
content, err := asymkey_model.CheckPublicKeyString(form.Key)
if err != nil {
repo.HandleCheckKeyStringError(ctx, err)
return
}
key, err := asymkey_model.AddPublicKey(ctx, uid, form.Title, content, 0)
if err != nil {
repo.HandleAddKeyError(ctx, err)
return
}
apiLink := composePublicKeysAPILink()
apiKey := convert.ToPublicKey(apiLink, key)
if ctx.IsUserSiteAdmin() || ctx.Doer.ID == key.OwnerID {
apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Doer)
}
ctx.JSON(http.StatusCreated, apiKey)
}
// CreatePublicKey create one public key for me
func CreatePublicKey(ctx *context.APIContext) {
// swagger:operation POST /user/keys user userCurrentPostKey
// ---
// summary: Create a public key
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - name: body
// in: body
// schema:
// "$ref": "#/definitions/CreateKeyOption"
// responses:
// "201":
// "$ref": "#/responses/PublicKey"
// "401":
// "$ref": "#/responses/unauthorized"
// "403":
// "$ref": "#/responses/forbidden"
// "422":
// "$ref": "#/responses/validationError"
form := web.GetForm(ctx).(*api.CreateKeyOption)
CreateUserPublicKey(ctx, *form, ctx.Doer.ID)
}
// DeletePublicKey delete one public key
func DeletePublicKey(ctx *context.APIContext) {
// swagger:operation DELETE /user/keys/{id} user userCurrentDeleteKey
// ---
// summary: Delete a public key
// produces:
// - application/json
// parameters:
// - name: id
// in: path
// description: id of key to delete
// type: integer
// format: int64
// required: true
// responses:
// "204":
// "$ref": "#/responses/empty"
// "401":
// "$ref": "#/responses/unauthorized"
// "403":
// "$ref": "#/responses/forbidden"
// "404":
// "$ref": "#/responses/notFound"
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageSSHKeys) {
ctx.NotFound("Not Found", errors.New("ssh keys setting is not allowed to be visited"))
return
}
id := ctx.ParamsInt64(":id")
externallyManaged, err := asymkey_model.PublicKeyIsExternallyManaged(ctx, id)
if err != nil {
if asymkey_model.IsErrKeyNotExist(err) {
ctx.NotFound()
} else {
ctx.Error(http.StatusInternalServerError, "PublicKeyIsExternallyManaged", err)
}
return
}
if externallyManaged {
ctx.Error(http.StatusForbidden, "", "SSH Key is externally managed for this user")
return
}
if err := asymkey_service.DeletePublicKey(ctx, ctx.Doer, id); err != nil {
if asymkey_model.IsErrKeyAccessDenied(err) {
ctx.Error(http.StatusForbidden, "", "You do not have access to this key")
} else {
ctx.Error(http.StatusInternalServerError, "DeletePublicKey", err)
}
return
}
ctx.Status(http.StatusNoContent)
}