Completed
Pull Request — master (#9256)
by Morris
28:24 queued 10:42
created
apps/federation/lib/BackgroundJob/GetSharedSecret.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 
155 155
 	protected function run($argument) {
156 156
 		$target = $argument['url'];
157
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
157
+		$created = isset($argument['created']) ? (int) $argument['created'] : $this->timeFactory->getTime();
158 158
 		$currentTime = $this->timeFactory->getTime();
159 159
 		$source = $this->urlGenerator->getAbsoluteURL('/');
160 160
 		$source = rtrim($source, '/');
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
 		$deadline = $currentTime - $this->maxLifespan;
165 165
 		if ($created < $deadline) {
166 166
 			$this->retainJob = false;
167
-			$this->trustedServers->setServerStatus($target,TrustedServers::STATUS_FAILURE);
167
+			$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
168 168
 			return;
169 169
 		}
170 170
 
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
173 173
 
174 174
 		// make sure that we have a well formatted url
175
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/');
175
+		$url = rtrim($target, '/').'/'.trim($endPoint, '/');
176 176
 
177 177
 		$result = null;
178 178
 		try {
@@ -195,21 +195,21 @@  discard block
 block discarded – undo
195 195
 		} catch (ClientException $e) {
196 196
 			$status = $e->getCode();
197 197
 			if ($status === Http::STATUS_FORBIDDEN) {
198
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
198
+				$this->logger->info($target.' refused to exchange a shared secret with you.', ['app' => 'federation']);
199 199
 			} else {
200
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
200
+				$this->logger->info($target.' responded with a '.$status.' containing: '.$e->getMessage(), ['app' => 'federation']);
201 201
 			}
202 202
 		} catch (RequestException $e) {
203 203
 			$status = -1; // There is no status code if we could not connect
204 204
 			$this->logger->logException($e, [
205
-				'message' => 'Could not connect to ' . $target,
205
+				'message' => 'Could not connect to '.$target,
206 206
 				'level' => \OCP\Util::INFO,
207 207
 				'app' => 'federation',
208 208
 			]);
209 209
 		} catch (RingException $e) {
210 210
 			$status = -1; // There is no status code if we could not connect
211 211
 			$this->logger->logException($e, [
212
-				'message' => 'Could not connect to ' . $target,
212
+				'message' => 'Could not connect to '.$target,
213 213
 				'level' => \OCP\Util::INFO,
214 214
 				'app' => 'federation',
215 215
 			]);
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
 				);
237 237
 			} else {
238 238
 				$this->logger->error(
239
-						'remote server "' . $target . '"" does not return a valid shared secret. Received data: ' . $body,
239
+						'remote server "'.$target.'"" does not return a valid shared secret. Received data: '.$body,
240 240
 						['app' => 'federation']
241 241
 				);
242 242
 				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 	 */
253 253
 	protected function reAddJob(array $argument) {
254 254
 		$url = $argument['url'];
255
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
255
+		$created = isset($argument['created']) ? (int) $argument['created'] : $this->timeFactory->getTime();
256 256
 		$token = $argument['token'];
257 257
 		$this->jobList->add(
258 258
 			GetSharedSecret::class,
Please login to merge, or discard this patch.
Indentation   +174 added lines, -174 removed lines patch added patch discarded remove patch
@@ -55,203 +55,203 @@
 block discarded – undo
55 55
  */
56 56
 class GetSharedSecret extends Job {
57 57
 
58
-	/** @var IClient */
59
-	private $httpClient;
58
+    /** @var IClient */
59
+    private $httpClient;
60 60
 
61
-	/** @var IJobList */
62
-	private $jobList;
61
+    /** @var IJobList */
62
+    private $jobList;
63 63
 
64
-	/** @var IURLGenerator */
65
-	private $urlGenerator;
64
+    /** @var IURLGenerator */
65
+    private $urlGenerator;
66 66
 
67
-	/** @var TrustedServers  */
68
-	private $trustedServers;
67
+    /** @var TrustedServers  */
68
+    private $trustedServers;
69 69
 
70
-	/** @var IDiscoveryService  */
71
-	private $ocsDiscoveryService;
70
+    /** @var IDiscoveryService  */
71
+    private $ocsDiscoveryService;
72 72
 
73
-	/** @var ILogger */
74
-	private $logger;
73
+    /** @var ILogger */
74
+    private $logger;
75 75
 
76
-	/** @var ITimeFactory */
77
-	private $timeFactory;
76
+    /** @var ITimeFactory */
77
+    private $timeFactory;
78 78
 
79
-	/** @var bool */
80
-	protected $retainJob = false;
79
+    /** @var bool */
80
+    protected $retainJob = false;
81 81
 
82
-	private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
82
+    private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/shared-secret';
83 83
 
84
-	/** @var  int  30 day = 2592000sec */
85
-	private $maxLifespan = 2592000;
84
+    /** @var  int  30 day = 2592000sec */
85
+    private $maxLifespan = 2592000;
86 86
 
87
-	/**
88
-	 * RequestSharedSecret constructor.
89
-	 *
90
-	 * @param IClientService $httpClientService
91
-	 * @param IURLGenerator $urlGenerator
92
-	 * @param IJobList $jobList
93
-	 * @param TrustedServers $trustedServers
94
-	 * @param ILogger $logger
95
-	 * @param IDiscoveryService $ocsDiscoveryService
96
-	 * @param ITimeFactory $timeFactory
97
-	 */
98
-	public function __construct(
99
-		IClientService $httpClientService,
100
-		IURLGenerator $urlGenerator,
101
-		IJobList $jobList,
102
-		TrustedServers $trustedServers,
103
-		ILogger $logger,
104
-		IDiscoveryService $ocsDiscoveryService,
105
-		ITimeFactory $timeFactory
106
-	) {
107
-		$this->logger = $logger;
108
-		$this->httpClient = $httpClientService->newClient();
109
-		$this->jobList = $jobList;
110
-		$this->urlGenerator = $urlGenerator;
111
-		$this->ocsDiscoveryService = $ocsDiscoveryService;
112
-		$this->trustedServers = $trustedServers;
113
-		$this->timeFactory = $timeFactory;
114
-	}
87
+    /**
88
+     * RequestSharedSecret constructor.
89
+     *
90
+     * @param IClientService $httpClientService
91
+     * @param IURLGenerator $urlGenerator
92
+     * @param IJobList $jobList
93
+     * @param TrustedServers $trustedServers
94
+     * @param ILogger $logger
95
+     * @param IDiscoveryService $ocsDiscoveryService
96
+     * @param ITimeFactory $timeFactory
97
+     */
98
+    public function __construct(
99
+        IClientService $httpClientService,
100
+        IURLGenerator $urlGenerator,
101
+        IJobList $jobList,
102
+        TrustedServers $trustedServers,
103
+        ILogger $logger,
104
+        IDiscoveryService $ocsDiscoveryService,
105
+        ITimeFactory $timeFactory
106
+    ) {
107
+        $this->logger = $logger;
108
+        $this->httpClient = $httpClientService->newClient();
109
+        $this->jobList = $jobList;
110
+        $this->urlGenerator = $urlGenerator;
111
+        $this->ocsDiscoveryService = $ocsDiscoveryService;
112
+        $this->trustedServers = $trustedServers;
113
+        $this->timeFactory = $timeFactory;
114
+    }
115 115
 
116
-	/**
117
-	 * run the job, then remove it from the joblist
118
-	 *
119
-	 * @param JobList $jobList
120
-	 * @param ILogger|null $logger
121
-	 */
122
-	public function execute($jobList, ILogger $logger = null) {
123
-		$target = $this->argument['url'];
124
-		// only execute if target is still in the list of trusted domains
125
-		if ($this->trustedServers->isTrustedServer($target)) {
126
-			$this->parentExecute($jobList, $logger);
127
-		}
116
+    /**
117
+     * run the job, then remove it from the joblist
118
+     *
119
+     * @param JobList $jobList
120
+     * @param ILogger|null $logger
121
+     */
122
+    public function execute($jobList, ILogger $logger = null) {
123
+        $target = $this->argument['url'];
124
+        // only execute if target is still in the list of trusted domains
125
+        if ($this->trustedServers->isTrustedServer($target)) {
126
+            $this->parentExecute($jobList, $logger);
127
+        }
128 128
 
129
-		$jobList->remove($this, $this->argument);
129
+        $jobList->remove($this, $this->argument);
130 130
 
131
-		if ($this->retainJob) {
132
-			$this->reAddJob($this->argument);
133
-		}
134
-	}
131
+        if ($this->retainJob) {
132
+            $this->reAddJob($this->argument);
133
+        }
134
+    }
135 135
 
136
-	/**
137
-	 * call execute() method of parent
138
-	 *
139
-	 * @param JobList $jobList
140
-	 * @param ILogger $logger
141
-	 */
142
-	protected function parentExecute($jobList, $logger = null) {
143
-		parent::execute($jobList, $logger);
144
-	}
136
+    /**
137
+     * call execute() method of parent
138
+     *
139
+     * @param JobList $jobList
140
+     * @param ILogger $logger
141
+     */
142
+    protected function parentExecute($jobList, $logger = null) {
143
+        parent::execute($jobList, $logger);
144
+    }
145 145
 
146
-	protected function run($argument) {
147
-		$target = $argument['url'];
148
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
149
-		$currentTime = $this->timeFactory->getTime();
150
-		$source = $this->urlGenerator->getAbsoluteURL('/');
151
-		$source = rtrim($source, '/');
152
-		$token = $argument['token'];
146
+    protected function run($argument) {
147
+        $target = $argument['url'];
148
+        $created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
149
+        $currentTime = $this->timeFactory->getTime();
150
+        $source = $this->urlGenerator->getAbsoluteURL('/');
151
+        $source = rtrim($source, '/');
152
+        $token = $argument['token'];
153 153
 
154
-		// kill job after 30 days of trying
155
-		$deadline = $currentTime - $this->maxLifespan;
156
-		if ($created < $deadline) {
157
-			$this->retainJob = false;
158
-			$this->trustedServers->setServerStatus($target,TrustedServers::STATUS_FAILURE);
159
-			return;
160
-		}
154
+        // kill job after 30 days of trying
155
+        $deadline = $currentTime - $this->maxLifespan;
156
+        if ($created < $deadline) {
157
+            $this->retainJob = false;
158
+            $this->trustedServers->setServerStatus($target,TrustedServers::STATUS_FAILURE);
159
+            return;
160
+        }
161 161
 
162
-		$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
163
-		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
162
+        $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
163
+        $endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
164 164
 
165
-		// make sure that we have a well formatted url
166
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/');
165
+        // make sure that we have a well formatted url
166
+        $url = rtrim($target, '/') . '/' . trim($endPoint, '/');
167 167
 
168
-		$result = null;
169
-		try {
170
-			$result = $this->httpClient->get(
171
-				$url,
172
-				[
173
-					'query' =>
174
-						[
175
-							'url' => $source,
176
-							'token' => $token,
177
-							'format' => 'json',
178
-						],
179
-					'timeout' => 3,
180
-					'connect_timeout' => 3,
181
-				]
182
-			);
168
+        $result = null;
169
+        try {
170
+            $result = $this->httpClient->get(
171
+                $url,
172
+                [
173
+                    'query' =>
174
+                        [
175
+                            'url' => $source,
176
+                            'token' => $token,
177
+                            'format' => 'json',
178
+                        ],
179
+                    'timeout' => 3,
180
+                    'connect_timeout' => 3,
181
+                ]
182
+            );
183 183
 
184
-			$status = $result->getStatusCode();
184
+            $status = $result->getStatusCode();
185 185
 
186
-		} catch (ClientException $e) {
187
-			$status = $e->getCode();
188
-			if ($status === Http::STATUS_FORBIDDEN) {
189
-				$this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
190
-			} else {
191
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
192
-			}
193
-		} catch (RequestException $e) {
194
-			$status = -1; // There is no status code if we could not connect
195
-			$this->logger->logException($e, [
196
-				'message' => 'Could not connect to ' . $target,
197
-				'level' => \OCP\Util::INFO,
198
-				'app' => 'federation',
199
-			]);
200
-		} catch (RingException $e) {
201
-			$status = -1; // There is no status code if we could not connect
202
-			$this->logger->logException($e, [
203
-				'message' => 'Could not connect to ' . $target,
204
-				'level' => \OCP\Util::INFO,
205
-				'app' => 'federation',
206
-			]);
207
-		} catch (\Exception $e) {
208
-			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
209
-			$this->logger->logException($e, ['app' => 'federation']);
210
-		}
186
+        } catch (ClientException $e) {
187
+            $status = $e->getCode();
188
+            if ($status === Http::STATUS_FORBIDDEN) {
189
+                $this->logger->info($target . ' refused to exchange a shared secret with you.', ['app' => 'federation']);
190
+            } else {
191
+                $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
192
+            }
193
+        } catch (RequestException $e) {
194
+            $status = -1; // There is no status code if we could not connect
195
+            $this->logger->logException($e, [
196
+                'message' => 'Could not connect to ' . $target,
197
+                'level' => \OCP\Util::INFO,
198
+                'app' => 'federation',
199
+            ]);
200
+        } catch (RingException $e) {
201
+            $status = -1; // There is no status code if we could not connect
202
+            $this->logger->logException($e, [
203
+                'message' => 'Could not connect to ' . $target,
204
+                'level' => \OCP\Util::INFO,
205
+                'app' => 'federation',
206
+            ]);
207
+        } catch (\Exception $e) {
208
+            $status = Http::STATUS_INTERNAL_SERVER_ERROR;
209
+            $this->logger->logException($e, ['app' => 'federation']);
210
+        }
211 211
 
212
-		// if we received a unexpected response we try again later
213
-		if (
214
-			$status !== Http::STATUS_OK
215
-			&& $status !== Http::STATUS_FORBIDDEN
216
-		) {
217
-			$this->retainJob = true;
218
-		}
212
+        // if we received a unexpected response we try again later
213
+        if (
214
+            $status !== Http::STATUS_OK
215
+            && $status !== Http::STATUS_FORBIDDEN
216
+        ) {
217
+            $this->retainJob = true;
218
+        }
219 219
 
220
-		if ($status === Http::STATUS_OK && $result instanceof IResponse) {
221
-			$body = $result->getBody();
222
-			$result = json_decode($body, true);
223
-			if (isset($result['ocs']['data']['sharedSecret'])) {
224
-				$this->trustedServers->addSharedSecret(
225
-						$target,
226
-						$result['ocs']['data']['sharedSecret']
227
-				);
228
-			} else {
229
-				$this->logger->error(
230
-						'remote server "' . $target . '"" does not return a valid shared secret. Received data: ' . $body,
231
-						['app' => 'federation']
232
-				);
233
-				$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
234
-			}
235
-		}
220
+        if ($status === Http::STATUS_OK && $result instanceof IResponse) {
221
+            $body = $result->getBody();
222
+            $result = json_decode($body, true);
223
+            if (isset($result['ocs']['data']['sharedSecret'])) {
224
+                $this->trustedServers->addSharedSecret(
225
+                        $target,
226
+                        $result['ocs']['data']['sharedSecret']
227
+                );
228
+            } else {
229
+                $this->logger->error(
230
+                        'remote server "' . $target . '"" does not return a valid shared secret. Received data: ' . $body,
231
+                        ['app' => 'federation']
232
+                );
233
+                $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
234
+            }
235
+        }
236 236
 
237
-	}
237
+    }
238 238
 
239
-	/**
240
-	 * re-add background job
241
-	 *
242
-	 * @param array $argument
243
-	 */
244
-	protected function reAddJob(array $argument) {
245
-		$url = $argument['url'];
246
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
247
-		$token = $argument['token'];
248
-		$this->jobList->add(
249
-			GetSharedSecret::class,
250
-			[
251
-				'url' => $url,
252
-				'token' => $token,
253
-				'created' => $created
254
-			]
255
-		);
256
-	}
239
+    /**
240
+     * re-add background job
241
+     *
242
+     * @param array $argument
243
+     */
244
+    protected function reAddJob(array $argument) {
245
+        $url = $argument['url'];
246
+        $created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
247
+        $token = $argument['token'];
248
+        $this->jobList->add(
249
+            GetSharedSecret::class,
250
+            [
251
+                'url' => $url,
252
+                'token' => $token,
253
+                'created' => $created
254
+            ]
255
+        );
256
+    }
257 257
 }
Please login to merge, or discard this patch.
apps/federation/lib/Controller/OCSAuthAPIController.php 2 patches
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -49,165 +49,165 @@
 block discarded – undo
49 49
  */
50 50
 class OCSAuthAPIController extends OCSController{
51 51
 
52
-	/** @var ISecureRandom  */
53
-	private $secureRandom;
54
-
55
-	/** @var IJobList */
56
-	private $jobList;
57
-
58
-	/** @var TrustedServers */
59
-	private $trustedServers;
60
-
61
-	/** @var DbHandler */
62
-	private $dbHandler;
63
-
64
-	/** @var ILogger */
65
-	private $logger;
66
-
67
-	/** @var ITimeFactory */
68
-	private $timeFactory;
69
-
70
-	/**
71
-	 * OCSAuthAPI constructor.
72
-	 *
73
-	 * @param string $appName
74
-	 * @param IRequest $request
75
-	 * @param ISecureRandom $secureRandom
76
-	 * @param IJobList $jobList
77
-	 * @param TrustedServers $trustedServers
78
-	 * @param DbHandler $dbHandler
79
-	 * @param ILogger $logger
80
-	 * @param ITimeFactory $timeFactory
81
-	 */
82
-	public function __construct(
83
-		$appName,
84
-		IRequest $request,
85
-		ISecureRandom $secureRandom,
86
-		IJobList $jobList,
87
-		TrustedServers $trustedServers,
88
-		DbHandler $dbHandler,
89
-		ILogger $logger,
90
-		ITimeFactory $timeFactory
91
-	) {
92
-		parent::__construct($appName, $request);
93
-
94
-		$this->secureRandom = $secureRandom;
95
-		$this->jobList = $jobList;
96
-		$this->trustedServers = $trustedServers;
97
-		$this->dbHandler = $dbHandler;
98
-		$this->logger = $logger;
99
-		$this->timeFactory = $timeFactory;
100
-	}
101
-
102
-	/**
103
-	 * @NoCSRFRequired
104
-	 * @PublicPage
105
-	 *
106
-	 * request received to ask remote server for a shared secret, for legacy end-points
107
-	 *
108
-	 * @param string $url
109
-	 * @param string $token
110
-	 * @return Http\DataResponse
111
-	 * @throws OCSForbiddenException
112
-	 */
113
-	public function requestSharedSecretLegacy($url, $token) {
114
-		return $this->requestSharedSecret($url, $token);
115
-	}
116
-
117
-
118
-	/**
119
-	 * @NoCSRFRequired
120
-	 * @PublicPage
121
-	 *
122
-	 * create shared secret and return it, for legacy end-points
123
-	 *
124
-	 * @param string $url
125
-	 * @param string $token
126
-	 * @return Http\DataResponse
127
-	 * @throws OCSForbiddenException
128
-	 */
129
-	public function getSharedSecretLegacy($url, $token) {
130
-		return $this->getSharedSecret($url, $token);
131
-	}
132
-
133
-	/**
134
-	 * @NoCSRFRequired
135
-	 * @PublicPage
136
-	 *
137
-	 * request received to ask remote server for a shared secret
138
-	 *
139
-	 * @param string $url
140
-	 * @param string $token
141
-	 * @return Http\DataResponse
142
-	 * @throws OCSForbiddenException
143
-	 */
144
-	public function requestSharedSecret($url, $token) {
145
-		if ($this->trustedServers->isTrustedServer($url) === false) {
146
-			$this->logger->error('remote server not trusted (' . $url . ') while requesting shared secret', ['app' => 'federation']);
147
-			throw new OCSForbiddenException();
148
-		}
149
-
150
-		// if both server initiated the exchange of the shared secret the greater
151
-		// token wins
152
-		$localToken = $this->dbHandler->getToken($url);
153
-		if (strcmp($localToken, $token) > 0) {
154
-			$this->logger->info(
155
-				'remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.',
156
-				['app' => 'federation']
157
-			);
158
-			throw new OCSForbiddenException();
159
-		}
160
-
161
-		$this->jobList->add(
162
-			'OCA\Federation\BackgroundJob\GetSharedSecret',
163
-			[
164
-				'url' => $url,
165
-				'token' => $token,
166
-				'created' => $this->timeFactory->getTime()
167
-			]
168
-		);
169
-
170
-		return new Http\DataResponse();
171
-	}
172
-
173
-	/**
174
-	 * @NoCSRFRequired
175
-	 * @PublicPage
176
-	 *
177
-	 * create shared secret and return it
178
-	 *
179
-	 * @param string $url
180
-	 * @param string $token
181
-	 * @return Http\DataResponse
182
-	 * @throws OCSForbiddenException
183
-	 */
184
-	public function getSharedSecret($url, $token) {
185
-
186
-		if ($this->trustedServers->isTrustedServer($url) === false) {
187
-			$this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']);
188
-			throw new OCSForbiddenException();
189
-		}
190
-
191
-		if ($this->isValidToken($url, $token) === false) {
192
-			$expectedToken = $this->dbHandler->getToken($url);
193
-			$this->logger->error(
194
-				'remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "'. $expectedToken . '") while getting shared secret',
195
-				['app' => 'federation']
196
-			);
197
-			throw new OCSForbiddenException();
198
-		}
199
-
200
-		$sharedSecret = $this->secureRandom->generate(32);
201
-
202
-		$this->trustedServers->addSharedSecret($url, $sharedSecret);
203
-
204
-		return new Http\DataResponse([
205
-			'sharedSecret' => $sharedSecret
206
-		]);
207
-	}
208
-
209
-	protected function isValidToken($url, $token) {
210
-		$storedToken = $this->dbHandler->getToken($url);
211
-		return hash_equals($storedToken, $token);
212
-	}
52
+    /** @var ISecureRandom  */
53
+    private $secureRandom;
54
+
55
+    /** @var IJobList */
56
+    private $jobList;
57
+
58
+    /** @var TrustedServers */
59
+    private $trustedServers;
60
+
61
+    /** @var DbHandler */
62
+    private $dbHandler;
63
+
64
+    /** @var ILogger */
65
+    private $logger;
66
+
67
+    /** @var ITimeFactory */
68
+    private $timeFactory;
69
+
70
+    /**
71
+     * OCSAuthAPI constructor.
72
+     *
73
+     * @param string $appName
74
+     * @param IRequest $request
75
+     * @param ISecureRandom $secureRandom
76
+     * @param IJobList $jobList
77
+     * @param TrustedServers $trustedServers
78
+     * @param DbHandler $dbHandler
79
+     * @param ILogger $logger
80
+     * @param ITimeFactory $timeFactory
81
+     */
82
+    public function __construct(
83
+        $appName,
84
+        IRequest $request,
85
+        ISecureRandom $secureRandom,
86
+        IJobList $jobList,
87
+        TrustedServers $trustedServers,
88
+        DbHandler $dbHandler,
89
+        ILogger $logger,
90
+        ITimeFactory $timeFactory
91
+    ) {
92
+        parent::__construct($appName, $request);
93
+
94
+        $this->secureRandom = $secureRandom;
95
+        $this->jobList = $jobList;
96
+        $this->trustedServers = $trustedServers;
97
+        $this->dbHandler = $dbHandler;
98
+        $this->logger = $logger;
99
+        $this->timeFactory = $timeFactory;
100
+    }
101
+
102
+    /**
103
+     * @NoCSRFRequired
104
+     * @PublicPage
105
+     *
106
+     * request received to ask remote server for a shared secret, for legacy end-points
107
+     *
108
+     * @param string $url
109
+     * @param string $token
110
+     * @return Http\DataResponse
111
+     * @throws OCSForbiddenException
112
+     */
113
+    public function requestSharedSecretLegacy($url, $token) {
114
+        return $this->requestSharedSecret($url, $token);
115
+    }
116
+
117
+
118
+    /**
119
+     * @NoCSRFRequired
120
+     * @PublicPage
121
+     *
122
+     * create shared secret and return it, for legacy end-points
123
+     *
124
+     * @param string $url
125
+     * @param string $token
126
+     * @return Http\DataResponse
127
+     * @throws OCSForbiddenException
128
+     */
129
+    public function getSharedSecretLegacy($url, $token) {
130
+        return $this->getSharedSecret($url, $token);
131
+    }
132
+
133
+    /**
134
+     * @NoCSRFRequired
135
+     * @PublicPage
136
+     *
137
+     * request received to ask remote server for a shared secret
138
+     *
139
+     * @param string $url
140
+     * @param string $token
141
+     * @return Http\DataResponse
142
+     * @throws OCSForbiddenException
143
+     */
144
+    public function requestSharedSecret($url, $token) {
145
+        if ($this->trustedServers->isTrustedServer($url) === false) {
146
+            $this->logger->error('remote server not trusted (' . $url . ') while requesting shared secret', ['app' => 'federation']);
147
+            throw new OCSForbiddenException();
148
+        }
149
+
150
+        // if both server initiated the exchange of the shared secret the greater
151
+        // token wins
152
+        $localToken = $this->dbHandler->getToken($url);
153
+        if (strcmp($localToken, $token) > 0) {
154
+            $this->logger->info(
155
+                'remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.',
156
+                ['app' => 'federation']
157
+            );
158
+            throw new OCSForbiddenException();
159
+        }
160
+
161
+        $this->jobList->add(
162
+            'OCA\Federation\BackgroundJob\GetSharedSecret',
163
+            [
164
+                'url' => $url,
165
+                'token' => $token,
166
+                'created' => $this->timeFactory->getTime()
167
+            ]
168
+        );
169
+
170
+        return new Http\DataResponse();
171
+    }
172
+
173
+    /**
174
+     * @NoCSRFRequired
175
+     * @PublicPage
176
+     *
177
+     * create shared secret and return it
178
+     *
179
+     * @param string $url
180
+     * @param string $token
181
+     * @return Http\DataResponse
182
+     * @throws OCSForbiddenException
183
+     */
184
+    public function getSharedSecret($url, $token) {
185
+
186
+        if ($this->trustedServers->isTrustedServer($url) === false) {
187
+            $this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']);
188
+            throw new OCSForbiddenException();
189
+        }
190
+
191
+        if ($this->isValidToken($url, $token) === false) {
192
+            $expectedToken = $this->dbHandler->getToken($url);
193
+            $this->logger->error(
194
+                'remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "'. $expectedToken . '") while getting shared secret',
195
+                ['app' => 'federation']
196
+            );
197
+            throw new OCSForbiddenException();
198
+        }
199
+
200
+        $sharedSecret = $this->secureRandom->generate(32);
201
+
202
+        $this->trustedServers->addSharedSecret($url, $sharedSecret);
203
+
204
+        return new Http\DataResponse([
205
+            'sharedSecret' => $sharedSecret
206
+        ]);
207
+    }
208
+
209
+    protected function isValidToken($url, $token) {
210
+        $storedToken = $this->dbHandler->getToken($url);
211
+        return hash_equals($storedToken, $token);
212
+    }
213 213
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
  *
48 48
  * @package OCA\Federation\Controller
49 49
  */
50
-class OCSAuthAPIController extends OCSController{
50
+class OCSAuthAPIController extends OCSController {
51 51
 
52 52
 	/** @var ISecureRandom  */
53 53
 	private $secureRandom;
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 	 */
144 144
 	public function requestSharedSecret($url, $token) {
145 145
 		if ($this->trustedServers->isTrustedServer($url) === false) {
146
-			$this->logger->error('remote server not trusted (' . $url . ') while requesting shared secret', ['app' => 'federation']);
146
+			$this->logger->error('remote server not trusted ('.$url.') while requesting shared secret', ['app' => 'federation']);
147 147
 			throw new OCSForbiddenException();
148 148
 		}
149 149
 
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 		$localToken = $this->dbHandler->getToken($url);
153 153
 		if (strcmp($localToken, $token) > 0) {
154 154
 			$this->logger->info(
155
-				'remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.',
155
+				'remote server ('.$url.') presented lower token. We will initiate the exchange of the shared secret.',
156 156
 				['app' => 'federation']
157 157
 			);
158 158
 			throw new OCSForbiddenException();
@@ -184,14 +184,14 @@  discard block
 block discarded – undo
184 184
 	public function getSharedSecret($url, $token) {
185 185
 
186 186
 		if ($this->trustedServers->isTrustedServer($url) === false) {
187
-			$this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']);
187
+			$this->logger->error('remote server not trusted ('.$url.') while getting shared secret', ['app' => 'federation']);
188 188
 			throw new OCSForbiddenException();
189 189
 		}
190 190
 
191 191
 		if ($this->isValidToken($url, $token) === false) {
192 192
 			$expectedToken = $this->dbHandler->getToken($url);
193 193
 			$this->logger->error(
194
-				'remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "'. $expectedToken . '") while getting shared secret',
194
+				'remote server ('.$url.') didn\'t send a valid token (got "'.$token.'" but expected "'.$expectedToken.'") while getting shared secret',
195 195
 				['app' => 'federation']
196 196
 			);
197 197
 			throw new OCSForbiddenException();
Please login to merge, or discard this patch.
apps/federation/lib/BackgroundJob/RequestSharedSecret.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 	protected function run($argument) {
155 155
 
156 156
 		$target = $argument['url'];
157
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
157
+		$created = isset($argument['created']) ? (int) $argument['created'] : $this->timeFactory->getTime();
158 158
 		$currentTime = $this->timeFactory->getTime();
159 159
 		$source = $this->urlGenerator->getAbsoluteURL('/');
160 160
 		$source = rtrim($source, '/');
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
173 173
 
174 174
 		// make sure that we have a well formated url
175
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/');
175
+		$url = rtrim($target, '/').'/'.trim($endPoint, '/');
176 176
 
177 177
 		try {
178 178
 			$result = $this->httpClient->post(
@@ -193,16 +193,16 @@  discard block
 block discarded – undo
193 193
 		} catch (ClientException $e) {
194 194
 			$status = $e->getCode();
195 195
 			if ($status === Http::STATUS_FORBIDDEN) {
196
-				$this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
196
+				$this->logger->info($target.' refused to ask for a shared secret.', ['app' => 'federation']);
197 197
 			} else {
198
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
198
+				$this->logger->info($target.' responded with a '.$status.' containing: '.$e->getMessage(), ['app' => 'federation']);
199 199
 			}
200 200
 		} catch (RequestException $e) {
201 201
 			$status = -1; // There is no status code if we could not connect
202
-			$this->logger->info('Could not connect to ' . $target, ['app' => 'federation']);
202
+			$this->logger->info('Could not connect to '.$target, ['app' => 'federation']);
203 203
 		} catch (RingException $e) {
204 204
 			$status = -1; // There is no status code if we could not connect
205
-			$this->logger->info('Could not connect to ' . $target, ['app' => 'federation']);
205
+			$this->logger->info('Could not connect to '.$target, ['app' => 'federation']);
206 206
 		} catch (\Exception $e) {
207 207
 			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
208 208
 			$this->logger->logException($e, ['app' => 'federation']);
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 	 */
226 226
 	protected function reAddJob(array $argument) {
227 227
 		$url = $argument['url'];
228
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
228
+		$created = isset($argument['created']) ? (int) $argument['created'] : $this->timeFactory->getTime();
229 229
 		$token = $argument['token'];
230 230
 
231 231
 		$this->jobList->add(
Please login to merge, or discard this patch.
Indentation   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -55,179 +55,179 @@
 block discarded – undo
55 55
  */
56 56
 class RequestSharedSecret extends Job {
57 57
 
58
-	/** @var IClient */
59
-	private $httpClient;
60
-
61
-	/** @var IJobList */
62
-	private $jobList;
63
-
64
-	/** @var IURLGenerator */
65
-	private $urlGenerator;
66
-
67
-	/** @var TrustedServers */
68
-	private $trustedServers;
69
-
70
-	/** @var IDiscoveryService  */
71
-	private $ocsDiscoveryService;
72
-
73
-	/** @var ILogger */
74
-	private $logger;
75
-
76
-	/** @var ITimeFactory */
77
-	private $timeFactory;
78
-
79
-	/** @var bool */
80
-	protected $retainJob = false;
81
-
82
-	private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret';
83
-
84
-	/** @var  int  30 day = 2592000sec */
85
-	private $maxLifespan = 2592000;
86
-
87
-	/**
88
-	 * RequestSharedSecret constructor.
89
-	 *
90
-	 * @param IClientService $httpClientService
91
-	 * @param IURLGenerator $urlGenerator
92
-	 * @param IJobList $jobList
93
-	 * @param TrustedServers $trustedServers
94
-	 * @param IDiscoveryService $ocsDiscoveryService
95
-	 * @param ILogger $logger
96
-	 * @param ITimeFactory $timeFactory
97
-	 */
98
-	public function __construct(
99
-		IClientService $httpClientService,
100
-		IURLGenerator $urlGenerator,
101
-		IJobList $jobList,
102
-		TrustedServers $trustedServers,
103
-		IDiscoveryService $ocsDiscoveryService,
104
-		ILogger $logger,
105
-		ITimeFactory $timeFactory
106
-	) {
107
-		$this->httpClient = $httpClientService->newClient();
108
-		$this->jobList = $jobList;
109
-		$this->urlGenerator = $urlGenerator;
110
-		$this->logger = $logger;
111
-		$this->ocsDiscoveryService = $ocsDiscoveryService;
112
-		$this->trustedServers = $trustedServers;
113
-		$this->timeFactory = $timeFactory;
114
-	}
115
-
116
-
117
-	/**
118
-	 * run the job, then remove it from the joblist
119
-	 *
120
-	 * @param JobList $jobList
121
-	 * @param ILogger|null $logger
122
-	 */
123
-	public function execute($jobList, ILogger $logger = null) {
124
-		$target = $this->argument['url'];
125
-		// only execute if target is still in the list of trusted domains
126
-		if ($this->trustedServers->isTrustedServer($target)) {
127
-			$this->parentExecute($jobList, $logger);
128
-		}
129
-
130
-		$jobList->remove($this, $this->argument);
131
-
132
-		if ($this->retainJob) {
133
-			$this->reAddJob($this->argument);
134
-		}
135
-	}
136
-
137
-	/**
138
-	 * call execute() method of parent
139
-	 *
140
-	 * @param JobList $jobList
141
-	 * @param ILogger $logger
142
-	 */
143
-	protected function parentExecute($jobList, $logger) {
144
-		parent::execute($jobList, $logger);
145
-	}
146
-
147
-	protected function run($argument) {
148
-
149
-		$target = $argument['url'];
150
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
151
-		$currentTime = $this->timeFactory->getTime();
152
-		$source = $this->urlGenerator->getAbsoluteURL('/');
153
-		$source = rtrim($source, '/');
154
-		$token = $argument['token'];
155
-
156
-		// kill job after 30 days of trying
157
-		$deadline = $currentTime - $this->maxLifespan;
158
-		if ($created < $deadline) {
159
-			$this->retainJob = false;
160
-			$this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
161
-			return;
162
-		}
163
-
164
-		$endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
165
-		$endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
166
-
167
-		// make sure that we have a well formated url
168
-		$url = rtrim($target, '/') . '/' . trim($endPoint, '/');
169
-
170
-		try {
171
-			$result = $this->httpClient->post(
172
-				$url,
173
-				[
174
-					'body' => [
175
-						'url' => $source,
176
-						'token' => $token,
177
-						'format' => 'json',
178
-					],
179
-					'timeout' => 3,
180
-					'connect_timeout' => 3,
181
-				]
182
-			);
183
-
184
-			$status = $result->getStatusCode();
185
-
186
-		} catch (ClientException $e) {
187
-			$status = $e->getCode();
188
-			if ($status === Http::STATUS_FORBIDDEN) {
189
-				$this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
190
-			} else {
191
-				$this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
192
-			}
193
-		} catch (RequestException $e) {
194
-			$status = -1; // There is no status code if we could not connect
195
-			$this->logger->info('Could not connect to ' . $target, ['app' => 'federation']);
196
-		} catch (RingException $e) {
197
-			$status = -1; // There is no status code if we could not connect
198
-			$this->logger->info('Could not connect to ' . $target, ['app' => 'federation']);
199
-		} catch (\Exception $e) {
200
-			$status = Http::STATUS_INTERNAL_SERVER_ERROR;
201
-			$this->logger->logException($e, ['app' => 'federation']);
202
-		}
203
-
204
-		// if we received a unexpected response we try again later
205
-		if (
206
-			$status !== Http::STATUS_OK
207
-			&& $status !== Http::STATUS_FORBIDDEN
208
-		) {
209
-			$this->retainJob = true;
210
-		}
211
-
212
-	}
213
-
214
-	/**
215
-	 * re-add background job
216
-	 *
217
-	 * @param array $argument
218
-	 */
219
-	protected function reAddJob(array $argument) {
220
-		$url = $argument['url'];
221
-		$created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
222
-		$token = $argument['token'];
223
-
224
-		$this->jobList->add(
225
-			RequestSharedSecret::class,
226
-			[
227
-				'url' => $url,
228
-				'token' => $token,
229
-				'created' => $created
230
-			]
231
-		);
232
-	}
58
+    /** @var IClient */
59
+    private $httpClient;
60
+
61
+    /** @var IJobList */
62
+    private $jobList;
63
+
64
+    /** @var IURLGenerator */
65
+    private $urlGenerator;
66
+
67
+    /** @var TrustedServers */
68
+    private $trustedServers;
69
+
70
+    /** @var IDiscoveryService  */
71
+    private $ocsDiscoveryService;
72
+
73
+    /** @var ILogger */
74
+    private $logger;
75
+
76
+    /** @var ITimeFactory */
77
+    private $timeFactory;
78
+
79
+    /** @var bool */
80
+    protected $retainJob = false;
81
+
82
+    private $defaultEndPoint = '/ocs/v2.php/apps/federation/api/v1/request-shared-secret';
83
+
84
+    /** @var  int  30 day = 2592000sec */
85
+    private $maxLifespan = 2592000;
86
+
87
+    /**
88
+     * RequestSharedSecret constructor.
89
+     *
90
+     * @param IClientService $httpClientService
91
+     * @param IURLGenerator $urlGenerator
92
+     * @param IJobList $jobList
93
+     * @param TrustedServers $trustedServers
94
+     * @param IDiscoveryService $ocsDiscoveryService
95
+     * @param ILogger $logger
96
+     * @param ITimeFactory $timeFactory
97
+     */
98
+    public function __construct(
99
+        IClientService $httpClientService,
100
+        IURLGenerator $urlGenerator,
101
+        IJobList $jobList,
102
+        TrustedServers $trustedServers,
103
+        IDiscoveryService $ocsDiscoveryService,
104
+        ILogger $logger,
105
+        ITimeFactory $timeFactory
106
+    ) {
107
+        $this->httpClient = $httpClientService->newClient();
108
+        $this->jobList = $jobList;
109
+        $this->urlGenerator = $urlGenerator;
110
+        $this->logger = $logger;
111
+        $this->ocsDiscoveryService = $ocsDiscoveryService;
112
+        $this->trustedServers = $trustedServers;
113
+        $this->timeFactory = $timeFactory;
114
+    }
115
+
116
+
117
+    /**
118
+     * run the job, then remove it from the joblist
119
+     *
120
+     * @param JobList $jobList
121
+     * @param ILogger|null $logger
122
+     */
123
+    public function execute($jobList, ILogger $logger = null) {
124
+        $target = $this->argument['url'];
125
+        // only execute if target is still in the list of trusted domains
126
+        if ($this->trustedServers->isTrustedServer($target)) {
127
+            $this->parentExecute($jobList, $logger);
128
+        }
129
+
130
+        $jobList->remove($this, $this->argument);
131
+
132
+        if ($this->retainJob) {
133
+            $this->reAddJob($this->argument);
134
+        }
135
+    }
136
+
137
+    /**
138
+     * call execute() method of parent
139
+     *
140
+     * @param JobList $jobList
141
+     * @param ILogger $logger
142
+     */
143
+    protected function parentExecute($jobList, $logger) {
144
+        parent::execute($jobList, $logger);
145
+    }
146
+
147
+    protected function run($argument) {
148
+
149
+        $target = $argument['url'];
150
+        $created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
151
+        $currentTime = $this->timeFactory->getTime();
152
+        $source = $this->urlGenerator->getAbsoluteURL('/');
153
+        $source = rtrim($source, '/');
154
+        $token = $argument['token'];
155
+
156
+        // kill job after 30 days of trying
157
+        $deadline = $currentTime - $this->maxLifespan;
158
+        if ($created < $deadline) {
159
+            $this->retainJob = false;
160
+            $this->trustedServers->setServerStatus($target, TrustedServers::STATUS_FAILURE);
161
+            return;
162
+        }
163
+
164
+        $endPoints = $this->ocsDiscoveryService->discover($target, 'FEDERATED_SHARING');
165
+        $endPoint = isset($endPoints['shared-secret']) ? $endPoints['shared-secret'] : $this->defaultEndPoint;
166
+
167
+        // make sure that we have a well formated url
168
+        $url = rtrim($target, '/') . '/' . trim($endPoint, '/');
169
+
170
+        try {
171
+            $result = $this->httpClient->post(
172
+                $url,
173
+                [
174
+                    'body' => [
175
+                        'url' => $source,
176
+                        'token' => $token,
177
+                        'format' => 'json',
178
+                    ],
179
+                    'timeout' => 3,
180
+                    'connect_timeout' => 3,
181
+                ]
182
+            );
183
+
184
+            $status = $result->getStatusCode();
185
+
186
+        } catch (ClientException $e) {
187
+            $status = $e->getCode();
188
+            if ($status === Http::STATUS_FORBIDDEN) {
189
+                $this->logger->info($target . ' refused to ask for a shared secret.', ['app' => 'federation']);
190
+            } else {
191
+                $this->logger->info($target . ' responded with a ' . $status . ' containing: ' . $e->getMessage(), ['app' => 'federation']);
192
+            }
193
+        } catch (RequestException $e) {
194
+            $status = -1; // There is no status code if we could not connect
195
+            $this->logger->info('Could not connect to ' . $target, ['app' => 'federation']);
196
+        } catch (RingException $e) {
197
+            $status = -1; // There is no status code if we could not connect
198
+            $this->logger->info('Could not connect to ' . $target, ['app' => 'federation']);
199
+        } catch (\Exception $e) {
200
+            $status = Http::STATUS_INTERNAL_SERVER_ERROR;
201
+            $this->logger->logException($e, ['app' => 'federation']);
202
+        }
203
+
204
+        // if we received a unexpected response we try again later
205
+        if (
206
+            $status !== Http::STATUS_OK
207
+            && $status !== Http::STATUS_FORBIDDEN
208
+        ) {
209
+            $this->retainJob = true;
210
+        }
211
+
212
+    }
213
+
214
+    /**
215
+     * re-add background job
216
+     *
217
+     * @param array $argument
218
+     */
219
+    protected function reAddJob(array $argument) {
220
+        $url = $argument['url'];
221
+        $created = isset($argument['created']) ? (int)$argument['created'] : $this->timeFactory->getTime();
222
+        $token = $argument['token'];
223
+
224
+        $this->jobList->add(
225
+            RequestSharedSecret::class,
226
+            [
227
+                'url' => $url,
228
+                'token' => $token,
229
+                'created' => $created
230
+            ]
231
+        );
232
+    }
233 233
 }
Please login to merge, or discard this patch.