* @author Christopher Schäpers * @author Christoph Wurst * @author Georg Ehrke * @author Joas Schilling * @author Jörn Friedrich Dreyer * @author Lukas Reschke * @author Morris Jobke * @author Robin Appelman * @author Robin McCorkell * @author Roeland Jago Douma * @author Thomas Müller * @author Vincent Petry * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see * */ require_once __DIR__ . '/lib/versioncheck.php'; use OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin; use Sabre\DAV\Exception\ServiceUnavailable; use Sabre\DAV\Server; /** * Class RemoteException * Dummy exception class to be use locally to identify certain conditions * Will not be logged to avoid DoS */ class RemoteException extends Exception { } /** * @param Exception|Error $e */ function handleException($e) { $request = \OC::$server->getRequest(); // in case the request content type is text/xml - we assume it's a WebDAV request $isXmlContentType = strpos($request->getHeader('Content-Type'), 'text/xml'); if ($isXmlContentType === 0) { // fire up a simple server to properly process the exception $server = new Server(); if (!($e instanceof RemoteException)) { // we shall not log on RemoteException $server->addPlugin(new ExceptionLoggerPlugin('webdav', \OC::$server->getLogger())); } $server->on('beforeMethod:*', function () use ($e) { if ($e instanceof RemoteException) { switch ($e->getCode()) { case 503: throw new ServiceUnavailable($e->getMessage()); case 404: throw new \Sabre\DAV\Exception\NotFound($e->getMessage()); } } $class = get_class($e); $msg = $e->getMessage(); throw new ServiceUnavailable("$class: $msg"); }); $server->exec(); } else { $statusCode = 500; if ($e instanceof \OC\ServiceUnavailableException) { $statusCode = 503; } if ($e instanceof RemoteException) { // we shall not log on RemoteException OC_Template::printErrorPage($e->getMessage(), '', $e->getCode()); } else { \OC::$server->getLogger()->logException($e, ['app' => 'remote']); OC_Template::printExceptionErrorPage($e, $statusCode); } } } /** * @param $service * @return string */ function resolveService($service) { $services = [ 'webdav' => 'dav/appinfo/v1/webdav.php', 'dav' => 'dav/appinfo/v2/remote.php', 'caldav' => 'dav/appinfo/v1/caldav.php', 'calendar' => 'dav/appinfo/v1/caldav.php', 'carddav' => 'dav/appinfo/v1/carddav.php', 'contacts' => 'dav/appinfo/v1/carddav.php', 'files' => 'dav/appinfo/v1/webdav.php', 'direct' => 'dav/appinfo/v2/direct.php', ]; if (isset($services[$service])) { return $services[$service]; } return \OC::$server->getConfig()->getAppValue('core', 'remote_' . $service); } try { require_once __DIR__ . '/lib/base.php'; // All resources served via the DAV endpoint should have the strictest possible // policy. Exempted from this is the SabreDAV browser plugin which overwrites // this policy with a softer one if debug mode is enabled. header("Content-Security-Policy: default-src 'none';"); if (\OCP\Util::needUpgrade()) { // since the behavior of apps or remotes are unpredictable during // an upgrade, return a 503 directly throw new RemoteException('Service unavailable', 503); } $request = \OC::$server->getRequest(); $pathInfo = $request->getPathInfo(); if ($pathInfo === false || $pathInfo === '') { throw new RemoteException('Path not found', 404); } if (!$pos = strpos($pathInfo, '/', 1)) { $pos = strlen($pathInfo); } $service = substr($pathInfo, 1, $pos - 1); $file = resolveService($service); if (is_null($file)) { throw new RemoteException('Path not found', 404); } $file = ltrim($file, '/'); $parts = explode('/', $file, 2); $app = $parts[0]; // Load all required applications \OC::$REQUESTEDAPP = $app; OC_App::loadApps(['authentication']); OC_App::loadApps(['filesystem', 'logging']); switch ($app) { case 'core': $file = OC::$SERVERROOT .'/'. $file; break; default: if (!\OC::$server->getAppManager()->isInstalled($app)) { throw new RemoteException('App not installed: ' . $app); } OC_App::loadApp($app); $file = OC_App::getAppPath($app) .'/'. $parts[1]; break; } $baseuri = OC::$WEBROOT . '/remote.php/'.$service.'/'; require_once $file; } catch (Exception $ex) { handleException($ex); } catch (Error $e) { handleException($e); } ef='#n43'>43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package models

import (
	"fmt"
	"testing"

	"code.gitea.io/gitea/models/db"
	repo_model "code.gitea.io/gitea/models/repo"
	"code.gitea.io/gitea/models/unittest"
	user_model "code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/modules/references"

	"github.com/stretchr/testify/assert"
)

func TestXRef_AddCrossReferences(t *testing.T) {
	assert.NoError(t, unittest.PrepareTestDatabase())

	// Issue #1 to test against
	itarget := testCreateIssue(t, 1, 2, "title1", "content1", false)

	// PR to close issue #1
	content := fmt.Sprintf("content2, closes #%d", itarget.Index)
	pr := testCreateIssue(t, 1, 2, "title2", content, true)
	ref := unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: pr.ID, RefCommentID: 0}).(*Comment)
	assert.Equal(t, CommentTypePullRef, ref.Type)
	assert.Equal(t, pr.RepoID, ref.RefRepoID)
	assert.True(t, ref.RefIsPull)
	assert.Equal(t, references.XRefActionCloses, ref.RefAction)

	// Comment on PR to reopen issue #1
	content = fmt.Sprintf("content2, reopens #%d", itarget.Index)
	c := testCreateComment(t, 1, 2, pr.ID, content)
	ref = unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: pr.ID, RefCommentID: c.ID}).(*Comment)
	assert.Equal(t, CommentTypeCommentRef, ref.Type)
	assert.Equal(t, pr.RepoID, ref.RefRepoID)
	assert.True(t, ref.RefIsPull)
	assert.Equal(t, references.XRefActionReopens, ref.RefAction)

	// Issue mentioning issue #1
	content = fmt.Sprintf("content3, mentions #%d", itarget.Index)
	i := testCreateIssue(t, 1, 2, "title3", content, false)
	ref = unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment)
	assert.Equal(t, CommentTypeIssueRef, ref.Type)
	assert.Equal(t, pr.RepoID, ref.RefRepoID)
	assert.False(t, ref.RefIsPull)
	assert.Equal(t, references.XRefActionNone, ref.RefAction)

	// Issue #4 to test against
	itarget = testCreateIssue(t, 3, 3, "title4", "content4", false)

	// Cross-reference to issue #4 by admin
	content = fmt.Sprintf("content5, mentions user3/repo3#%d", itarget.Index)
	i = testCreateIssue(t, 2, 1, "title5", content, false)
	ref = unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment)
	assert.Equal(t, CommentTypeIssueRef, ref.Type)
	assert.Equal(t, i.RepoID, ref.RefRepoID)
	assert.False(t, ref.RefIsPull)
	assert.Equal(t, references.XRefActionNone, ref.RefAction)

	// Cross-reference to issue #4 with no permission
	content = fmt.Sprintf("content6, mentions user3/repo3#%d", itarget.Index)
	i = testCreateIssue(t, 4, 5, "title6", content, false)
	unittest.AssertNotExistsBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0})
}

