OC.L10N.register( "files_external", { "External storages" : "Almacenamiento externo", "Personal" : "Personal", "System" : "Sistema", "Grant access" : "Conceder acceso", "Error configuring OAuth1" : "Se presentó un error al configurar OAuth1", "Please provide a valid app key and secret." : "Por favor proporciona una llave de aplicación y secreto válidos.", "Error configuring OAuth2" : "Se presentó un error al configurar OAuth2", "Generate keys" : "Generar llaves", "Error generating key pair" : "Se presentó un error al generar el juego de llaves", "All users. Type to select user or group." : "Todos los usuarios. Escribe para seleccionar el usuario o grupo", "(group)" : "(grupo)", "Compatibility with Mac NFD encoding (slow)" : "Compatibilidad con codificación Mac NFD (lenta)", "Admin defined" : "Administrador definido", "Are you sure you want to delete this external storage" : "¿Estás seguro de que quieres borrar este almacenamiento externo?", "Delete storage?" : "¿Borrar almacenamiento?", "Saved" : "Guardado", "Saving..." : "Guardando...", "Save" : "Guardar", "Empty response from the server" : "Respuesta del servidor vacía", "Couldn't access. Please log out and in again to activate this mount point" : "No fue posible accesar. Por favor sal de la sesión y vuelve a entrar para activar este punto de montaje", "Couldn't get the information from the remote server: {code} {type}" : "No fue posible obtener la información del servidor remoto: {code} {type}", "Couldn't get the list of external mount points: {type}" : "No fue posible obtener la lista de puntos de montaje externos: {type}", "There was an error with message: " : "Se presentó un problema con el mensaje:", "External mount error" : "Error de montaje externo", "external-storage" : "almacenamiento externo", "Couldn't fetch list of Windows network drive mount points: Empty response from server" : "No fue posible obtener el listado de los puntos de motaje de unidades de red Windows. Respuesta vacía del servidor", "Some of the configured external mount points are not connected. Please click on the red row(s) for more information" : "Algunos de los puntos de montaje externos configurados no se encuentran conectados. Por favor has click en los renglon(es) en rojo para más información", "Please enter the credentials for the {mount} mount" : "Por favor ingresa las credenciales para el montaje {mount}", "Username" : "Usuario", "Password" : "Contraseña", "Credentials saved" : "Credenciales guardadas", "Credentials saving failed" : "Se ha presentado una falla al guardar las credenciales", "Credentials required" : "Se requieren credenciales", "Storage with ID \"%d\" not found" : "El almacenamiento con ID \"%d\" no fue encontrado", "Invalid backend or authentication mechanism class" : "Backend o clase de mecanismo de autenticación inválido ", "Invalid mount point" : "Punto de montaje inválido", "Objectstore forbidden" : "Objectstore prohibido", "Invalid storage backend \"%s\"" : "Almacenamiento de backend \"%s\" inválido ", "Not permitted to use backend \"%s\"" : "No está permitido usar el backend \"%s\"", "Not permitted to use authentication mechanism \"%s\"" : "No está permitido el uso del mecanismo de autenticación \"%s\"", "Unsatisfied backend parameters" : "Parametros del backend no satisfechos", "Unsatisfied authentication mechanism parameters" : "Parámetros no satisfechos del mecanismo de autenticación", "Insufficient data: %s" : "Datos insuficientes: %s", "%s" : "%s", "Storage with ID \"%d\" is not user editable" : "El almacenamiento con ID \"%d\" no puede ser editado por el usuario", "Access key" : "Llave de acceso", "Secret key" : "Llave secreta", "Builtin" : "Integrado", "None" : "Ninguno", "OAuth1" : "OAuth1", "App key" : "Llave de la aplicación", "App secret" : "Secreto de la aplicación", "OAuth2" : "OAuth2", "Client ID" : "ID del cliente", "Client secret" : "Secreto del cliente", "OpenStack" : "OpenStack", "Tenant name" : "Nombre de inquilino", "Identity endpoint URL" : "URL del punto de enlace de Identidad", "Rackspace" : "Rackspace", "API key" : "Llave de API", "Global credentials" : "Credenciales globales", "Log-in credentials, save in database" : "Credenciales de inicio de sesión, guardar en la base de datos", "Username and password" : "Usuario y contraseña", "Log-in credentials, save in session" : "Credenciales de inicio de sesión, guardar en la sesión", "User entered, store in database" : "Usuario ingresado, almacenar en la base de datos", "RSA public key" : "Llave pública RSA", "Public key" : "Llave pública", "Amazon S3" : "Amazon S3", "Bucket" : "Bucket", "Hostname" : "Nombre del servidor", "Port" : "Puerto", "Region" : "Región", "Enable SSL" : "Habilitar SSL", "Enable Path Style" : "Habilitar Estilo de Ruta", "WebDAV" : "WebDAV", "URL" : "URL", "Remote subfolder" : "Subcarpeta remota", "Secure https://" : "https:// seguro", "FTP" : "FTP", "Host" : "Servidor", "Secure ftps://" : "ftps:// seguro", "Local" : "Local", "Location" : "Ubicación", "Nextcloud" : "Nextcloud", "SFTP" : "SFTP", "Root" : "Raíz", "SFTP with secret key login" : "Inicio de sesión SFTP con llave secreta", "SMB / CIFS" : "SMB / CIFS", "Share" : "Compartir", "Domain" : "Dominio", "SMB / CIFS using OC login" : "SMB / CIFS usando inicio de sesión OC", "Username as share" : "Usuario como elemento compartido", "OpenStack Object Storage" : "OpenStack Object Storage", "Service name" : "Nombre del servicio", "Request timeout (seconds)" : "Tiemo de vida de la solicitud (segudos)", "The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "El soporte para cURL en PHP no se encuentra habilitado o instalado. El montaje de %s no es posible. Por favor solicita a tu administador su instalación. ", "The FTP support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "El soporte para FTP en PHP no se encuentra habilitado o instalado. El montaje de %s no es posible. Por favor solicita a tu administador su instalación. ", "\"%s\" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "\"%s\" no se encuentra instalado. El montaje de %s no es posible. Por favor solicita a tu administrador su instalación. ", "No external storage configured" : "No se ha configurado el almacenamiento externo", "You can add external storages in the personal settings" : "Puedes agregar almacenamiento externo en las configuraciones personales", "Name" : "Nombre", "Storage type" : "Tipo de almacenamiento", "Scope" : "Alcance", "Enable encryption" : "Habilitar encripción", "Enable previews" : "Habilitar vistas previas", "Enable sharing" : "Habilitar compartir", "Check for changes" : "Verificar si hay cambios", "Never" : "Nunca", "Once every direct access" : "Una vez cada acceso directo", "Folder name" : "Nombre de la carpeta", "External storage" : "Almacenamiento externo", "Authentication" : "Autenticación", "Configuration" : "Configuración", "Available for" : "Disponible para", "Add storage" : "Agregar almacenamiento", "Advanced settings" : "Configuraciones avanzadas", "Delete" : "Borrar", "Allow users to mount external storage" : "Permitir a los usuarios montar almacenamiento externo", "Allow users to mount the following external storage" : "Permitir a los usuarios montar el siguiente almacenamiento externo" }, "nplurals=2; plural=(n != 1);"); ng-crl'>automated/noid/stable28-update-code-signing-crl Nextcloud server, a safe home for all your data: https://github.com/nextcloud/serverwww-data
aboutsummaryrefslogtreecommitdiffstats
path: root/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php
blob: 4853b527bf383356c92aa335c8631a04b018ce84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
<?php
/**
 * ownCloud - App Framework
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Bernhard Posselt <dev@bernhard-posselt.com>
 * @copyright Bernhard Posselt 2014
 */

