diff --git a/apps/files/ajax/delete.php b/apps/files/ajax/delete.php
index 99f49188384993606ee06cc474f29f1493313b29..f6aa4f0c90ef77094e7611484c58d1d61d2d5df6 100644
--- a/apps/files/ajax/delete.php
+++ b/apps/files/ajax/delete.php
@@ -1,10 +1,9 @@
 <?php
 
-// Init owncloud
-
-
 OCP\JSON::checkLoggedIn();
 OCP\JSON::callCheck();
+\OC::$session->close();
+
 
 // Get data
 $dir = stripslashes($_POST["dir"]);
diff --git a/apps/files/ajax/download.php b/apps/files/ajax/download.php
index 6a34cbe4ef1928ed9727bc2c8aa28afe5df97393..1f7e42e0d3e3b282487bd2e811e032ef93b95788 100644
--- a/apps/files/ajax/download.php
+++ b/apps/files/ajax/download.php
@@ -29,6 +29,7 @@ $RUNTIME_APPTYPES=array('filesystem');
 
 // Check if we are a user
 OCP\User::checkLoggedIn();
+\OC::$session->close();
 
 $files = $_GET["files"];
 $dir = $_GET["dir"];
diff --git a/apps/files/ajax/getstoragestats.php b/apps/files/ajax/getstoragestats.php
index dd7c7dc5571c09c2ecac5442f27ce2495f8e641b..17415b6933f09d4b1ef35241bada4d35db3ec946 100644
--- a/apps/files/ajax/getstoragestats.php
+++ b/apps/files/ajax/getstoragestats.php
@@ -10,6 +10,7 @@ if (isset($_GET['dir'])) {
 }
 
 OCP\JSON::checkLoggedIn();
+\OC::$session->close();
 
 // send back json
 OCP\JSON::success(array('data' => \OCA\Files\Helper::buildFileStorageStatistics($dir)));
diff --git a/apps/files/ajax/list.php b/apps/files/ajax/list.php
index c8286bc15ca2fbef22e623195b2d9ad8a90831ec..667209599a012a45a9c72c2a352ae42a40fa3d0f 100644
--- a/apps/files/ajax/list.php
+++ b/apps/files/ajax/list.php
@@ -7,6 +7,7 @@ $RUNTIME_APPTYPES=array('filesystem');
 
 
 OCP\JSON::checkLoggedIn();
+\OC::$session->close();
 
 // Load the files
 $dir = isset( $_GET['dir'] ) ? $_GET['dir'] : '';
diff --git a/apps/files/ajax/mimeicon.php b/apps/files/ajax/mimeicon.php
index dbb8b60112ab6937dd935aeca87e4c070966f956..6557ff941ac1dc8095d9f62ce7948fcce2e5e49b 100644
--- a/apps/files/ajax/mimeicon.php
+++ b/apps/files/ajax/mimeicon.php
@@ -1,3 +1,4 @@
 <?php
+\OC::$session->close();
 
 print OC_Helper::mimetypeIcon($_GET['mime']);
diff --git a/apps/files/ajax/move.php b/apps/files/ajax/move.php
index 04a260265c259775c84b50c96d2a027c9cc06905..0a8dbc24a650abb41f5616f140c51fe0b5e628a8 100644
--- a/apps/files/ajax/move.php
+++ b/apps/files/ajax/move.php
@@ -1,10 +1,8 @@
 <?php
 
-// Init owncloud
-
-
 OCP\JSON::checkLoggedIn();
 OCP\JSON::callCheck();
+\OC::$session->close();
 
 // Get data
 $dir = stripslashes($_POST["dir"]);
diff --git a/apps/files/ajax/newfile.php b/apps/files/ajax/newfile.php
index 0187b20075920e4920177c2c08b22b2263ee178a..1234cf11394342dfb655c97687197a8b7f32f06a 100644
--- a/apps/files/ajax/newfile.php
+++ b/apps/files/ajax/newfile.php
@@ -7,7 +7,8 @@ if(!OC_User::isLoggedIn()) {
 	exit;
 }
 
