feat: add deploy tokens (#37306)

Deploy keys only work over SSH. A deploy token is their counterpart for HTTPS: a repository scoped credential, used as the password of a Git request, with read or read and write access. It covers Git operations and LFS, and can be regenerated in place.

Signed-off-by: silverwind <me@silverwind.io>
Co-authored-by: Claude Mythos <noreply@anthropic.com>
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: bircni <bircni@icloud.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
ToastyTheBot
2026-08-27 03:32:44 +08:00
committed by GitHub
parent 3c4d5a6a5c
commit 646ea0f253
76 changed files with 1594 additions and 831 deletions
+31 -2
View File
@@ -11,6 +11,7 @@ import (
asymkey_model "gitea.dev/models/asymkey"
auth_model "gitea.dev/models/auth"
deploykey_model "gitea.dev/models/deploykey"
"gitea.dev/models/perm"
repo_model "gitea.dev/models/repo"
"gitea.dev/models/unittest"
@@ -66,7 +67,7 @@ func TestCreateReadOnlyDeployKey(t *testing.T) {
resp := MakeRequest(t, req, http.StatusCreated)
newDeployKey := DecodeJSON(t, resp, &api.DeployKey{})
unittest.AssertExistsAndLoadBean(t, &asymkey_model.DeployKey{
unittest.AssertExistsAndLoadBean(t, &deploykey_model.DeployKey{
ID: newDeployKey.ID,
Name: rawKeyBody.Title,
Mode: perm.AccessModeRead,
@@ -103,7 +104,7 @@ func TestCreateReadWriteDeployKey(t *testing.T) {
resp := MakeRequest(t, req, http.StatusCreated)
newDeployKey := DecodeJSON(t, resp, &api.DeployKey{})
unittest.AssertExistsAndLoadBean(t, &asymkey_model.DeployKey{
unittest.AssertExistsAndLoadBean(t, &deploykey_model.DeployKey{
ID: newDeployKey.ID,
Name: rawKeyBody.Title,
Mode: perm.AccessModeWrite,
@@ -204,3 +205,31 @@ func TestCreateUserKey(t *testing.T) {
fingerprintPublicKeys = DecodeJSON(t, resp, []api.PublicKey{})
assert.Empty(t, fingerprintPublicKeys)
}
func TestCreateDeployToken(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: "repo1"})
repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID})
session := loginUser(t, repoOwner.Name)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys", repoOwner.Name, repo.Name)
req := NewRequestWithJSON(t, "POST", keysURL+"/tokens", api.CreateDeployKeyTokenOption{Title: "ci", ReadOnly: true}).
AddTokenAuth(token)
created := DecodeJSON(t, MakeRequest(t, req, http.StatusCreated), &api.DeployKey{})
assert.NotEmpty(t, created.Token)
assert.True(t, created.ReadOnly)
// a token is listed and deleted like a deploy key, but it is never readable again
resp := MakeRequest(t, NewRequest(t, "GET", keysURL).AddTokenAuth(token), http.StatusOK)
listed := DecodeJSON(t, resp, []api.DeployKey{})
assert.Len(t, listed, 1)
assert.NotContains(t, resp.Body.String(), created.Token)
assert.Equal(t, created.Fingerprint, listed[0].Fingerprint)
assert.Contains(t, created.Fingerprint, "********")
MakeRequest(t, NewRequest(t, "DELETE", fmt.Sprintf("%s/%d", keysURL, created.ID)).AddTokenAuth(token), http.StatusNoContent)
resp = MakeRequest(t, NewRequest(t, "GET", keysURL).AddTokenAuth(token), http.StatusOK)
assert.Empty(t, DecodeJSON(t, resp, []api.DeployKey{}))
}
+22 -25
View File
@@ -8,8 +8,9 @@ import (
"net/url"
"testing"
asymkey_model "gitea.dev/models/asymkey"
deploykey_model "gitea.dev/models/deploykey"
"gitea.dev/models/perm"
"gitea.dev/models/user"
"gitea.dev/modules/private"
"github.com/stretchr/testify/assert"
@@ -27,7 +28,7 @@ func TestAPIPrivateNoServ(t *testing.T) {
assert.Equal(t, "user2@localhost", key.Name)
keyContent := "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment"
deployKey, err := asymkey_model.AddDeployKey(ctx, 1, "test-deploy", keyContent, perm.AccessModeRead)
deployKey, err := deploykey_model.AddDeployKeySSH(ctx, 1, "test-deploy", keyContent, perm.AccessModeRead)
assert.NoError(t, err)
key, user, err = private.ServNoCommand(ctx, deployKey.KeyID)
@@ -47,9 +48,8 @@ func TestAPIPrivateServ(t *testing.T) {
results, extra := private.ServCommand(ctx, 1, "user2", "repo1", perm.AccessModeWrite, "git-upload-pack", "")
assert.NoError(t, extra.Error)
assert.False(t, results.IsWiki)
assert.Zero(t, results.DeployKeyID)
assert.Equal(t, int64(1), results.KeyID)
assert.Equal(t, "user2@localhost", results.KeyName)
assert.Empty(t, results.UserExtDoerData)
assert.Equal(t, int64(1), results.PublicKeyID)
assert.Equal(t, "user2", results.UserName)
assert.Equal(t, int64(2), results.UserID)
assert.Equal(t, "user2", results.OwnerName)
@@ -70,9 +70,8 @@ func TestAPIPrivateServ(t *testing.T) {
results, extra = private.ServCommand(ctx, 1, "user15", "big_test_public_1", perm.AccessModeRead, "git-upload-pack", "")
assert.NoError(t, extra.Error)
assert.False(t, results.IsWiki)
assert.Zero(t, results.DeployKeyID)
assert.Equal(t, int64(1), results.KeyID)
assert.Equal(t, "user2@localhost", results.KeyName)
assert.Empty(t, results.UserExtDoerData)
assert.Equal(t, int64(1), results.PublicKeyID)
assert.Equal(t, "user2", results.UserName)
assert.Equal(t, int64(2), results.UserID)
assert.Equal(t, "user15", results.OwnerName)
@@ -86,18 +85,18 @@ func TestAPIPrivateServ(t *testing.T) {
// Add reading deploy key
testContent := "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment"
deployKey, err := asymkey_model.AddDeployKey(ctx, 19 /* repo id */, "test-deploy", testContent, perm.AccessModeRead)
deployKey, err := deploykey_model.AddDeployKeySSH(ctx, 19 /* repo id */, "test-deploy", testContent, perm.AccessModeRead)
assert.NoError(t, err)
// Can pull from repo we're a deploy-key for
deployKeyUser := user.NewDeployKeyUser()
results, extra = private.ServCommand(ctx, deployKey.KeyID, "user15", "big_test_private_1", perm.AccessModeRead, "git-upload-pack", "")
assert.NoError(t, extra.Error)
assert.False(t, results.IsWiki)
assert.NotZero(t, results.DeployKeyID)
assert.Equal(t, deployKey.KeyID, results.KeyID)
assert.Equal(t, "test-deploy", results.KeyName)
assert.Equal(t, "user15", results.UserName)
assert.Equal(t, int64(15), results.UserID)
assert.NotEmpty(t, results.UserExtDoerData)
assert.Equal(t, deployKey.KeyID, results.PublicKeyID)
assert.Equal(t, deployKeyUser.Name, results.UserName)
assert.Equal(t, deployKeyUser.ID, results.UserID)
assert.Equal(t, "user15", results.OwnerName)
assert.Equal(t, "big_test_private_1", results.RepoName)
assert.Equal(t, int64(19), results.RepoID)
@@ -119,7 +118,7 @@ func TestAPIPrivateServ(t *testing.T) {
// Add writing deploy key
testContent = "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment"
deployKey, err = asymkey_model.AddDeployKey(ctx, 20 /* repo id */, "test-deploy", testContent, perm.AccessModeWrite)
deployKey, err = deploykey_model.AddDeployKeySSH(ctx, 20 /* repo id */, "test-deploy", testContent, perm.AccessModeWrite)
assert.NoError(t, err)
// Cannot push to a private repo with reading key
@@ -131,11 +130,10 @@ func TestAPIPrivateServ(t *testing.T) {
results, extra = private.ServCommand(ctx, deployKey.KeyID, "user15", "big_test_private_2", perm.AccessModeRead, "git-upload-pack", "")
assert.NoError(t, extra.Error)
assert.False(t, results.IsWiki)
assert.NotZero(t, results.DeployKeyID)
assert.Equal(t, deployKey.KeyID, results.KeyID)
assert.Equal(t, "test-deploy", results.KeyName)
assert.Equal(t, "user15", results.UserName)
assert.Equal(t, int64(15), results.UserID)
assert.NotEmpty(t, results.UserExtDoerData)
assert.Equal(t, deployKey.KeyID, results.PublicKeyID)
assert.Equal(t, deployKeyUser.Name, results.UserName)
assert.Equal(t, deployKeyUser.ID, results.UserID)
assert.Equal(t, "user15", results.OwnerName)
assert.Equal(t, "big_test_private_2", results.RepoName)
assert.Equal(t, int64(20), results.RepoID)
@@ -144,11 +142,10 @@ func TestAPIPrivateServ(t *testing.T) {
results, extra = private.ServCommand(ctx, deployKey.KeyID, "user15", "big_test_private_2", perm.AccessModeWrite, "git-upload-pack", "")
assert.NoError(t, extra.Error)
assert.False(t, results.IsWiki)
assert.NotZero(t, results.DeployKeyID)
assert.Equal(t, deployKey.KeyID, results.KeyID)
assert.Equal(t, "test-deploy", results.KeyName)
assert.Equal(t, "user15", results.UserName)
assert.Equal(t, int64(15), results.UserID)
assert.NotEmpty(t, results.UserExtDoerData)
assert.Equal(t, deployKey.KeyID, results.PublicKeyID)
assert.Equal(t, deployKeyUser.Name, results.UserName)
assert.Equal(t, deployKeyUser.ID, results.UserID)
assert.Equal(t, "user15", results.OwnerName)
assert.Equal(t, "big_test_private_2", results.RepoName)
assert.Equal(t, int64(20), results.RepoID)
+76
View File
@@ -0,0 +1,76 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package integration
import (
"net/http"
"testing"
deploykey_model "gitea.dev/models/deploykey"
"gitea.dev/models/perm"
repo_model "gitea.dev/models/repo"
"gitea.dev/models/unittest"
"gitea.dev/modules/git"
lfs_module "gitea.dev/modules/lfs"
"gitea.dev/modules/setting"
"gitea.dev/modules/test"
"gitea.dev/tests"
"github.com/stretchr/testify/require"
)
func TestDeployTokenGitHTTP(t *testing.T) {
defer tests.PrepareTestEnv(t)()
// need to disable agit, otherwise the "write" permission check is skipped at pre-receive (git-receive-pack) step
defer test.MockVariableValue(&git.DefaultFeatures().SupportProcReceive, false)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
otherRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
readKey, err := deploykey_model.AddDeployKeyToken(t.Context(), repo.ID, "read", perm.AccessModeRead)
require.NoError(t, err)
writeKey, err := deploykey_model.AddDeployKeyToken(t.Context(), repo.ID, "write", perm.AccessModeWrite)
require.NoError(t, err)
requestAs := func(t *testing.T, token, path string, expected int) {
MakeRequest(t, NewRequest(t, "GET", path).AddBasicAuth("deploy-token", token), expected)
}
t.Run("Clone", func(t *testing.T) {
requestAs(t, readKey.Token, "/"+repo.FullName()+"/info/refs?service=git-upload-pack", http.StatusOK)
})
t.Run("PushWithReadToken", func(t *testing.T) {
requestAs(t, readKey.Token, "/"+repo.FullName()+"/info/refs?service=git-receive-pack", http.StatusNotFound)
})
t.Run("PushWithWriteToken", func(t *testing.T) {
requestAs(t, writeKey.Token, "/"+repo.FullName()+"/info/refs?service=git-receive-pack", http.StatusOK)
})
t.Run("OtherRepo", func(t *testing.T) {
requestAs(t, readKey.Token, "/"+otherRepo.FullName()+"/info/refs?service=git-upload-pack", http.StatusNotFound)
})
t.Run("UnknownToken", func(t *testing.T) {
requestAs(t, deploykey_model.DeployTokenPrefix+"0123456789abcdef", "/"+repo.FullName()+"/info/refs?service=git-upload-pack", http.StatusUnauthorized)
})
t.Run("RejectedOutsideGitHTTP", func(t *testing.T) {
// the owner of the repo would be able to read it, the token must not act as that owner
requestAs(t, readKey.Token, "/api/v1/repos/"+repo.FullName(), http.StatusUnauthorized)
})
t.Run("LFS", func(t *testing.T) {
defer test.MockVariableValue(&setting.LFS.StartServer, true)()
batchAs := func(t *testing.T, token, repoName, operation string, expected int) {
req := NewRequestWithJSON(t, "POST", "/"+repoName+"/info/lfs/objects/batch", lfs_module.BatchRequest{Operation: operation}).
AddBasicAuth("deploy-token", token).
SetHeader("Accept", lfs_module.AcceptHeader).
SetHeader("Content-Type", lfs_module.MediaType)
MakeRequest(t, req, expected)
}
batchAs(t, readKey.Token, repo.FullName(), "download", http.StatusOK)
batchAs(t, readKey.Token, repo.FullName(), "upload", http.StatusUnauthorized)
batchAs(t, writeKey.Token, repo.FullName(), "upload", http.StatusOK)
batchAs(t, readKey.Token, otherRepo.FullName(), "download", http.StatusUnauthorized)
})
}
+1 -1
View File
@@ -171,7 +171,7 @@ func doSSHLFSAccessTest(_ APITestContext, keyID int64) func(*testing.T) {
_, err := cmd.Output()
var errExit *exec.ExitError
require.ErrorAs(t, err, &errExit) // inaccessible, error
assert.Contains(t, string(errExit.Stderr), fmt.Sprintf(`User 2 with key %d:test-key has no "write" permission for user5/repo4`, keyID))
assert.Contains(t, string(errExit.Stderr), `has no "write" permission for user5/repo4`)
})
}
}