namespace Test\AppFramework\Middleware\Security;

use OC\AppFramework\Http\Request;
use OC\AppFramework\Middleware\Security\CORSMiddleware;
use OC\AppFramework\Middleware\Security\Exceptions\SecurityException;
use OC\AppFramework\Utility\ControllerMethodReflector;
use OC\Security\Bruteforce\Throttler;
use OC\User\Session;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\Response;
use OCP\IConfig;
use OCP\Security\ISecureRandom;

class CORSMiddlewareTest extends \Test\TestCase {

	/** @var ControllerMethodReflector */
	private $reflector;
	/** @var Session|\PHPUnit\Framework\MockObject\MockObject */
	private $session;
	/** @var Throttler */
	private $throttler;
	/** @var Controller */
	private $controller;

	protected function setUp(): void {
		parent::setUp();
		$this->reflector = new ControllerMethodReflector();
		$this->session = $this->createMock(Session::class);
		$this->throttler =  $this->createMock(Throttler::class);
		$this->controller = $this->createMock(Controller::class);
	}

	/**
	 * @CORS
	 */
	public function testSetCORSAPIHeader() {
		$request = new Request(
			[
				'server' => [
					'HTTP_ORIGIN' => 'test'
				]
			],
			$this->createMock(ISecureRandom::class),
			$this->createMock(IConfig::class)
		);
		$this->reflector->reflect($this, __FUNCTION__);
		$middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler);