-session_write_close();
+\OC::$session->close();
+
 // Get the params
 $dir = isset( $_REQUEST['dir'] ) ? '/'.trim($_REQUEST['dir'], '/\\') : '';
 $filename = isset( $_REQUEST['filename'] ) ? trim($_REQUEST['filename'], '/\\') : '';
diff --git a/apps/files/ajax/newfolder.php b/apps/files/ajax/newfolder.php
index b2b4fb27f74a0a3bdd4ae4a2a8cdd3df543214bc..032447460f3fb0961c4c0251e6f02aa7b5b6a34c 100644
--- a/apps/files/ajax/newfolder.php
+++ b/apps/files/ajax/newfolder.php
@@ -5,6 +5,7 @@
 
 OCP\JSON::checkLoggedIn();
 OCP\JSON::callCheck();
+\OC::$session->close();
 
 // Get the params
 $dir = isset( $_POST['dir'] ) ? stripslashes($_POST['dir']) : '';
diff --git a/apps/files/ajax/rawlist.php b/apps/files/ajax/rawlist.php
index 6433ddefd69e22b5f6822f31801b4f10f3d1b4a4..6c2569e2ebbc903d86d196ce55561724e3ea407a 100644
--- a/apps/files/ajax/rawlist.php
+++ b/apps/files/ajax/rawlist.php
@@ -4,6 +4,7 @@
 $RUNTIME_APPTYPES = array('filesystem');
 
 OCP\JSON::checkLoggedIn();
+\OC::$session->close();
 
 // Load the files
 $dir = isset($_GET['dir']) ? $_GET['dir'] : '';
diff --git a/apps/files/ajax/rename.php b/apps/files/ajax/rename.php
index 5b07c306af86bef818584380db742bfb11ff34c5..fa3ddace63d4b887d077bd78bee231589dc5aade 100644
--- a/apps/files/ajax/rename.php
+++ b/apps/files/ajax/rename.php
@@ -23,6 +23,7 @@
 
 OCP\JSON::checkLoggedIn();
 OCP\JSON::callCheck();
+\OC::$session->close();
 
 $files = new \OCA\Files\App(
 	\OC\Files\Filesystem::getView(),
diff --git a/apps/files/ajax/scan.php b/apps/files/ajax/scan.php
index 5b32b6db9b72ad27b8c383ec3acc243c1b7fe891..d5d884838013407ced18732a3b576a4ab5000c7d 100644
--- a/apps/files/ajax/scan.php
+++ b/apps/files/ajax/scan.php
@@ -1,6 +1,6 @@
 <?php
 set_time_limit(0); //scanning can take ages
-session_write_close();
+\OC::$session->close();
 
 $force = (isset($_GET['force']) and ($_GET['force'] === 'true'));
 $dir = isset($_GET['dir']) ? $_GET['dir'] : '';
diff --git a/apps/files/ajax/upload.php b/apps/files/ajax/upload.php
index 145f40c50da5725a30d61246fcbad94842e0787f..37c600e91da384b270d2883b8aa8cec9e4eecc76 100644
--- a/apps/files/ajax/upload.php
+++ b/apps/files/ajax/upload.php
@@ -58,6 +58,7 @@ if (empty($_POST['dirToken'])) {
 
 
 OCP\JSON::callCheck();
+\OC::$session->close();
 
 
 // get array with current storage stats (e.g. max file size)
diff --git a/apps/files_encryption/lib/helper.php b/apps/files_encryption/lib/helper.php
index ef3775875f0f5d911e38901d2f803f903c11c31b..8cbbe8a45a6ef62f638a675414d392f486887ba4 100755
--- a/apps/files_encryption/lib/helper.php
+++ b/apps/files_encryption/lib/helper.php
@@ -367,9 +367,14 @@ class Helper {
 		$post = 0;
 		if(count($_POST) > 0) {
 			$post = 1;
-			}
-			header('Location: ' . $location . '?p=' . $post . '&errorCode=' . $errorCode);
-			exit();
+		}
+
+		if(defined('PHPUNIT_RUN') and PHPUNIT_RUN) {
+			throw new \Exception("Encryption error: $errorCode");
+		}
+
+		header('Location: ' . $location . '?p=' . $post . '&errorCode=' . $errorCode);
+		exit();
 	}
 
 	/**
diff --git a/cron.php b/cron.php
index 44ca421328b5893e1f4fd5b748105287d231852f..a0447f97f190bb54795203e14f49a5f10fd25a12 100644
--- a/cron.php
+++ b/cron.php
@@ -48,7 +48,7 @@ try {
 
 	require_once 'lib/base.php';
 
-	session_write_close();
+	\OC::$session->close();
 
 	$logger = \OC_Log::$object;
 
diff --git a/lib/private/connector/sabre/auth.php b/lib/private/connector/sabre/auth.php
index 0c84fa6b7578e85656fb042ece59a13642f44276..5577273df8c004c79317531030021b7e953f7635 100644
--- a/lib/private/connector/sabre/auth.php
+++ b/lib/private/connector/sabre/auth.php
@@ -73,6 +73,20 @@ class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic {
 	  */
 	public function authenticate(Sabre_DAV_Server $server, $realm) {
 
+		$result = $this->auth($server, $realm);
+
+		// close the session - right after authentication there is not need to write to the session any more
+		\OC::$session->close();
+
+		return $result;
+    }
+
+	/**
+	 * @param Sabre_DAV_Server $server
+	 * @param $realm
+	 * @return bool
+	 */
+	private function auth(Sabre_DAV_Server $server, $realm) {
 		if (OC_User::handleApacheAuth() || OC_User::isLoggedIn()) {
 			$user = OC_User::getUser();
 			OC_Util::setupFS($user);
@@ -81,5 +95,5 @@ class OC_Connector_Sabre_Auth extends Sabre_DAV_Auth_Backend_AbstractBasic {
 		}
 
 		return parent::authenticate($server, $realm);
-    }
+	}
 }