func TestXRef_NeuterCrossReferences(t *testing.T) {
	assert.NoError(t, unittest.PrepareTestDatabase())

	// Issue #1 to test against
	itarget := testCreateIssue(t, 1, 2, "title1", "content1", false)

	// Issue mentioning issue #1
	title := fmt.Sprintf("title2, mentions #%d", itarget.Index)
	i := testCreateIssue(t, 1, 2, title, "content2", false)
	ref := unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment)
	assert.Equal(t, CommentTypeIssueRef, ref.Type)
	assert.Equal(t, references.XRefActionNone, ref.RefAction)

	d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)
	i.Title = "title2, no mentions"
	assert.NoError(t, ChangeIssueTitle(i, d, title))

	ref = unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment)
	assert.Equal(t, CommentTypeIssueRef, ref.Type)
	assert.Equal(t, references.XRefActionNeutered, ref.RefAction)
}

func TestXRef_ResolveCrossReferences(t *testing.T) {
	assert.NoError(t, unittest.PrepareTestDatabase())

	d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}).(*user_model.User)

	i1 := testCreateIssue(t, 1, 2, "title1", "content1", false)
	i2 := testCreateIssue(t, 1, 2, "title2", "content2", false)
	i3 := testCreateIssue(t, 1, 2, "title3", "content3", false)
	_, err := ChangeIssueStatus(db.DefaultContext, i3, d, true)
	assert.NoError(t, err)

	pr := testCreatePR(t, 1, 2, "titlepr", fmt.Sprintf("closes #%d", i1.Index))
	rp := unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: i1.ID, RefIssueID: pr.Issue.ID, RefCommentID: 0}).(*Comment)

	c1 := testCreateComment(t, 1, 2, pr.Issue.ID, fmt.Sprintf("closes #%d", i2.Index))
	r1 := unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: i2.ID, RefIssueID: pr.Issue.ID, RefCommentID: c1.ID}).(*Comment)

	// Must be ignored
	c2 := testCreateComment(t, 1, 2, pr.Issue.ID, fmt.Sprintf("mentions #%d", i2.Index))
	unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: i2.ID, RefIssueID: pr.Issue.ID, RefCommentID: c2.ID})

	// Must be superseded by c4/r4
	c3 := testCreateComment(t, 1, 2, pr.Issue.ID, fmt.Sprintf("reopens #%d", i3.Index))
	unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: i3.ID, RefIssueID: pr.Issue.ID, RefCommentID: c3.ID})

	c4 := testCreateComment(t, 1, 2, pr.Issue.ID, fmt.Sprintf("closes #%d", i3.Index))
	r4 := unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: i3.ID, RefIssueID: pr.Issue.ID, RefCommentID: c4.ID}).(*Comment)

	refs, err := pr.ResolveCrossReferences(db.DefaultContext)
	assert.NoError(t, err)
	assert.Len(t, refs, 3)
	assert.Equal(t, rp.ID, refs[0].ID, "bad ref rp: %+v", refs[0])
	assert.Equal(t, r1.ID, refs[1].ID, "bad ref r1: %+v", refs[1])
	assert.Equal(t, r4.ID, refs[2].ID, "bad ref r4: %+v", refs[2])
}

