mirror of
https://github.com/go-gitea/gitea
synced 2025-07-22 18:28:37 +00:00
Prevent double-login for Git HTTP and LFS and simplify login (#15303)
* Prevent double-login for Git HTTP and LFS and simplify login There are a number of inconsistencies with our current methods for logging in for git and lfs. The first is that there is a double login process. This is particularly evident in 1.13 where there are no less than 4 hash checks for basic authentication due to the previous IsPasswordSet behaviour. This duplicated code had individual inconsistencies that were not helpful and caused confusion. This PR does the following: * Remove the specific login code from the git and lfs handlers except for the lfs special bearer token * Simplify the meaning of DisableBasicAuthentication to allow Token and Oauth2 sign-in. * The removal of the specific code from git and lfs means that these both now have the same login semantics and can - if not DisableBasicAuthentication - login from external services. Further it allows Oauth2 token authentication as per our standard mechanisms. * The change in the recovery handler prevents the service from re-attempting to login - primarily because this could easily cause a further panic and it is wasteful. * add test Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: Andrew Thornton <art27@cantab.net>
This commit is contained in:
@@ -31,15 +31,6 @@ func checkIsValidRequest(ctx *context.Context) bool {
|
||||
writeStatus(ctx, http.StatusBadRequest)
|
||||
return false
|
||||
}
|
||||
if !ctx.IsSigned {
|
||||
user, _, _, err := parseToken(ctx.Req.Header.Get("Authorization"))
|
||||
if err != nil {
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
|
||||
writeStatus(ctx, http.StatusUnauthorized)
|
||||
return false
|
||||
}
|
||||
ctx.User = user
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -73,19 +64,21 @@ func GetListLockHandler(ctx *context.Context) {
|
||||
// Status is written in checkIsValidRequest
|
||||
return
|
||||
}
|
||||
ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
|
||||
|
||||
rv, _ := unpack(ctx)
|
||||
|
||||
repository, err := models.GetRepositoryByOwnerAndName(rv.User, rv.Repo)
|
||||
if err != nil {
|
||||
log.Debug("Could not find repository: %s/%s - %s", rv.User, rv.Repo, err)
|
||||
writeStatus(ctx, 404)
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
|
||||
ctx.JSON(401, api.LFSLockError{
|
||||
Message: "You must have pull access to list locks",
|
||||
})
|
||||
return
|
||||
}
|
||||
repository.MustOwner()
|
||||
|
||||
authenticated := authenticate(ctx, repository, rv.Authorization, false)
|
||||
authenticated := authenticate(ctx, repository, rv.Authorization, true, false)
|
||||
if !authenticated {
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
|
||||
ctx.JSON(http.StatusUnauthorized, api.LFSLockError{
|
||||
@@ -93,6 +86,7 @@ func GetListLockHandler(ctx *context.Context) {
|
||||
})
|
||||
return
|
||||
}
|
||||
ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
|
||||
|
||||
cursor := ctx.QueryInt("cursor")
|
||||
if cursor < 0 {
|
||||
@@ -160,7 +154,6 @@ func PostLockHandler(ctx *context.Context) {
|
||||
// Status is written in checkIsValidRequest
|
||||
return
|
||||
}
|
||||
ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
|
||||
|
||||
userName := ctx.Params("username")
|
||||
repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git")
|
||||
@@ -169,12 +162,15 @@ func PostLockHandler(ctx *context.Context) {
|
||||
repository, err := models.GetRepositoryByOwnerAndName(userName, repoName)
|
||||
if err != nil {
|
||||
log.Error("Unable to get repository: %s/%s Error: %v", userName, repoName, err)
|
||||
writeStatus(ctx, 404)
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
|
||||
ctx.JSON(401, api.LFSLockError{
|
||||
Message: "You must have push access to create locks",
|
||||
})
|
||||
return
|
||||
}
|
||||
repository.MustOwner()
|
||||
|
||||
authenticated := authenticate(ctx, repository, authorization, true)
|
||||
authenticated := authenticate(ctx, repository, authorization, true, true)
|
||||
if !authenticated {
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
|
||||
ctx.JSON(http.StatusUnauthorized, api.LFSLockError{
|
||||
@@ -183,6 +179,8 @@ func PostLockHandler(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
|
||||
|
||||
var req api.LFSLockRequest
|
||||
bodyReader := ctx.Req.Body
|
||||
defer bodyReader.Close()
|
||||
@@ -229,7 +227,6 @@ func VerifyLockHandler(ctx *context.Context) {
|
||||
// Status is written in checkIsValidRequest
|
||||
return
|
||||
}
|
||||
ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
|
||||
|
||||
userName := ctx.Params("username")
|
||||
repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git")
|
||||
@@ -238,12 +235,15 @@ func VerifyLockHandler(ctx *context.Context) {
|
||||
repository, err := models.GetRepositoryByOwnerAndName(userName, repoName)
|
||||
if err != nil {
|
||||
log.Error("Unable to get repository: %s/%s Error: %v", userName, repoName, err)
|
||||
writeStatus(ctx, 404)
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
|
||||
ctx.JSON(401, api.LFSLockError{
|
||||
Message: "You must have push access to verify locks",
|
||||
})
|
||||
return
|
||||
}
|
||||
repository.MustOwner()
|
||||
|
||||
authenticated := authenticate(ctx, repository, authorization, true)
|
||||
authenticated := authenticate(ctx, repository, authorization, true, true)
|
||||
if !authenticated {
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
|
||||
ctx.JSON(http.StatusUnauthorized, api.LFSLockError{
|
||||
@@ -252,6 +252,8 @@ func VerifyLockHandler(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
|
||||
|
||||
cursor := ctx.QueryInt("cursor")
|
||||
if cursor < 0 {
|
||||
cursor = 0
|
||||
@@ -296,7 +298,6 @@ func UnLockHandler(ctx *context.Context) {
|
||||
// Status is written in checkIsValidRequest
|
||||
return
|
||||
}
|
||||
ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
|
||||
|
||||
userName := ctx.Params("username")
|
||||
repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git")
|
||||
@@ -305,12 +306,15 @@ func UnLockHandler(ctx *context.Context) {
|
||||
repository, err := models.GetRepositoryByOwnerAndName(userName, repoName)
|
||||
if err != nil {
|
||||
log.Error("Unable to get repository: %s/%s Error: %v", userName, repoName, err)
|
||||
writeStatus(ctx, 404)
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
|
||||
ctx.JSON(401, api.LFSLockError{
|
||||
Message: "You must have push access to delete locks",
|
||||
})
|
||||
return
|
||||
}
|
||||
repository.MustOwner()
|
||||
|
||||
authenticated := authenticate(ctx, repository, authorization, true)
|
||||
authenticated := authenticate(ctx, repository, authorization, true, true)
|
||||
if !authenticated {
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
|
||||
ctx.JSON(http.StatusUnauthorized, api.LFSLockError{
|
||||
@@ -319,6 +323,8 @@ func UnLockHandler(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
|
||||
|
||||
var req api.LFSLockDeleteRequest
|
||||
bodyReader := ctx.Req.Body
|
||||
defer bodyReader.Close()
|
||||
|
@@ -94,7 +94,7 @@ func getAuthenticatedRepoAndMeta(ctx *context.Context, rc *requestContext, p lfs
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if !authenticate(ctx, repository, rc.Authorization, requireWrite) {
|
||||
if !authenticate(ctx, repository, rc.Authorization, false, requireWrite) {
|
||||
requireAuth(ctx)
|
||||
return nil, nil
|
||||
}
|
||||
@@ -232,7 +232,7 @@ func PostHandler(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if !authenticate(ctx, repository, rc.Authorization, true) {
|
||||
if !authenticate(ctx, repository, rc.Authorization, false, true) {
|
||||
requireAuth(ctx)
|
||||
return
|
||||
}
|
||||
@@ -322,7 +322,7 @@ func BatchHandler(ctx *context.Context) {
|
||||
requireWrite = true
|
||||
}
|
||||
|
||||
if !authenticate(ctx, repository, reqCtx.Authorization, requireWrite) {
|
||||
if !authenticate(ctx, repository, reqCtx.Authorization, false, requireWrite) {
|
||||
requireAuth(ctx)
|
||||
return
|
||||
}
|
||||
@@ -561,7 +561,7 @@ func logRequest(r *http.Request, status int) {
|
||||
|
||||
// authenticate uses the authorization string to determine whether
|
||||
// or not to proceed. This server assumes an HTTP Basic auth format.
|
||||
func authenticate(ctx *context.Context, repository *models.Repository, authorization string, requireWrite bool) bool {
|
||||
func authenticate(ctx *context.Context, repository *models.Repository, authorization string, requireSigned, requireWrite bool) bool {
|
||||
accessMode := models.AccessModeRead
|
||||
if requireWrite {
|
||||
accessMode = models.AccessModeWrite
|
||||
@@ -575,89 +575,72 @@ func authenticate(ctx *context.Context, repository *models.Repository, authoriza
|
||||
}
|
||||
|
||||
canRead := perm.CanAccess(accessMode, models.UnitTypeCode)
|
||||
if canRead {
|
||||
if canRead && (!requireSigned || ctx.IsSigned) {
|
||||
return true
|
||||
}
|
||||
|
||||
user, repo, opStr, err := parseToken(authorization)
|
||||
user, err := parseToken(authorization, repository, accessMode)
|
||||
if err != nil {
|
||||
// Most of these are Warn level - the true internal server errors are logged in parseToken already
|
||||
log.Warn("Authentication failure for provided token with Error: %v", err)
|
||||
return false
|
||||
}
|
||||
ctx.User = user
|
||||
if opStr == "basic" {
|
||||
perm, err = models.GetUserRepoPermission(repository, ctx.User)
|
||||
if err != nil {
|
||||
log.Error("Unable to GetUserRepoPermission for user %-v in repo %-v Error: %v", ctx.User, repository)
|
||||
return false
|
||||
}
|
||||
return perm.CanAccess(accessMode, models.UnitTypeCode)
|
||||
}
|
||||
if repository.ID == repo.ID {
|
||||
if requireWrite && opStr != "upload" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return true
|
||||
}
|
||||
|
||||
func parseToken(authorization string) (*models.User, *models.Repository, string, error) {
|
||||
func handleLFSToken(tokenSHA string, target *models.Repository, mode models.AccessMode) (*models.User, error) {
|
||||
if !strings.Contains(tokenSHA, ".") {
|
||||
return nil, nil
|
||||
}
|
||||
token, err := jwt.ParseWithClaims(tokenSHA, &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return setting.LFS.JWTSecretBytes, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
claims, claimsOk := token.Claims.(*Claims)
|
||||
if !token.Valid || !claimsOk {
|
||||
return nil, fmt.Errorf("invalid token claim")
|
||||
}
|
||||
|
||||
if claims.RepoID != target.ID {
|
||||
return nil, fmt.Errorf("invalid token claim")
|
||||
}
|
||||
|
||||
if mode == models.AccessModeWrite && claims.Op != "upload" {
|
||||
return nil, fmt.Errorf("invalid token claim")
|
||||
}
|
||||
|
||||
u, err := models.GetUserByID(claims.UserID)
|
||||
if err != nil {
|
||||
log.Error("Unable to GetUserById[%d]: Error: %v", claims.UserID, err)
|
||||
return nil, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func parseToken(authorization string, target *models.Repository, mode models.AccessMode) (*models.User, error) {
|
||||
if authorization == "" {
|
||||
return nil, nil, "unknown", fmt.Errorf("No token")
|
||||
}
|
||||
if strings.HasPrefix(authorization, "Bearer ") {
|
||||
token, err := jwt.ParseWithClaims(authorization[7:], &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return setting.LFS.JWTSecretBytes, nil
|
||||
})
|
||||
if err != nil {
|
||||
// The error here is WARN level because it is caused by bad authorization rather than an internal server error
|
||||
return nil, nil, "unknown", err
|
||||
}
|
||||
claims, claimsOk := token.Claims.(*Claims)
|
||||
if !token.Valid || !claimsOk {
|
||||
return nil, nil, "unknown", fmt.Errorf("Token claim invalid")
|
||||
}
|
||||
r, err := models.GetRepositoryByID(claims.RepoID)
|
||||
if err != nil {
|
||||
log.Error("Unable to GetRepositoryById[%d]: Error: %v", claims.RepoID, err)
|
||||
return nil, nil, claims.Op, err
|
||||
}
|
||||
u, err := models.GetUserByID(claims.UserID)
|
||||
if err != nil {
|
||||
log.Error("Unable to GetUserById[%d]: Error: %v", claims.UserID, err)
|
||||
return nil, r, claims.Op, err
|
||||
}
|
||||
return u, r, claims.Op, nil
|
||||
return nil, fmt.Errorf("no token")
|
||||
}
|
||||
|
||||
if strings.HasPrefix(authorization, "Basic ") {
|
||||
c, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authorization, "Basic "))
|
||||
if err != nil {
|
||||
return nil, nil, "basic", err
|
||||
}
|
||||
cs := string(c)
|
||||
i := strings.IndexByte(cs, ':')
|
||||
if i < 0 {
|
||||
return nil, nil, "basic", fmt.Errorf("Basic auth invalid")
|
||||
}
|
||||
user, password := cs[:i], cs[i+1:]
|
||||
u, err := models.GetUserByName(user)
|
||||
if err != nil {
|
||||
log.Error("Unable to GetUserByName[%d]: Error: %v", user, err)
|
||||
return nil, nil, "basic", err
|
||||
}
|
||||
if !u.IsPasswordSet() || !u.ValidatePassword(password) {
|
||||
return nil, nil, "basic", fmt.Errorf("Basic auth failed")
|
||||
}
|
||||
return u, nil, "basic", nil
|
||||
parts := strings.SplitN(authorization, " ", 2)
|
||||
if len(parts) != 2 {
|
||||
return nil, fmt.Errorf("no token")
|
||||
}
|
||||
|
||||
return nil, nil, "unknown", fmt.Errorf("Token not found")
|
||||
tokenSHA := parts[1]
|
||||
switch strings.ToLower(parts[0]) {
|
||||
case "bearer":
|
||||
fallthrough
|
||||
case "token":
|
||||
return handleLFSToken(tokenSHA, target, mode)
|
||||
}
|
||||
return nil, fmt.Errorf("token not found")
|
||||
}
|
||||
|
||||
func requireAuth(ctx *context.Context) {
|
||||
|
Reference in New Issue
Block a user