mirror of
https://github.com/go-gitea/gitea.git
synced 2025-07-04 00:01:16 -04:00
Compare commits
1 Commits
904a982120
...
12abcc132a
Author | SHA1 | Date | |
---|---|---|---|
|
12abcc132a |
@ -715,8 +715,7 @@ func (c *Comment) LoadReactions(ctx context.Context, repo *repo_model.Repository
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadReview loads the associated review
|
||||
func (c *Comment) LoadReview(ctx context.Context) (err error) {
|
||||
func (c *Comment) loadReview(ctx context.Context) (err error) {
|
||||
if c.ReviewID == 0 {
|
||||
return nil
|
||||
}
|
||||
@ -733,6 +732,11 @@ func (c *Comment) LoadReview(ctx context.Context) (err error) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadReview loads the associated review
|
||||
func (c *Comment) LoadReview(ctx context.Context) error {
|
||||
return c.loadReview(ctx)
|
||||
}
|
||||
|
||||
// DiffSide returns "previous" if Comment.Line is a LOC of the previous changes and "proposed" if it is a LOC of the proposed changes.
|
||||
func (c *Comment) DiffSide() string {
|
||||
if c.Line < 0 {
|
||||
@ -852,7 +856,7 @@ func updateCommentInfos(ctx context.Context, opts *CreateCommentOptions, comment
|
||||
}
|
||||
if comment.ReviewID != 0 {
|
||||
if comment.Review == nil {
|
||||
if err := comment.LoadReview(ctx); err != nil {
|
||||
if err := comment.loadReview(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
@ -1,47 +0,0 @@
|
||||
// Copyright 2025 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package httpauth
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
)
|
||||
|
||||
type BasicAuth struct {
|
||||
Username, Password string
|
||||
}
|
||||
|
||||
type BearerToken struct {
|
||||
Token string
|
||||
}
|
||||
|
||||
type ParsedAuthorizationHeader struct {
|
||||
BasicAuth *BasicAuth
|
||||
BearerToken *BearerToken
|
||||
}
|
||||
|
||||
func ParseAuthorizationHeader(header string) (ret ParsedAuthorizationHeader, _ bool) {
|
||||
parts := strings.Fields(header)
|
||||
if len(parts) != 2 {
|
||||
return ret, false
|
||||
}
|
||||
if util.AsciiEqualFold(parts[0], "basic") {
|
||||
s, err := base64.StdEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return ret, false
|
||||
}
|
||||
u, p, ok := strings.Cut(string(s), ":")
|
||||
if !ok {
|
||||
return ret, false
|
||||
}
|
||||
ret.BasicAuth = &BasicAuth{Username: u, Password: p}
|
||||
return ret, true
|
||||
} else if util.AsciiEqualFold(parts[0], "token") || util.AsciiEqualFold(parts[0], "bearer") {
|
||||
ret.BearerToken = &BearerToken{Token: parts[1]}
|
||||
return ret, true
|
||||
}
|
||||
return ret, false
|
||||
}
|
@ -1,43 +0,0 @@
|
||||
// Copyright 2025 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package httpauth
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestParseAuthorizationHeader(t *testing.T) {
|
||||
type parsed = ParsedAuthorizationHeader
|
||||
type basic = BasicAuth
|
||||
type bearer = BearerToken
|
||||
cases := []struct {
|
||||
headerValue string
|
||||
expected parsed
|
||||
ok bool
|
||||
}{
|
||||
{"", parsed{}, false},
|
||||
{"?", parsed{}, false},
|
||||
{"foo", parsed{}, false},
|
||||
{"any value", parsed{}, false},
|
||||
|
||||
{"Basic ?", parsed{}, false},
|
||||
{"Basic " + base64.StdEncoding.EncodeToString([]byte("foo")), parsed{}, false},
|
||||
{"Basic " + base64.StdEncoding.EncodeToString([]byte("foo:bar")), parsed{BasicAuth: &basic{"foo", "bar"}}, true},
|
||||
{"basic " + base64.StdEncoding.EncodeToString([]byte("foo:bar")), parsed{BasicAuth: &basic{"foo", "bar"}}, true},
|
||||
|
||||
{"token value", parsed{BearerToken: &bearer{"value"}}, true},
|
||||
{"Token value", parsed{BearerToken: &bearer{"value"}}, true},
|
||||
{"bearer value", parsed{BearerToken: &bearer{"value"}}, true},
|
||||
{"Bearer value", parsed{BearerToken: &bearer{"value"}}, true},
|
||||
{"Bearer wrong value", parsed{}, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
ret, ok := ParseAuthorizationHeader(c.headerValue)
|
||||
assert.Equal(t, c.ok, ok, "header %q", c.headerValue)
|
||||
assert.Equal(t, c.expected, ret, "header %q", c.headerValue)
|
||||
}
|
||||
}
|
@ -8,10 +8,13 @@ import (
|
||||
"crypto/sha1"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
@ -33,6 +36,19 @@ func ShortSha(sha1 string) string {
|
||||
return util.TruncateRunes(sha1, 10)
|
||||
}
|
||||
|
||||
// BasicAuthDecode decode basic auth string
|
||||
func BasicAuthDecode(encoded string) (string, string, error) {
|
||||
s, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
if username, password, ok := strings.Cut(string(s), ":"); ok {
|
||||
return username, password, nil
|
||||
}
|
||||
return "", "", errors.New("invalid basic authentication")
|
||||
}
|
||||
|
||||
// VerifyTimeLimitCode verify time limit code
|
||||
func VerifyTimeLimitCode(now time.Time, data string, minutes int, code string) bool {
|
||||
if len(code) <= 18 {
|
||||
|
@ -26,6 +26,25 @@ func TestShortSha(t *testing.T) {
|
||||
assert.Equal(t, "veryverylo", ShortSha("veryverylong"))
|
||||
}
|
||||
|
||||
func TestBasicAuthDecode(t *testing.T) {
|
||||
_, _, err := BasicAuthDecode("?")
|
||||
assert.Equal(t, "illegal base64 data at input byte 0", err.Error())
|
||||
|
||||
user, pass, err := BasicAuthDecode("Zm9vOmJhcg==")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "foo", user)
|
||||
assert.Equal(t, "bar", pass)
|
||||
|
||||
_, _, err = BasicAuthDecode("aW52YWxpZA==")
|
||||
assert.Error(t, err)
|
||||
|
||||
_, _, err = BasicAuthDecode("invalid")
|
||||
assert.Error(t, err)
|
||||
|
||||
_, _, err = BasicAuthDecode("YWxpY2U=") // "alice", no colon
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestVerifyTimeLimitCode(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.InstallLock, true)()
|
||||
initGeneralSecret := func(secret string) {
|
||||
|
@ -116,17 +116,14 @@ type ContentsExtResponse struct {
|
||||
|
||||
// ContentsResponse contains information about a repo's entry's (dir, file, symlink, submodule) metadata and content
|
||||
type ContentsResponse struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
SHA string `json:"sha"`
|
||||
|
||||
LastCommitSHA *string `json:"last_commit_sha,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
SHA string `json:"sha"`
|
||||
LastCommitSHA string `json:"last_commit_sha"`
|
||||
// swagger:strfmt date-time
|
||||
LastCommitterDate *time.Time `json:"last_committer_date,omitempty"`
|
||||
LastCommitterDate time.Time `json:"last_committer_date"`
|
||||
// swagger:strfmt date-time
|
||||
LastAuthorDate *time.Time `json:"last_author_date,omitempty"`
|
||||
LastCommitMessage *string `json:"last_commit_message,omitempty"`
|
||||
|
||||
LastAuthorDate time.Time `json:"last_author_date"`
|
||||
// `type` will be `file`, `dir`, `symlink`, or `submodule`
|
||||
Type string `json:"type"`
|
||||
Size int64 `json:"size"`
|
||||
@ -144,8 +141,8 @@ type ContentsResponse struct {
|
||||
SubmoduleGitURL *string `json:"submodule_git_url"`
|
||||
Links *FileLinksResponse `json:"_links"`
|
||||
|
||||
LfsOid *string `json:"lfs_oid,omitempty"`
|
||||
LfsSize *int64 `json:"lfs_size,omitempty"`
|
||||
LfsOid *string `json:"lfs_oid"`
|
||||
LfsSize *int64 `json:"lfs_size"`
|
||||
}
|
||||
|
||||
// FileCommitResponse contains information generated from a Git commit for a repo's file.
|
||||
|
@ -110,24 +110,3 @@ func SplitTrimSpace(input, sep string) []string {
|
||||
}
|
||||
return stringList
|
||||
}
|
||||
|
||||
func asciiLower(b byte) byte {
|
||||
if 'A' <= b && b <= 'Z' {
|
||||
return b + ('a' - 'A')
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// AsciiEqualFold is from Golang https://cs.opensource.google/go/go/+/refs/tags/go1.24.4:src/net/http/internal/ascii/print.go
|
||||
// ASCII only. In most cases for protocols, we should only use this but not [strings.EqualFold]
|
||||
func AsciiEqualFold(s, t string) bool { //nolint:revive // PascalCase
|
||||
if len(s) != len(t) {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(s); i++ {
|
||||
if asciiLower(s[i]) != asciiLower(t[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
@ -1969,7 +1969,6 @@ pulls.cmd_instruction_checkout_title=Basculer
|
||||
pulls.cmd_instruction_checkout_desc=Depuis votre dépôt, basculer sur une nouvelle branche et tester des modifications.
|
||||
pulls.cmd_instruction_merge_title=Fusionner
|
||||
pulls.cmd_instruction_merge_desc=Fusionner les modifications et mettre à jour sur Gitea.
|
||||
pulls.cmd_instruction_merge_warning=Attention : cette opération ne peut pas fusionner la demande d’ajout car la « détection automatique de fusion manuelle » n’a pas été activée
|
||||
pulls.clear_merge_message=Effacer le message de fusion
|
||||
pulls.clear_merge_message_hint=Effacer le message de fusion ne supprimera que le message de la révision, mais pas les pieds de révision générés tels que "Co-Authored-By:".
|
||||
|
||||
@ -2769,8 +2768,6 @@ branch.new_branch_from=`Créer une nouvelle branche à partir de "%s"`
|
||||
branch.renamed=La branche %s à été renommée en %s.
|
||||
branch.rename_default_or_protected_branch_error=Seuls les administrateurs peuvent renommer les branches par défaut ou protégées.
|
||||
branch.rename_protected_branch_failed=Cette branche est protégée par des règles de protection basées sur des globs.
|
||||
branch.commits_divergence_from=Divergence de révisions : %[1]d en retard et %[2]d en avance sur %[3]s
|
||||
branch.commits_no_divergence=Identique à la branche %[1]s
|
||||
|
||||
tag.create_tag=Créer l'étiquette %s
|
||||
tag.create_tag_operation=Créer une étiquette
|
||||
|
@ -2769,8 +2769,6 @@ branch.new_branch_from=`Cruthaigh brainse nua ó "%s"`
|
||||
branch.renamed=Ainmníodh brainse %s go %s.
|
||||
branch.rename_default_or_protected_branch_error=Ní féidir ach le riarthóirí brainsí réamhshocraithe nó cosanta a athainmniú.
|
||||
branch.rename_protected_branch_failed=Tá an brainse seo faoi chosaint ag rialacha cosanta domhanda.
|
||||
branch.commits_divergence_from=Déanann sé dialltacht a thiomnú: %[1]d taobh thiar agus %[2]d chun tosaigh ar %[3]s
|
||||
branch.commits_no_divergence=Mar an gcéanna le brainse %[1]s
|
||||
|
||||
tag.create_tag=Cruthaigh clib %s
|
||||
tag.create_tag_operation=Cruthaigh clib
|
||||
|
@ -2769,8 +2769,6 @@ branch.new_branch_from=`Criar um novo ramo a partir do ramo "%s"`
|
||||
branch.renamed=O ramo %s foi renomeado para %s.
|
||||
branch.rename_default_or_protected_branch_error=Só os administradores é que podem renomear o ramo principal ou ramos protegidos.
|
||||
branch.rename_protected_branch_failed=Este ramo está protegido por regras de salvaguarda baseadas em padrões glob.
|
||||
branch.commits_divergence_from=Divergência nos cometimentos: %[1]d atrás e %[2]d à frente de %[3]s
|
||||
branch.commits_no_divergence=Idêntico ao ramo %[1]s
|
||||
|
||||
tag.create_tag=Criar etiqueta %s
|
||||
tag.create_tag_operation=Criar etiqueta
|
||||
|
@ -812,8 +812,7 @@ func GetContentsExt(ctx *context.APIContext) {
|
||||
// required: true
|
||||
// - name: filepath
|
||||
// in: path
|
||||
// description: path of the dir, file, symlink or submodule in the repo. Swagger requires path parameter to be "required",
|
||||
// you can leave it empty or pass a single dot (".") to get the root directory.
|
||||
// description: path of the dir, file, symlink or submodule in the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: ref
|
||||
@ -824,8 +823,7 @@ func GetContentsExt(ctx *context.APIContext) {
|
||||
// - name: includes
|
||||
// in: query
|
||||
// description: By default this API's response only contains file's metadata. Use comma-separated "includes" options to retrieve more fields.
|
||||
// Option "file_content" will try to retrieve the file content, "lfs_metadata" will try to retrieve LFS metadata,
|
||||
// "commit_metadata" will try to retrieve commit metadata, and "commit_message" will try to retrieve commit message.
|
||||
// Option "file_content" will try to retrieve the file content, option "lfs_metadata" will try to retrieve LFS metadata.
|
||||
// type: string
|
||||
// required: false
|
||||
// responses:
|
||||
@ -834,9 +832,6 @@ func GetContentsExt(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
if treePath := ctx.PathParam("*"); treePath == "." || treePath == "/" {
|
||||
ctx.SetPathParam("*", "") // workaround for swagger, it requires path parameter to be "required", but we need to list root directory
|
||||
}
|
||||
opts := files_service.GetContentsOrListOptions{TreePath: ctx.PathParam("*")}
|
||||
for includeOpt := range strings.SplitSeq(ctx.FormString("includes"), ",") {
|
||||
if includeOpt == "" {
|
||||
@ -847,10 +842,6 @@ func GetContentsExt(ctx *context.APIContext) {
|
||||
opts.IncludeSingleFileContent = true
|
||||
case "lfs_metadata":
|
||||
opts.IncludeLfsMetadata = true
|
||||
case "commit_metadata":
|
||||
opts.IncludeCommitMetadata = true
|
||||
case "commit_message":
|
||||
opts.IncludeCommitMessage = true
|
||||
default:
|
||||
ctx.APIError(http.StatusBadRequest, fmt.Sprintf("unknown include option %q", includeOpt))
|
||||
return
|
||||
@ -892,11 +883,7 @@ func GetContents(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/ContentsResponse"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
ret := getRepoContents(ctx, files_service.GetContentsOrListOptions{
|
||||
TreePath: ctx.PathParam("*"),
|
||||
IncludeSingleFileContent: true,
|
||||
IncludeCommitMetadata: true,
|
||||
})
|
||||
ret := getRepoContents(ctx, files_service.GetContentsOrListOptions{TreePath: ctx.PathParam("*"), IncludeSingleFileContent: true})
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
@ -4,16 +4,18 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/models/auth"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/auth/httpauth"
|
||||
"code.gitea.io/gitea/modules/base"
|
||||
"code.gitea.io/gitea/modules/json"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
@ -106,8 +108,9 @@ func InfoOAuth(ctx *context.Context) {
|
||||
|
||||
var accessTokenScope auth.AccessTokenScope
|
||||
if auHead := ctx.Req.Header.Get("Authorization"); auHead != "" {
|
||||
if parsed, ok := httpauth.ParseAuthorizationHeader(auHead); ok && parsed.BearerToken != nil {
|
||||
accessTokenScope, _ = auth_service.GetOAuthAccessTokenScopeAndUserID(ctx, parsed.BearerToken.Token)
|
||||
auths := strings.Fields(auHead)
|
||||
if len(auths) == 2 && (auths[0] == "token" || strings.ToLower(auths[0]) == "bearer") {
|
||||
accessTokenScope, _ = auth_service.GetOAuthAccessTokenScopeAndUserID(ctx, auths[1])
|
||||
}
|
||||
}
|
||||
|
||||
@ -124,12 +127,18 @@ func InfoOAuth(ctx *context.Context) {
|
||||
ctx.JSON(http.StatusOK, response)
|
||||
}
|
||||
|
||||
func parseBasicAuth(ctx *context.Context) (username, password string, err error) {
|
||||
authHeader := ctx.Req.Header.Get("Authorization")
|
||||
if authType, authData, ok := strings.Cut(authHeader, " "); ok && strings.EqualFold(authType, "Basic") {
|
||||
return base.BasicAuthDecode(authData)
|
||||
}
|
||||
return "", "", errors.New("invalid basic authentication")
|
||||
}
|
||||
|
||||
// IntrospectOAuth introspects an oauth token
|
||||
func IntrospectOAuth(ctx *context.Context) {
|
||||
clientIDValid := false
|
||||
authHeader := ctx.Req.Header.Get("Authorization")
|
||||
if parsed, ok := httpauth.ParseAuthorizationHeader(authHeader); ok && parsed.BasicAuth != nil {
|
||||
clientID, clientSecret := parsed.BasicAuth.Username, parsed.BasicAuth.Password
|
||||
if clientID, clientSecret, err := parseBasicAuth(ctx); err == nil {
|
||||
app, err := auth.GetOAuth2ApplicationByClientID(ctx, clientID)
|
||||
if err != nil && !auth.IsErrOauthClientIDInvalid(err) {
|
||||
// this is likely a database error; log it and respond without details
|
||||
@ -456,16 +465,16 @@ func AccessTokenOAuth(ctx *context.Context) {
|
||||
form := *web.GetForm(ctx).(*forms.AccessTokenForm)
|
||||
// if there is no ClientID or ClientSecret in the request body, fill these fields by the Authorization header and ensure the provided field matches the Authorization header
|
||||
if form.ClientID == "" || form.ClientSecret == "" {
|
||||
if authHeader := ctx.Req.Header.Get("Authorization"); authHeader != "" {
|
||||
parsed, ok := httpauth.ParseAuthorizationHeader(authHeader)
|
||||
if !ok || parsed.BasicAuth == nil {
|
||||
authHeader := ctx.Req.Header.Get("Authorization")
|
||||
if authType, authData, ok := strings.Cut(authHeader, " "); ok && strings.EqualFold(authType, "Basic") {
|
||||
clientID, clientSecret, err := base.BasicAuthDecode(authData)
|
||||
if err != nil {
|
||||
handleAccessTokenError(ctx, oauth2_provider.AccessTokenError{
|
||||
ErrorCode: oauth2_provider.AccessTokenErrorCodeInvalidRequest,
|
||||
ErrorDescription: "cannot parse basic auth header",
|
||||
})
|
||||
return
|
||||
}
|
||||
clientID, clientSecret := parsed.BasicAuth.Username, parsed.BasicAuth.Password
|
||||
// validate that any fields present in the form match the Basic auth header
|
||||
if form.ClientID != "" && form.ClientID != clientID {
|
||||
handleAccessTokenError(ctx, oauth2_provider.AccessTokenError{
|
||||
|
@ -7,11 +7,12 @@ package auth
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
actions_model "code.gitea.io/gitea/models/actions"
|
||||
auth_model "code.gitea.io/gitea/models/auth"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/auth/httpauth"
|
||||
"code.gitea.io/gitea/modules/base"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
@ -53,15 +54,17 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
authHeader := req.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
baHead := req.Header.Get("Authorization")
|
||||
if len(baHead) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
parsed, ok := httpauth.ParseAuthorizationHeader(authHeader)
|
||||
if !ok || parsed.BasicAuth == nil {
|
||||
|
||||
auths := strings.SplitN(baHead, " ", 2)
|
||||
if len(auths) != 2 || (strings.ToLower(auths[0]) != "basic") {
|
||||
return nil, nil
|
||||
}
|
||||
uname, passwd := parsed.BasicAuth.Username, parsed.BasicAuth.Password
|
||||
|
||||
uname, passwd, _ := base.BasicAuthDecode(auths[1])
|
||||
|
||||
// Check if username or password is a token
|
||||
isUsernameToken := len(passwd) == 0 || passwd == "x-oauth-basic"
|
||||
|
@ -13,7 +13,6 @@ import (
|
||||
actions_model "code.gitea.io/gitea/models/actions"
|
||||
auth_model "code.gitea.io/gitea/models/auth"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/auth/httpauth"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/timeutil"
|
||||
@ -98,9 +97,9 @@ func parseToken(req *http.Request) (string, bool) {
|
||||
|
||||
// check header token
|
||||
if auHead := req.Header.Get("Authorization"); auHead != "" {
|
||||
parsed, ok := httpauth.ParseAuthorizationHeader(auHead)
|
||||
if ok && parsed.BearerToken != nil {
|
||||
return parsed.BearerToken.Token, true
|
||||
auths := strings.Fields(auHead)
|
||||
if len(auths) == 2 && (auths[0] == "token" || strings.ToLower(auths[0]) == "bearer") {
|
||||
return auths[1], true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
|
@ -27,7 +27,6 @@ import (
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/auth/httpauth"
|
||||
"code.gitea.io/gitea/modules/json"
|
||||
lfs_module "code.gitea.io/gitea/modules/lfs"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
@ -595,11 +594,19 @@ func parseToken(ctx stdCtx.Context, authorization string, target *repo_model.Rep
|
||||
if authorization == "" {
|
||||
return nil, errors.New("no token")
|
||||
}
|
||||
parsed, ok := httpauth.ParseAuthorizationHeader(authorization)
|
||||
if !ok || parsed.BearerToken == nil {
|
||||
return nil, errors.New("token not found")
|
||||
|
||||
parts := strings.SplitN(authorization, " ", 2)
|
||||
if len(parts) != 2 {
|
||||
return nil, errors.New("no token")
|
||||
}
|
||||
return handleLFSToken(ctx, parsed.BearerToken.Token, target, mode)
|
||||
tokenSHA := parts[1]
|
||||
switch strings.ToLower(parts[0]) {
|
||||
case "bearer":
|
||||
fallthrough
|
||||
case "token":
|
||||
return handleLFSToken(ctx, tokenSHA, target, mode)
|
||||
}
|
||||
return nil, errors.New("token not found")
|
||||
}
|
||||
|
||||
func requireAuth(ctx *context.Context) {
|
||||
|
@ -46,25 +46,10 @@ func DeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model
|
||||
}
|
||||
}
|
||||
|
||||
func shouldSendCommentChangeNotification(ctx context.Context, comment *issues_model.Comment) bool {
|
||||
if err := comment.LoadReview(ctx); err != nil {
|
||||
log.Error("LoadReview: %v", err)
|
||||
return false
|
||||
} else if comment.Review != nil && comment.Review.Type == issues_model.ReviewTypePending {
|
||||
// Pending review comments updating should not triggered
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// CreateIssueComment notifies issue comment related message to notifiers
|
||||
func CreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository,
|
||||
issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User,
|
||||
) {
|
||||
if !shouldSendCommentChangeNotification(ctx, comment) {
|
||||
return
|
||||
}
|
||||
|
||||
for _, notifier := range notifiers {
|
||||
notifier.CreateIssueComment(ctx, doer, repo, issue, comment, mentions)
|
||||
}
|
||||
@ -171,10 +156,6 @@ func PullReviewDismiss(ctx context.Context, doer *user_model.User, review *issue
|
||||
|
||||
// UpdateComment notifies update comment to notifiers
|
||||
func UpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment, oldContent string) {
|
||||
if !shouldSendCommentChangeNotification(ctx, c) {
|
||||
return
|
||||
}
|
||||
|
||||
for _, notifier := range notifiers {
|
||||
notifier.UpdateComment(ctx, doer, c, oldContent)
|
||||
}
|
||||
@ -182,10 +163,6 @@ func UpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.C
|
||||
|
||||
// DeleteComment notifies delete comment to notifiers
|
||||
func DeleteComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment) {
|
||||
if !shouldSendCommentChangeNotification(ctx, c) {
|
||||
return
|
||||
}
|
||||
|
||||
for _, notifier := range notifiers {
|
||||
notifier.DeleteComment(ctx, doer, c)
|
||||
}
|
||||
|
@ -39,8 +39,6 @@ type GetContentsOrListOptions struct {
|
||||
TreePath string
|
||||
IncludeSingleFileContent bool // include the file's content when the tree path is a file
|
||||
IncludeLfsMetadata bool
|
||||
IncludeCommitMetadata bool
|
||||
IncludeCommitMessage bool
|
||||
}
|
||||
|
||||
// GetContentsOrList gets the metadata of a file's contents (*ContentsResponse) if treePath not a tree
|
||||
@ -134,46 +132,39 @@ func getFileContentsByEntryInternal(_ context.Context, repo *repo_model.Reposito
|
||||
}
|
||||
selfURLString := selfURL.String()
|
||||
|
||||
err = gitRepo.AddLastCommitCache(repo.GetCommitsCountCacheKey(refCommit.InputRef, refType != git.RefTypeCommit), repo.FullName(), refCommit.CommitID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lastCommit, err := refCommit.Commit.GetCommitByPath(opts.TreePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// All content types have these fields in populated
|
||||
contentsResponse := &api.ContentsResponse{
|
||||
Name: entry.Name(),
|
||||
Path: opts.TreePath,
|
||||
SHA: entry.ID.String(),
|
||||
Size: entry.Size(),
|
||||
URL: &selfURLString,
|
||||
Name: entry.Name(),
|
||||
Path: opts.TreePath,
|
||||
SHA: entry.ID.String(),
|
||||
LastCommitSHA: lastCommit.ID.String(),
|
||||
Size: entry.Size(),
|
||||
URL: &selfURLString,
|
||||
Links: &api.FileLinksResponse{
|
||||
Self: &selfURLString,
|
||||
},
|
||||
}
|
||||
|
||||
if opts.IncludeCommitMetadata || opts.IncludeCommitMessage {
|
||||
err = gitRepo.AddLastCommitCache(repo.GetCommitsCountCacheKey(refCommit.InputRef, refType != git.RefTypeCommit), repo.FullName(), refCommit.CommitID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lastCommit, err := refCommit.Commit.GetCommitByPath(opts.TreePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if opts.IncludeCommitMetadata {
|
||||
contentsResponse.LastCommitSHA = util.ToPointer(lastCommit.ID.String())
|
||||
// GitHub doesn't have these fields in the response, but we could follow other similar APIs to name them
|
||||
// https://docs.github.com/en/rest/commits/commits?apiVersion=2022-11-28#list-commits
|
||||
if lastCommit.Committer != nil {
|
||||
contentsResponse.LastCommitterDate = util.ToPointer(lastCommit.Committer.When)
|
||||
}
|
||||
if lastCommit.Author != nil {
|
||||
contentsResponse.LastAuthorDate = util.ToPointer(lastCommit.Author.When)
|
||||
}
|
||||
}
|
||||
if opts.IncludeCommitMessage {
|
||||
contentsResponse.LastCommitMessage = util.ToPointer(lastCommit.Message())
|
||||
}
|
||||
// GitHub doesn't have these fields in the response, but we could follow other similar APIs to name them
|
||||
// https://docs.github.com/en/rest/commits/commits?apiVersion=2022-11-28#list-commits
|
||||
if lastCommit.Committer != nil {
|
||||
contentsResponse.LastCommitterDate = lastCommit.Committer.When
|
||||
}
|
||||
if lastCommit.Author != nil {
|
||||
contentsResponse.LastAuthorDate = lastCommit.Author.When
|
||||
}
|
||||
|
||||
// Now populate the rest of the ContentsResponse based on the entry type
|
||||
// Now populate the rest of the ContentsResponse based on entry type
|
||||
if entry.IsRegular() || entry.IsExecutable() {
|
||||
contentsResponse.Type = string(ContentTypeRegular)
|
||||
// if it is listing the repo root dir, don't waste system resources on reading content
|
||||
|
@ -5,21 +5,56 @@ package files
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
"code.gitea.io/gitea/routers/api/v1/utils"
|
||||
"code.gitea.io/gitea/services/contexttest"
|
||||
|
||||
_ "code.gitea.io/gitea/models/actions"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
unittest.MainTest(m)
|
||||
}
|
||||
|
||||
func getExpectedReadmeContentsResponse() *api.ContentsResponse {
|
||||
treePath := "README.md"
|
||||
sha := "4b4851ad51df6a7d9f25c979345979eaeb5b349f"
|
||||
encoding := "base64"
|
||||
content := "IyByZXBvMQoKRGVzY3JpcHRpb24gZm9yIHJlcG8x"
|
||||
selfURL := "https://try.gitea.io/api/v1/repos/user2/repo1/contents/" + treePath + "?ref=master"
|
||||
htmlURL := "https://try.gitea.io/user2/repo1/src/branch/master/" + treePath
|
||||
gitURL := "https://try.gitea.io/api/v1/repos/user2/repo1/git/blobs/" + sha
|
||||
downloadURL := "https://try.gitea.io/user2/repo1/raw/branch/master/" + treePath
|
||||
return &api.ContentsResponse{
|
||||
Name: treePath,
|
||||
Path: treePath,
|
||||
SHA: "4b4851ad51df6a7d9f25c979345979eaeb5b349f",
|
||||
LastCommitSHA: "65f1bf27bc3bf70f64657658635e66094edbcb4d",
|
||||
LastCommitterDate: time.Date(2017, time.March, 19, 16, 47, 59, 0, time.FixedZone("", -14400)),
|
||||
LastAuthorDate: time.Date(2017, time.March, 19, 16, 47, 59, 0, time.FixedZone("", -14400)),
|
||||
Type: "file",
|
||||
Size: 30,
|
||||
Encoding: &encoding,
|
||||
Content: &content,
|
||||
URL: &selfURL,
|
||||
HTMLURL: &htmlURL,
|
||||
GitURL: &gitURL,
|
||||
DownloadURL: &downloadURL,
|
||||
Links: &api.FileLinksResponse{
|
||||
Self: &selfURL,
|
||||
GitURL: &gitURL,
|
||||
HTMLURL: &htmlURL,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetContents(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
ctx, _ := contexttest.MockContext(t, "user2/repo1")
|
||||
@ -28,8 +63,45 @@ func TestGetContents(t *testing.T) {
|
||||
contexttest.LoadRepoCommit(t, ctx)
|
||||
contexttest.LoadUser(t, ctx, 2)
|
||||
contexttest.LoadGitRepo(t, ctx)
|
||||
defer ctx.Repo.GitRepo.Close()
|
||||
repo, gitRepo := ctx.Repo.Repository, ctx.Repo.GitRepo
|
||||
refCommit, err := utils.ResolveRefCommit(ctx, ctx.Repo.Repository, ctx.Repo.Repository.DefaultBranch)
|
||||
require.NoError(t, err)
|
||||
|
||||
// GetContentsOrList's behavior is fully tested in integration tests, so we don't need to test it here.
|
||||
t.Run("GetContentsOrList(README.md)-MetaOnly", func(t *testing.T) {
|
||||
expectedContentsResponse := getExpectedReadmeContentsResponse()
|
||||
expectedContentsResponse.Encoding = nil // because will be in a list, doesn't have encoding and content
|
||||
expectedContentsResponse.Content = nil
|
||||
extResp, err := GetContentsOrList(ctx, repo, gitRepo, refCommit, GetContentsOrListOptions{TreePath: "README.md", IncludeSingleFileContent: false})
|
||||
assert.Equal(t, expectedContentsResponse, extResp.FileContents)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("GetContentsOrList(README.md)", func(t *testing.T) {
|
||||
expectedContentsResponse := getExpectedReadmeContentsResponse()
|
||||
extResp, err := GetContentsOrList(ctx, repo, gitRepo, refCommit, GetContentsOrListOptions{TreePath: "README.md", IncludeSingleFileContent: true})
|
||||
assert.Equal(t, expectedContentsResponse, extResp.FileContents)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("GetContentsOrList(RootDir)", func(t *testing.T) {
|
||||
readmeContentsResponse := getExpectedReadmeContentsResponse()
|
||||
readmeContentsResponse.Encoding = nil // because will be in a list, doesn't have encoding and content
|
||||
readmeContentsResponse.Content = nil
|
||||
expectedContentsListResponse := []*api.ContentsResponse{readmeContentsResponse}
|
||||
// even if IncludeFileContent is true, it has no effect for directory listing
|
||||
extResp, err := GetContentsOrList(ctx, repo, gitRepo, refCommit, GetContentsOrListOptions{TreePath: "", IncludeSingleFileContent: true})
|
||||
assert.Equal(t, expectedContentsListResponse, extResp.DirContents)
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("GetContentsOrList(NoSuchTreePath)", func(t *testing.T) {
|
||||
extResp, err := GetContentsOrList(ctx, repo, gitRepo, refCommit, GetContentsOrListOptions{TreePath: "no-such/file.md"})
|
||||
assert.Error(t, err)
|
||||
assert.EqualError(t, err, "object does not exist [id: , rel_path: no-such]")
|
||||
assert.Nil(t, extResp.DirContents)
|
||||
assert.Nil(t, extResp.FileContents)
|
||||
})
|
||||
|
||||
t.Run("GetBlobBySHA", func(t *testing.T) {
|
||||
sha := "65f1bf27bc3bf70f64657658635e66094edbcb4d"
|
||||
|
@ -22,12 +22,7 @@ import (
|
||||
func GetContentsListFromTreePaths(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, refCommit *utils.RefCommit, treePaths []string) (files []*api.ContentsResponse) {
|
||||
var size int64
|
||||
for _, treePath := range treePaths {
|
||||
// ok if fails, then will be nil
|
||||
fileContents, _ := GetFileContents(ctx, repo, gitRepo, refCommit, GetContentsOrListOptions{
|
||||
TreePath: treePath,
|
||||
IncludeSingleFileContent: true,
|
||||
IncludeCommitMetadata: true,
|
||||
})
|
||||
fileContents, _ := GetFileContents(ctx, repo, gitRepo, refCommit, GetContentsOrListOptions{TreePath: treePath, IncludeSingleFileContent: true}) // ok if fails, then will be nil
|
||||
if fileContents != nil && fileContents.Content != nil && *fileContents.Content != "" {
|
||||
// if content isn't empty (e.g., due to the single blob being too large), add file size to response size
|
||||
size += int64(len(*fileContents.Content))
|
||||
|
@ -29,7 +29,7 @@ export default {
|
||||
important: true, // the frameworks are mixed together, so tailwind needs to override other framework's styles
|
||||
content: [
|
||||
isProduction && '!./templates/devtest/**/*',
|
||||
isProduction && '!./web_src/js/standalone/devtest.ts',
|
||||
isProduction && '!./web_src/js/standalone/devtest.js',
|
||||
'!./templates/swagger/v1_json.tmpl',
|
||||
'!./templates/user/auth/oidc_wellknown.tmpl',
|
||||
'!**/*_test.go',
|
||||
|
8
templates/swagger/v1_json.tmpl
generated
8
templates/swagger/v1_json.tmpl
generated
@ -7663,7 +7663,7 @@
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "path of the dir, file, symlink or submodule in the repo. Swagger requires path parameter to be \"required\", you can leave it empty or pass a single dot (\".\") to get the root directory.",
|
||||
"description": "path of the dir, file, symlink or submodule in the repo",
|
||||
"name": "filepath",
|
||||
"in": "path",
|
||||
"required": true
|
||||
@ -7676,7 +7676,7 @@
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "By default this API's response only contains file's metadata. Use comma-separated \"includes\" options to retrieve more fields. Option \"file_content\" will try to retrieve the file content, \"lfs_metadata\" will try to retrieve LFS metadata, \"commit_metadata\" will try to retrieve commit metadata, and \"commit_message\" will try to retrieve commit message.",
|
||||
"description": "By default this API's response only contains file's metadata. Use comma-separated \"includes\" options to retrieve more fields. Option \"file_content\" will try to retrieve the file content, option \"lfs_metadata\" will try to retrieve LFS metadata.",
|
||||
"name": "includes",
|
||||
"in": "query"
|
||||
}
|
||||
@ -22484,10 +22484,6 @@
|
||||
"format": "date-time",
|
||||
"x-go-name": "LastAuthorDate"
|
||||
},
|
||||
"last_commit_message": {
|
||||
"type": "string",
|
||||
"x-go-name": "LastCommitMessage"
|
||||
},
|
||||
"last_commit_sha": {
|
||||
"type": "string",
|
||||
"x-go-name": "LastCommitSHA"
|
||||
|
@ -19,7 +19,6 @@ import (
|
||||
"code.gitea.io/gitea/modules/gitrepo"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
"code.gitea.io/gitea/services/context"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@ -53,8 +52,8 @@ func getCreateFileOptions() api.CreateFileOptions {
|
||||
func normalizeFileContentResponseCommitTime(c *api.ContentsResponse) {
|
||||
// decoded JSON response may contain different timezone from the one parsed by git commit
|
||||
// so we need to normalize the time to UTC to make "assert.Equal" pass
|
||||
c.LastCommitterDate = util.ToPointer(c.LastCommitterDate.UTC())
|
||||
c.LastAuthorDate = util.ToPointer(c.LastAuthorDate.UTC())
|
||||
c.LastCommitterDate = c.LastCommitterDate.UTC()
|
||||
c.LastAuthorDate = c.LastAuthorDate.UTC()
|
||||
}
|
||||
|
||||
type apiFileResponseInfo struct {
|
||||
@ -75,9 +74,9 @@ func getExpectedFileResponseForCreate(info apiFileResponseInfo) *api.FileRespons
|
||||
Name: path.Base(info.treePath),
|
||||
Path: info.treePath,
|
||||
SHA: sha,
|
||||
LastCommitSHA: util.ToPointer(info.lastCommitSHA),
|
||||
LastCommitterDate: util.ToPointer(info.lastCommitterWhen),
|
||||
LastAuthorDate: util.ToPointer(info.lastAuthorWhen),
|
||||
LastCommitSHA: info.lastCommitSHA,
|
||||
LastCommitterDate: info.lastCommitterWhen,
|
||||
LastAuthorDate: info.lastAuthorWhen,
|
||||
Size: 16,
|
||||
Type: "file",
|
||||
Encoding: &encoding,
|
||||
|
@ -18,7 +18,6 @@ import (
|
||||
"code.gitea.io/gitea/modules/gitrepo"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
"code.gitea.io/gitea/services/context"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@ -61,9 +60,9 @@ func getExpectedFileResponseForUpdate(info apiFileResponseInfo) *api.FileRespons
|
||||
Name: path.Base(info.treePath),
|
||||
Path: info.treePath,
|
||||
SHA: sha,
|
||||
LastCommitSHA: util.ToPointer(info.lastCommitSHA),
|
||||
LastCommitterDate: util.ToPointer(info.lastCommitterWhen),
|
||||
LastAuthorDate: util.ToPointer(info.lastAuthorWhen),
|
||||
LastCommitSHA: info.lastCommitSHA,
|
||||
LastCommitterDate: info.lastCommitterWhen,
|
||||
LastAuthorDate: info.lastAuthorWhen,
|
||||
Type: "file",
|
||||
Size: 20,
|
||||
Encoding: &encoding,
|
||||
|
@ -18,7 +18,6 @@ import (
|
||||
"code.gitea.io/gitea/modules/gitrepo"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
repo_service "code.gitea.io/gitea/services/repository"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@ -36,9 +35,9 @@ func getExpectedContentsListResponseForContents(ref, refType, lastCommitSHA stri
|
||||
Name: path.Base(treePath),
|
||||
Path: treePath,
|
||||
SHA: sha,
|
||||
LastCommitSHA: util.ToPointer(lastCommitSHA),
|
||||
LastCommitterDate: util.ToPointer(time.Date(2017, time.March, 19, 16, 47, 59, 0, time.FixedZone("", -14400))),
|
||||
LastAuthorDate: util.ToPointer(time.Date(2017, time.March, 19, 16, 47, 59, 0, time.FixedZone("", -14400))),
|
||||
LastCommitSHA: lastCommitSHA,
|
||||
LastCommitterDate: time.Date(2017, time.March, 19, 16, 47, 59, 0, time.FixedZone("", -14400)),
|
||||
LastAuthorDate: time.Date(2017, time.March, 19, 16, 47, 59, 0, time.FixedZone("", -14400)),
|
||||
Type: "file",
|
||||
Size: 30,
|
||||
URL: &selfURL,
|
||||
@ -66,6 +65,7 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) {
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo
|
||||
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // public repo
|
||||
repo16 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}) // private repo
|
||||
treePath := "" // root dir
|
||||
|
||||
// Get user2's token
|
||||
session := loginUser(t, user2.Name)
|
||||
@ -94,7 +94,7 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) {
|
||||
// ref is default ref
|
||||
ref := repo1.DefaultBranch
|
||||
refType := "branch"
|
||||
req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents?ref=%s", user2.Name, repo1.Name, ref)
|
||||
req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?ref=%s", user2.Name, repo1.Name, treePath, ref)
|
||||
resp := MakeRequest(t, req, http.StatusOK)
|
||||
var contentsListResponse []*api.ContentsResponse
|
||||
DecodeJSON(t, resp, &contentsListResponse)
|
||||
@ -106,7 +106,7 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) {
|
||||
|
||||
// No ref
|
||||
refType = "branch"
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/", user2.Name, repo1.Name)
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath)
|
||||
resp = MakeRequest(t, req, http.StatusOK)
|
||||
DecodeJSON(t, resp, &contentsListResponse)
|
||||
assert.NotNil(t, contentsListResponse)
|
||||
@ -117,7 +117,7 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) {
|
||||
// ref is the branch we created above in setup
|
||||
ref = newBranch
|
||||
refType = "branch"
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents?ref=%s", user2.Name, repo1.Name, ref)
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?ref=%s", user2.Name, repo1.Name, treePath, ref)
|
||||
resp = MakeRequest(t, req, http.StatusOK)
|
||||
DecodeJSON(t, resp, &contentsListResponse)
|
||||
assert.NotNil(t, contentsListResponse)
|
||||
@ -131,7 +131,7 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) {
|
||||
// ref is the new tag we created above in setup
|
||||
ref = newTag
|
||||
refType = "tag"
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/?ref=%s", user2.Name, repo1.Name, ref)
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?ref=%s", user2.Name, repo1.Name, treePath, ref)
|
||||
resp = MakeRequest(t, req, http.StatusOK)
|
||||
DecodeJSON(t, resp, &contentsListResponse)
|
||||
assert.NotNil(t, contentsListResponse)
|
||||
@ -145,7 +145,7 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) {
|
||||
// ref is a commit
|
||||
ref = commitID
|
||||
refType = "commit"
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/?ref=%s", user2.Name, repo1.Name, ref)
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?ref=%s", user2.Name, repo1.Name, treePath, ref)
|
||||
resp = MakeRequest(t, req, http.StatusOK)
|
||||
DecodeJSON(t, resp, &contentsListResponse)
|
||||
assert.NotNil(t, contentsListResponse)
|
||||
@ -154,21 +154,21 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) {
|
||||
|
||||
// Test file contents a file with a bad ref
|
||||
ref = "badref"
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/?ref=%s", user2.Name, repo1.Name, ref)
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?ref=%s", user2.Name, repo1.Name, treePath, ref)
|
||||
MakeRequest(t, req, http.StatusNotFound)
|
||||
|
||||
// Test accessing private ref with user token that does not have access - should fail
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/", user2.Name, repo16.Name).
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath).
|
||||
AddTokenAuth(token4)
|
||||
MakeRequest(t, req, http.StatusNotFound)
|
||||
|
||||
// Test access private ref of owner of token
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/", user2.Name, repo16.Name).
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/readme.md", user2.Name, repo16.Name).
|
||||
AddTokenAuth(token2)
|
||||
MakeRequest(t, req, http.StatusOK)
|
||||
|
||||
// Test access of org org3 private repo file by owner user2
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/", org3.Name, repo3.Name).
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath).
|
||||
AddTokenAuth(token2)
|
||||
MakeRequest(t, req, http.StatusOK)
|
||||
}
|
||||
|
@ -35,9 +35,9 @@ func getExpectedContentsResponseForContents(ref, refType, lastCommitSHA string)
|
||||
Name: treePath,
|
||||
Path: treePath,
|
||||
SHA: "4b4851ad51df6a7d9f25c979345979eaeb5b349f",
|
||||
LastCommitSHA: util.ToPointer(lastCommitSHA),
|
||||
LastCommitterDate: util.ToPointer(time.Date(2017, time.March, 19, 16, 47, 59, 0, time.FixedZone("", -14400))),
|
||||
LastAuthorDate: util.ToPointer(time.Date(2017, time.March, 19, 16, 47, 59, 0, time.FixedZone("", -14400))),
|
||||
LastCommitSHA: lastCommitSHA,
|
||||
LastCommitterDate: time.Date(2017, time.March, 19, 16, 47, 59, 0, time.FixedZone("", -14400)),
|
||||
LastAuthorDate: time.Date(2017, time.March, 19, 16, 47, 59, 0, time.FixedZone("", -14400)),
|
||||
Type: "file",
|
||||
Size: 30,
|
||||
Encoding: util.ToPointer("base64"),
|
||||
@ -97,16 +97,11 @@ func testAPIGetContents(t *testing.T, u *url.URL) {
|
||||
require.NoError(t, err)
|
||||
/*** END SETUP ***/
|
||||
|
||||
// not found
|
||||
req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/no-such/file.md", user2.Name, repo1.Name)
|
||||
resp := MakeRequest(t, req, http.StatusNotFound)
|
||||
assert.Contains(t, resp.Body.String(), "object does not exist [id: , rel_path: no-such]")
|
||||
|
||||
// ref is default ref
|
||||
ref := repo1.DefaultBranch
|
||||
refType := "branch"
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?ref=%s", user2.Name, repo1.Name, treePath, ref)
|
||||
resp = MakeRequest(t, req, http.StatusOK)
|
||||
req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?ref=%s", user2.Name, repo1.Name, treePath, ref)
|
||||
resp := MakeRequest(t, req, http.StatusOK)
|
||||
var contentsResponse api.ContentsResponse
|
||||
DecodeJSON(t, resp, &contentsResponse)
|
||||
lastCommit, _ := gitRepo.GetCommitByPath("README.md")
|
||||
@ -121,7 +116,7 @@ func testAPIGetContents(t *testing.T, u *url.URL) {
|
||||
expectedContentsResponse = getExpectedContentsResponseForContents(repo1.DefaultBranch, refType, lastCommit.ID.String())
|
||||
assert.Equal(t, *expectedContentsResponse, contentsResponse)
|
||||
|
||||
// ref is the branch we created above in setup
|
||||
// ref is the branch we created above in setup
|
||||
ref = newBranch
|
||||
refType = "branch"
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?ref=%s", user2.Name, repo1.Name, treePath, ref)
|
||||
@ -211,30 +206,14 @@ func testAPIGetContentsExt(t *testing.T) {
|
||||
session := loginUser(t, "user2")
|
||||
token2 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
|
||||
t.Run("DirContents", func(t *testing.T) {
|
||||
req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/contents-ext?ref=sub-home-md-img-check")
|
||||
req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/contents-ext/docs?ref=sub-home-md-img-check")
|
||||
resp := MakeRequest(t, req, http.StatusOK)
|
||||
var contentsResponse api.ContentsExtResponse
|
||||
DecodeJSON(t, resp, &contentsResponse)
|
||||
assert.Nil(t, contentsResponse.FileContents)
|
||||
assert.NotNil(t, contentsResponse.DirContents)
|
||||
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/contents-ext/.?ref=sub-home-md-img-check")
|
||||
resp = MakeRequest(t, req, http.StatusOK)
|
||||
contentsResponse = api.ContentsExtResponse{}
|
||||
DecodeJSON(t, resp, &contentsResponse)
|
||||
assert.Nil(t, contentsResponse.FileContents)
|
||||
assert.NotNil(t, contentsResponse.DirContents)
|
||||
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/contents-ext/docs?ref=sub-home-md-img-check")
|
||||
resp = MakeRequest(t, req, http.StatusOK)
|
||||
contentsResponse = api.ContentsExtResponse{}
|
||||
DecodeJSON(t, resp, &contentsResponse)
|
||||
assert.Nil(t, contentsResponse.FileContents)
|
||||
assert.Equal(t, "README.md", contentsResponse.DirContents[0].Name)
|
||||
assert.Nil(t, contentsResponse.DirContents[0].Encoding)
|
||||
assert.Nil(t, contentsResponse.DirContents[0].Content)
|
||||
assert.Nil(t, contentsResponse.DirContents[0].LastCommitSHA)
|
||||
assert.Nil(t, contentsResponse.DirContents[0].LastCommitMessage)
|
||||
|
||||
// "includes=file_content" shouldn't affect directory listing
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/contents-ext/docs?ref=sub-home-md-img-check&includes=file_content")
|
||||
@ -261,7 +240,7 @@ func testAPIGetContentsExt(t *testing.T) {
|
||||
assert.Equal(t, util.ToPointer("0b8d8b5f15046343fd32f451df93acc2bdd9e6373be478b968e4cad6b6647351"), respFile.LfsOid)
|
||||
})
|
||||
t.Run("FileContents", func(t *testing.T) {
|
||||
// by default, no file content or commit info is returned
|
||||
// by default, no file content is returned
|
||||
req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/contents-ext/docs/README.md?ref=sub-home-md-img-check")
|
||||
resp := MakeRequest(t, req, http.StatusOK)
|
||||
var contentsResponse api.ContentsExtResponse
|
||||
@ -270,11 +249,9 @@ func testAPIGetContentsExt(t *testing.T) {
|
||||
assert.Equal(t, "README.md", contentsResponse.FileContents.Name)
|
||||
assert.Nil(t, contentsResponse.FileContents.Encoding)
|
||||
assert.Nil(t, contentsResponse.FileContents.Content)
|
||||
assert.Nil(t, contentsResponse.FileContents.LastCommitSHA)
|
||||
assert.Nil(t, contentsResponse.FileContents.LastCommitMessage)
|
||||
|
||||
// file content is only returned when `includes=file_content`
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/contents-ext/docs/README.md?ref=sub-home-md-img-check&includes=file_content,commit_metadata,commit_message")
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/contents-ext/docs/README.md?ref=sub-home-md-img-check&includes=file_content")
|
||||
resp = MakeRequest(t, req, http.StatusOK)
|
||||
contentsResponse = api.ContentsExtResponse{}
|
||||
DecodeJSON(t, resp, &contentsResponse)
|
||||
@ -282,8 +259,6 @@ func testAPIGetContentsExt(t *testing.T) {
|
||||
assert.Equal(t, "README.md", contentsResponse.FileContents.Name)
|
||||
assert.NotNil(t, contentsResponse.FileContents.Encoding)
|
||||
assert.NotNil(t, contentsResponse.FileContents.Content)
|
||||
assert.Equal(t, "4649299398e4d39a5c09eb4f534df6f1e1eb87cc", *contentsResponse.FileContents.LastCommitSHA)
|
||||
assert.Equal(t, "Test how READMEs render images when found in a subfolder\n", *contentsResponse.FileContents.LastCommitMessage)
|
||||
|
||||
req = NewRequestf(t, "GET", "/api/v1/repos/user2/lfs/contents-ext/jpeg.jpg?includes=file_content").AddTokenAuth(token2)
|
||||
resp = session.MakeRequest(t, req, http.StatusOK)
|
||||
@ -295,8 +270,6 @@ func testAPIGetContentsExt(t *testing.T) {
|
||||
assert.Equal(t, "jpeg.jpg", respFile.Name)
|
||||
assert.NotNil(t, respFile.Encoding)
|
||||
assert.NotNil(t, respFile.Content)
|
||||
assert.Nil(t, contentsResponse.FileContents.LastCommitSHA)
|
||||
assert.Nil(t, contentsResponse.FileContents.LastCommitMessage)
|
||||
assert.Equal(t, util.ToPointer(int64(107)), respFile.LfsSize)
|
||||
assert.Equal(t, util.ToPointer("0b8d8b5f15046343fd32f451df93acc2bdd9e6373be478b968e4cad6b6647351"), respFile.LfsOid)
|
||||
})
|
||||
|
@ -155,9 +155,9 @@ func getExpectedFileResponseForRepoFilesCreate(commitID string, lastCommit *git.
|
||||
Name: path.Base(treePath),
|
||||
Path: treePath,
|
||||
SHA: "103ff9234cefeee5ec5361d22b49fbb04d385885",
|
||||
LastCommitSHA: util.ToPointer(lastCommit.ID.String()),
|
||||
LastCommitterDate: util.ToPointer(lastCommit.Committer.When),
|
||||
LastAuthorDate: util.ToPointer(lastCommit.Author.When),
|
||||
LastCommitSHA: lastCommit.ID.String(),
|
||||
LastCommitterDate: lastCommit.Committer.When,
|
||||
LastAuthorDate: lastCommit.Author.When,
|
||||
Type: "file",
|
||||
Size: 18,
|
||||
Encoding: &encoding,
|
||||
@ -198,7 +198,7 @@ func getExpectedFileResponseForRepoFilesCreate(commitID string, lastCommit *git.
|
||||
SHA: "65f1bf27bc3bf70f64657658635e66094edbcb4d",
|
||||
},
|
||||
},
|
||||
Message: "Creates new/file.txt\n",
|
||||
Message: "Updates README.md\n",
|
||||
Tree: &api.CommitMeta{
|
||||
URL: setting.AppURL + "api/v1/repos/user2/repo1/git/trees/f93e3a1a1525fb5b91020da86e44810c87a2d7bc",
|
||||
SHA: "f93e3a1a1525fb5b91020git dda86e44810c87a2d7bc",
|
||||
@ -225,9 +225,9 @@ func getExpectedFileResponseForRepoFilesUpdate(commitID, filename, lastCommitSHA
|
||||
Name: filename,
|
||||
Path: filename,
|
||||
SHA: "dbf8d00e022e05b7e5cf7e535de857de57925647",
|
||||
LastCommitSHA: util.ToPointer(lastCommitSHA),
|
||||
LastCommitterDate: util.ToPointer(lastCommitterWhen),
|
||||
LastAuthorDate: util.ToPointer(lastAuthorWhen),
|
||||
LastCommitSHA: lastCommitSHA,
|
||||
LastCommitterDate: lastCommitterWhen,
|
||||
LastAuthorDate: lastAuthorWhen,
|
||||
Type: "file",
|
||||
Size: 43,
|
||||
Encoding: &encoding,
|
||||
@ -331,7 +331,7 @@ func getExpectedFileResponseForRepoFilesUpdateRename(commitID, lastCommitSHA str
|
||||
Name: detail.filename,
|
||||
Path: detail.filename,
|
||||
SHA: detail.sha,
|
||||
LastCommitSHA: util.ToPointer(lastCommitSHA),
|
||||
LastCommitSHA: lastCommitSHA,
|
||||
Type: "file",
|
||||
Size: detail.size,
|
||||
Encoding: util.ToPointer("base64"),
|
||||
@ -537,7 +537,7 @@ func TestChangeRepoFilesForUpdateWithFileRename(t *testing.T) {
|
||||
lastCommit, _ := commit.GetCommitByPath(opts.Files[0].TreePath)
|
||||
expectedFileResponse := getExpectedFileResponseForRepoFilesUpdateRename(commit.ID.String(), lastCommit.ID.String())
|
||||
for _, file := range filesResponse.Files {
|
||||
file.LastCommitterDate, file.LastAuthorDate = nil, nil // there might be different time in one operation, so we ignore them
|
||||
file.LastCommitterDate, file.LastAuthorDate = time.Time{}, time.Time{} // there might be different time in one operation, so we ignore them
|
||||
}
|
||||
assert.Len(t, filesResponse.Files, 4)
|
||||
assert.Equal(t, expectedFileResponse.Files, filesResponse.Files)
|
||||
|
Loading…
x
Reference in New Issue
Block a user