		$response = $middleware->afterController($this->controller, __FUNCTION__, new Response());
		$headers = $response->getHeaders();
		$this->assertEquals('test', $headers['Access-Control-Allow-Origin']);
	}


	public function testNoAnnotationNoCORSHEADER() {
		$request = new Request(
			[
				'server' => [
					'HTTP_ORIGIN' => 'test'
				]
			],
			$this->createMock(ISecureRandom::class),
			$this->createMock(IConfig::class)
		);
		$middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler);

		$response = $middleware->afterController($this->controller, __FUNCTION__, new Response());
		$headers = $response->getHeaders();
		$this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers));
	}


	/**
	 * @CORS
	 */
	public function testNoOriginHeaderNoCORSHEADER() {
		$request = new Request(
			[],
			$this->createMock(ISecureRandom::class),
			$this->createMock(IConfig::class)
		);
		$this->reflector->reflect($this, __FUNCTION__);
		$middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler);

		$response = $middleware->afterController($this->controller, __FUNCTION__, new Response());
		$headers = $response->getHeaders();
		$this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers));
	}


	/**
	 * @CORS
	 */
	public function testCorsIgnoredIfWithCredentialsHeaderPresent() {
		$this->expectException(\OC\AppFramework\Middleware\Security\Exceptions\SecurityException::class);

		$request = new Request(
			[
				'server' => [
					'HTTP_ORIGIN' => 'test'
				]
			],
			$this->createMock(ISecureRandom::class),
			$this->createMock(IConfig::class)
		);
		$this->reflector->reflect($this, __FUNCTION__);
		$middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler);

		$response = new Response();
		$response->addHeader('AcCess-control-Allow-Credentials ', 'TRUE');
		$middleware->afterController($this->controller, __FUNCTION__, $response);
	}

	/**
	 * @CORS
	 * @PublicPage
	 */
	public function testNoCORSShouldAllowCookieAuth() {
		$request = new Request(
			[],
			$this->createMock(ISecureRandom::class),
			$this->createMock(IConfig::class)
		);
		$this->reflector->reflect($this, __FUNCTION__);
		$middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler);
		$this->session->expects($this->never())
			->method('logout');
		$this->session->expects($this->never())
			->method('logClientIn')
			->with($this->equalTo('user'), $this->equalTo('pass'))
			->willReturn(true);
		$this->reflector->reflect($this, __FUNCTION__);

		$middleware->beforeController($this->controller, __FUNCTION__);
	}

	/**
	 * @CORS
	 */
	public function testCORSShouldRelogin() {
		$request = new Request(
			['server' => [
				'PHP_AUTH_USER' => 'user',
				'PHP_AUTH_PW' => 'pass'
			]],
			$this->createMock(ISecureRandom::class),
			$this->createMock(IConfig::class)
		);
		$this->session->expects($this->once())
			->method('logout');
		$this->session->expects($this->once())
			->method('logClientIn')
			->with($this->equalTo('user'), $this->equalTo('pass'))
			->willReturn(true);
		$this->reflector->reflect($this, __FUNCTION__);
		$middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler);

		$middleware->beforeController($this->controller, __FUNCTION__);
	}

	/**
	 * @CORS
	 */
	public function testCORSShouldFailIfPasswordLoginIsForbidden() {
		$this->expectException(\OC\AppFramework\Middleware\Security\Exceptions\SecurityException::class);

		$request = new Request(
			['server' => [
				'PHP_AUTH_USER' => 'user',
				'PHP_AUTH_PW' => 'pass'
			]],
			$this->createMock(ISecureRandom::class),
			$this->createMock(IConfig::class)
		);
		$this->session->expects($this->once())
			->method('logout');
		$this->session->expects($this->once())
			->method('logClientIn')
			->with($this->equalTo('user'), $this->equalTo('pass'))
			->will($this->throwException(new \OC\Authentication\Exceptions\PasswordLoginForbiddenException));
		$this->reflector->reflect($this, __FUNCTION__);
		$middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler);

		$middleware->beforeController($this->controller, __FUNCTION__);
	}

	/**
	 * @CORS
	 */
	public function testCORSShouldNotAllowCookieAuth() {
		$this->expectException(\OC\AppFramework\Middleware\Security\Exceptions\SecurityException::class);

		$request = new Request(
			['server' => [
				'PHP_AUTH_USER' => 'user',
				'PHP_AUTH_PW' => 'pass'
			]],
			$this->createMock(ISecureRandom::class),
			$this->createMock(IConfig::class)
		);
		$this->session->expects($this->once())
			->method('logout');
		$this->session->expects($this->once())
			->method('logClientIn')
			->with($this->equalTo('user'), $this->equalTo('pass'))
			->willReturn(false);
		$this->reflector->reflect($this, __FUNCTION__);
		$middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler);

		$middleware->beforeController($this->controller, __FUNCTION__);
	}

	public function testAfterExceptionWithSecurityExceptionNoStatus() {
		$request = new Request(
			['server' => [
				'PHP_AUTH_USER' => 'user',
				'PHP_AUTH_PW' => 'pass'
			]],
			$this->createMock(ISecureRandom::class),
			$this->createMock(IConfig::class)
		);
		$middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler);
		$response = $middleware->afterException($this->controller, __FUNCTION__, new SecurityException('A security exception'));

		$expected = new JSONResponse(['message' => 'A security exception'], 500);
		$this->assertEquals($expected, $response);
	}

	public function testAfterExceptionWithSecurityExceptionWithStatus() {
		$request = new Request(
			['server' => [
				'PHP_AUTH_USER' => 'user',
				'PHP_AUTH_PW' => 'pass'
			]],
			$this->createMock(ISecureRandom::class),
			$this->createMock(IConfig::class)
		);
		$middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler);
		$response = $middleware->afterException($this->controller, __FUNCTION__, new SecurityException('A security exception', 501));

		$expected = new JSONResponse(['message' => 'A security exception'], 501);
		$this->assertEquals($expected, $response);
	}


	public function testAfterExceptionWithRegularException() {
		$this->expectException(\Exception::class);
		$this->expectExceptionMessage('A regular exception');

		$request = new Request(
			['server' => [
				'PHP_AUTH_USER' => 'user',
				'PHP_AUTH_PW' => 'pass'
			]],
			$this->createMock(ISecureRandom::class),
			$this->createMock(IConfig::class)
		);
		$middleware = new CORSMiddleware($request, $this->reflector, $this->session, $this->throttler);
		$middleware->afterException($this->controller, __FUNCTION__, new \Exception('A regular exception'));
	}
}