func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispull bool) *Issue {
	r := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo}).(*repo_model.Repository)
	d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: doer}).(*user_model.User)

	idx, err := db.GetNextResourceIndex("issue_index", r.ID)
	assert.NoError(t, err)
	i := &Issue{
		RepoID:   r.ID,
		PosterID: d.ID,
		Poster:   d,
		Title:    title,
		Content:  content,
		IsPull:   ispull,
		Index:    idx,
	}

	ctx, committer, err := db.TxContext()
	assert.NoError(t, err)
	defer committer.Close()
	err = newIssue(ctx, d, NewIssueOptions{
		Repo:  r,
		Issue: i,
	})
	assert.NoError(t, err)
	i, err = getIssueByID(ctx, i.ID)
	assert.NoError(t, err)
	assert.NoError(t, i.addCrossReferences(ctx, d, false))
	assert.NoError(t, committer.Commit())
	return i
}

func testCreatePR(t *testing.T, repo, doer int64, title, content string) *PullRequest {
	r := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo}).(*repo_model.Repository)
	d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: doer}).(*user_model.User)
	i := &Issue{RepoID: r.ID, PosterID: d.ID, Poster: d, Title: title, Content: content, IsPull: true}
	pr := &PullRequest{HeadRepoID: repo, BaseRepoID: repo, HeadBranch: "head", BaseBranch: "base", Status: PullRequestStatusMergeable}
	assert.NoError(t, NewPullRequest(db.DefaultContext, r, i, nil, nil, pr))
	pr.Issue = i
	return pr
}

func testCreateComment(t *testing.T, repo, doer, issue int64, content string) *Comment {
	d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: doer}).(*user_model.User)
	i := unittest.AssertExistsAndLoadBean(t, &Issue{ID: issue}).(*Issue)
	c := &Comment{Type: CommentTypeComment, PosterID: doer, Poster: d, IssueID: issue, Issue: i, Content: content}

	ctx, committer, err := db.TxContext()
	assert.NoError(t, err)
	defer committer.Close()
	err = db.Insert(ctx, c)
	assert.NoError(t, err)
	assert.NoError(t, c.addCrossReferences(ctx, d, false))
	assert.NoError(t, committer.Commit())
	return c
}