diff --git a/lib/private/session/internal.php b/lib/private/session/internal.php
index a7c9e2fdefd36ed8620e403b85d1a59dcab73187..42ec9606dc9defacd5c6482097dccbe05c925c2c 100644
--- a/lib/private/session/internal.php
+++ b/lib/private/session/internal.php
@@ -26,8 +26,7 @@ class Internal extends Memory {
 	}
 
 	public function __destruct() {
-		$_SESSION = array_merge($_SESSION, $this->data);
-		session_write_close();
+		$this->close();
 	}
 
 	/**
@@ -47,4 +46,15 @@ class Internal extends Memory {
 		@session_start();
 		$this->data = $_SESSION = array();
 	}
+
+	public function close() {
+		$_SESSION = array_merge($_SESSION, $this->data);
+		session_write_close();
+
+		parent::close();
+	}
+
+    public function reopen() {
+        throw new \Exception('The session cannot be reopened - reopen() is ony to be used in unit testing.');
+    }
 }
diff --git a/lib/private/session/memory.php b/lib/private/session/memory.php
index 1b9ac45257520ad21dd9624a5d8fc245f6f14f7b..1497c0f89281256b41c4d569f142101785371204 100644
--- a/lib/private/session/memory.php
+++ b/lib/private/session/memory.php
@@ -28,6 +28,7 @@ class Memory extends Session {
 	 * @param integer $value
 	 */
 	public function set($key, $value) {
+		$this->validateSession();
 		$this->data[$key] = $value;
 	}
 
@@ -54,10 +55,29 @@ class Memory extends Session {
 	 * @param string $key
 	 */
 	public function remove($key) {
+		$this->validateSession();
 		unset($this->data[$key]);
 	}
 
 	public function clear() {
 		$this->data = array();
 	}
+
+	/**
+	 * Helper function for PHPUnit execution - don't use in non-test code
+	 */
+	public function reopen() {
+		$this->sessionClosed = false;
+	}
+
+	/**
+	 * In case the session has already been locked an exception will be thrown
+	 *
+	 * @throws \Exception
+	 */
+	private function validateSession() {
+		if ($this->sessionClosed) {
+			throw new \Exception('Session has been closed - no further changes to the session as allowed');
+		}
+	}
 }
diff --git a/lib/private/session/session.php b/lib/private/session/session.php
index fe160faa2679196079ced3e74490ba9fc4247dc6..6f6c804f38489f36676a55d09f403eb76f7d3c4a 100644
--- a/lib/private/session/session.php
+++ b/lib/private/session/session.php
@@ -12,6 +12,11 @@ use OCP\ISession;
 
 abstract class Session implements \ArrayAccess, ISession {
 
+	/**
+	 * @var bool
+	 */
+	protected $sessionClosed = false;
+
 	/**
 	 * $name serves as a namespace for the session keys
 	 *
@@ -49,4 +54,11 @@ abstract class Session implements \ArrayAccess, ISession {
 	public function offsetUnset($offset) {
 		$this->remove($offset);
 	}
+
+	/**
+	 * Close the session and release the lock
+	 */
+	public function close() {
+		$this->sessionClosed = true;
+	}
 }
diff --git a/lib/public/isession.php b/lib/public/isession.php
index 20da712cda3079426526a9de8edc6faf66137269..dc5719625cc4fb72dc37ea79e6797a7298991090 100644
--- a/lib/public/isession.php
+++ b/lib/public/isession.php
@@ -75,4 +75,9 @@ interface ISession {
 	 */
 	public function clear();
 
+	/**
+	 * Close the session and release the lock
+	 */
+	public function close();
+
 }
diff --git a/tests/phpunit-autotest.xml b/tests/phpunit-autotest.xml
index 1a2ab35491b88bbc10c8d8482376b0e336044fbc..872ff2c2596891ffc53e52876054031c0f8e7ffa 100644
--- a/tests/phpunit-autotest.xml
+++ b/tests/phpunit-autotest.xml
@@ -36,6 +36,7 @@
 		</whitelist>
 	</filter>
 	<listeners>
+		<listener class="StartSessionListener" file="startsessionlistener.php" />
 	  <listener class="TestCleanupListener" file="testcleanuplistener.php">
 		<arguments>
 			<string>detail</string>
diff --git a/tests/phpunit.xml.dist b/tests/phpunit.xml.dist
index 71a4ff2762c1737778cfa1d4b30a3eb15b19086f..21c63ea0469aeaa29a102ecf8fe5d543d3a3a423 100644
--- a/tests/phpunit.xml.dist
+++ b/tests/phpunit.xml.dist
@@ -29,4 +29,7 @@
 			</exclude>
 		</whitelist>
 	</filter>
+	<listeners>
+		<listener class="StartSessionListener" file="startsessionlistener.php" />
+	</listeners>
 </phpunit>
diff --git a/tests/startsessionlistener.php b/tests/startsessionlistener.php
new file mode 100644
index 0000000000000000000000000000000000000000..808a2a2226fe095a942552893225d53188a233cd
--- /dev/null
+++ b/tests/startsessionlistener.php
@@ -0,0 +1,44 @@
+<?php
+/**
+ * Copyright (c) 2014 Thomas Müller <deepdiver@owncloud.com>
+ * This file is licensed under the Affero General Public License version 3 or
+ * later.
+ * See the COPYING-README file.
+ */
+
+/**
+ * Starts a new session before each test execution
+ */
+class StartSessionListener implements PHPUnit_Framework_TestListener {
+
+	public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) {
+	}
+
+	public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) {
+	}
+
+	public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) {
+	}
+
+	public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) {
+	}
+
+	public function startTest(PHPUnit_Framework_Test $test) {
+	}
+
+	public function endTest(PHPUnit_Framework_Test $test, $time) {
+		// reopen the session - only allowed for memory session
+		if (\OC::$session instanceof \OC\Session\Memory) {
+			/** @var $session \OC\Session\Memory */
+			$session = \OC::$session;
+			$session->reopen();
+		}
+	}
+
+	public function startTestSuite(PHPUnit_Framework_TestSuite $suite) {
+	}
+
+	public function endTestSuite(PHPUnit_Framework_TestSuite $suite) {
+	}
+
+}