-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathconnection.py
1803 lines (1555 loc) · 80.4 KB
/
connection.py
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This module provides a Connection object to manage and persist settings when interacting with the OpenEO API.
"""
from __future__ import annotations
import datetime
import json
import logging
import os
import shlex
import sys
import warnings
from collections import OrderedDict
from pathlib import Path, PurePosixPath
from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple, Union
import requests
import shapely.geometry.base
from requests import Response
from requests.auth import AuthBase, HTTPBasicAuth
import openeo
from openeo.capabilities import ApiVersionException, ComparableVersion
from openeo.config import config_log, get_config_option
from openeo.internal.documentation import openeo_process
from openeo.internal.graph_building import FlatGraphableMixin, PGNode, as_flat_graph
from openeo.internal.jupyter import VisualDict, VisualList
from openeo.internal.processes.builder import ProcessBuilderBase
from openeo.internal.warnings import deprecated, legacy_alias
from openeo.metadata import Band, BandDimension, CollectionMetadata, SpatialDimension, TemporalDimension
from openeo.rest import CapabilitiesException, OpenEoApiError, OpenEoClientException, OpenEoRestError
from openeo.rest._datacube import build_child_callback
from openeo.rest.auth.auth import BasicBearerAuth, BearerAuth, NullAuth, OidcBearerAuth
from openeo.rest.auth.config import AuthConfig, RefreshTokenStore
from openeo.rest.auth.oidc import (
DefaultOidcClientGrant,
GrantsChecker,
OidcAuthCodePkceAuthenticator,
OidcAuthenticator,
OidcClientCredentialsAuthenticator,
OidcClientInfo,
OidcDeviceAuthenticator,
OidcException,
OidcProviderInfo,
OidcRefreshTokenAuthenticator,
OidcResourceOwnerPasswordAuthenticator,
)
from openeo.rest.datacube import DataCube, InputDate
from openeo.rest.http import requests_with_retry
from openeo.rest.job import BatchJob, RESTJob
from openeo.rest.mlmodel import MlModel
from openeo.rest.rest_capabilities import RESTCapabilities
from openeo.rest.service import Service
from openeo.rest.udp import Parameter, RESTUserDefinedProcess
from openeo.rest.userfile import UserFile
from openeo.rest.vectorcube import VectorCube
from openeo.util import (
ContextTimer,
LazyLoadCache,
dict_no_none,
ensure_list,
load_json_resource,
rfc3339,
str_truncate,
url_join,
)
_log = logging.getLogger(__name__)
# Default timeouts for requests
# TODO: get default_timeout from config?
DEFAULT_TIMEOUT = 20 * 60
DEFAULT_TIMEOUT_SYNCHRONOUS_EXECUTE = 30 * 60
class RestApiConnection:
"""Base connection class implementing generic REST API request functionality"""
def __init__(
self,
root_url: str,
auth: Optional[AuthBase] = None,
session: Optional[requests.Session] = None,
default_timeout: Optional[int] = None,
slow_response_threshold: Optional[float] = None,
):
self._root_url = root_url
self.auth = auth or NullAuth()
# TODO: #441 [WIP] Add requests_with_retry here to the session?
self.session = session or requests_with_retry()
self.default_timeout = default_timeout or DEFAULT_TIMEOUT
self.default_headers = {
"User-Agent": "openeo-python-client/{cv} {py}/{pv} {pl}".format(
cv=openeo.client_version(),
py=sys.implementation.name, pv=".".join(map(str, sys.version_info[:3])),
pl=sys.platform
)
}
self.slow_response_threshold = slow_response_threshold
@property
def root_url(self):
return self._root_url
def build_url(self, path: str):
return url_join(self._root_url, path)
def _merged_headers(self, headers: dict) -> dict:
"""Merge default headers with given headers"""
result = self.default_headers.copy()
if headers:
result.update(headers)
return result
def _is_external(self, url: str) -> bool:
"""Check if given url is external (not under root url)"""
root = self.root_url.rstrip("/")
return not (url == root or url.startswith(root + '/'))
def request(
self,
method: str,
path: str,
*,
headers: Optional[dict] = None,
auth: Optional[AuthBase] = None,
check_error: bool = True,
expected_status: Optional[Union[int, Iterable[int]]] = None,
**kwargs,
):
"""Generic request send"""
url = self.build_url(path)
# Don't send default auth headers to external domains.
auth = auth or (self.auth if not self._is_external(url) else None)
slow_response_threshold = kwargs.pop("slow_response_threshold", self.slow_response_threshold)
if _log.isEnabledFor(logging.DEBUG):
_log.debug("Request `{m} {u}` with headers {h}, auth {a}, kwargs {k}".format(
m=method.upper(), u=url, h=headers and headers.keys(), a=type(auth).__name__, k=list(kwargs.keys()))
)
with ContextTimer() as timer:
resp = self.session.request(
method=method,
url=url,
headers=self._merged_headers(headers),
auth=auth,
timeout=kwargs.pop("timeout", self.default_timeout),
**kwargs
)
if slow_response_threshold and timer.elapsed() > slow_response_threshold:
_log.warning("Slow response: `{m} {u}` took {e:.2f}s (>{t:.2f}s)".format(
m=method.upper(), u=str_truncate(url, width=64),
e=timer.elapsed(), t=slow_response_threshold
))
if _log.isEnabledFor(logging.DEBUG):
_log.debug("Got {r} headers {h!r}".format(r=resp, h=resp.headers))
# Check for API errors and unexpected HTTP status codes as desired.
status = resp.status_code
expected_status = ensure_list(expected_status) if expected_status else []
if check_error and status >= 400 and status not in expected_status:
self._raise_api_error(resp)
if expected_status and status not in expected_status:
raise OpenEoRestError("Got status code {s!r} for `{m} {p}` (expected {e!r}) with body {body}".format(
m=method.upper(), p=path, s=status, e=expected_status, body=resp.text)
)
return resp
def _raise_api_error(self, response: requests.Response):
"""Convert API error response to Python exception"""
status_code = response.status_code
try:
# Try parsing the error info according to spec and wrap it in an exception.
info = response.json()
exception = OpenEoApiError(
http_status_code=status_code,
code=info.get("code", "unknown"),
message=info.get("message", "unknown error"),
id=info.get("id"),
url=info.get("url"),
)
except Exception:
# Parsing of error info went wrong: let's see if we can still extract some helpful information.
text = response.text
_log.warning("Failed to parse API error response: {s} {t!r}".format(s=status_code, t=text))
if status_code == 502 and "Proxy Error" in text:
msg = "Received 502 Proxy Error." \
" This typically happens if an OpenEO request takes too long and is killed." \
" Consider using batch jobs instead of doing synchronous processing."
exception = OpenEoApiError(http_status_code=status_code, message=msg)
else:
exception = OpenEoApiError(http_status_code=status_code, message=text)
raise exception
def get(self, path: str, stream: bool = False, auth: Optional[AuthBase] = None, **kwargs) -> Response:
"""
Do GET request to REST API.
:param path: API path (without root url)
:param stream: True if the get request should be streamed, else False
:param auth: optional custom authentication to use instead of the default one
:return: response: Response
"""
return self.request("get", path=path, stream=stream, auth=auth, **kwargs)
def post(self, path: str, json: Optional[dict] = None, **kwargs) -> Response:
"""
Do POST request to REST API.
:param path: API path (without root url)
:param json: Data (as dictionary) to be posted with JSON encoding)
:return: response: Response
"""
return self.request("post", path=path, json=json, allow_redirects=False, **kwargs)
def delete(self, path: str, **kwargs) -> Response:
"""
Do DELETE request to REST API.
:param path: API path (without root url)
:return: response: Response
"""
return self.request("delete", path=path, allow_redirects=False, **kwargs)
def patch(self, path: str, **kwargs) -> Response:
"""
Do PATCH request to REST API.
:param path: API path (without root url)
:return: response: Response
"""
return self.request("patch", path=path, allow_redirects=False, **kwargs)
def put(self, path: str, headers: Optional[dict] = None, data: Optional[dict] = None, **kwargs) -> Response:
"""
Do PUT request to REST API.
:param path: API path (without root url)
:param headers: headers that gets added to the request.
:param data: data that gets added to the request.
:return: response: Response
"""
return self.request("put", path=path, data=data, headers=headers, allow_redirects=False, **kwargs)
def __repr__(self):
return "<{c} to {r!r} with {a}>".format(c=type(self).__name__, r=self._root_url, a=type(self.auth).__name__)
class Connection(RestApiConnection):
"""
Connection to an openEO backend.
"""
_MINIMUM_API_VERSION = ComparableVersion("1.0.0")
def __init__(
self,
url: str,
*,
auth: Optional[AuthBase] = None,
session: Optional[requests.Session] = None,
default_timeout: Optional[int] = None,
auth_config: Optional[AuthConfig] = None,
refresh_token_store: Optional[RefreshTokenStore] = None,
slow_response_threshold: Optional[float] = None,
oidc_auth_renewer: Optional[OidcAuthenticator] = None,
auto_validate: bool = True,
):
"""
Constructor of Connection, authenticates user.
:param url: String Backend root url
"""
if "://" not in url:
url = "https://" + url
self._orig_url = url
super().__init__(
root_url=self.version_discovery(url, session=session, timeout=default_timeout),
auth=auth, session=session, default_timeout=default_timeout,
slow_response_threshold=slow_response_threshold,
)
self._capabilities_cache = LazyLoadCache()
# Initial API version check.
self._api_version.require_at_least(self._MINIMUM_API_VERSION)
self._auth_config = auth_config
self._refresh_token_store = refresh_token_store
self._oidc_auth_renewer = oidc_auth_renewer
self._auto_validate = auto_validate
@classmethod
def version_discovery(
cls, url: str, session: Optional[requests.Session] = None, timeout: Optional[int] = None
) -> str:
"""
Do automatic openEO API version discovery from given url, using a "well-known URI" strategy.
:param url: initial backend url (not including "/.well-known/openeo")
:return: root url of highest supported backend version
"""
try:
connection = RestApiConnection(url, session=session)
well_known_url_response = connection.get("/.well-known/openeo", timeout=timeout)
assert well_known_url_response.status_code == 200
versions = well_known_url_response.json()["versions"]
supported_versions = [v for v in versions if cls._MINIMUM_API_VERSION <= v["api_version"]]
assert supported_versions
production_versions = [v for v in supported_versions if v.get("production", True)]
highest_version = max(production_versions or supported_versions, key=lambda v: v["api_version"])
_log.debug("Highest supported version available in backend: %s" % highest_version)
return highest_version['url']
except Exception:
# Be very lenient about failing on the well-known URI strategy.
return url
def _get_auth_config(self) -> AuthConfig:
if self._auth_config is None:
self._auth_config = AuthConfig()
return self._auth_config
def _get_refresh_token_store(self) -> RefreshTokenStore:
if self._refresh_token_store is None:
self._refresh_token_store = RefreshTokenStore()
return self._refresh_token_store
def authenticate_basic(self, username: Optional[str] = None, password: Optional[str] = None) -> Connection:
"""
Authenticate a user to the backend using basic username and password.
:param username: User name
:param password: User passphrase
"""
if not self.capabilities().supports_endpoint("/credentials/basic", method="GET"):
raise OpenEoClientException("This openEO back-end does not support basic authentication.")
if username is None:
username, password = self._get_auth_config().get_basic_auth(backend=self._orig_url)
if username is None:
raise OpenEoClientException("No username/password given or found.")
resp = self.get(
'/credentials/basic',
# /credentials/basic is the only endpoint that expects a Basic HTTP auth
auth=HTTPBasicAuth(username, password)
).json()
# Switch to bearer based authentication in further requests.
self.auth = BasicBearerAuth(access_token=resp["access_token"])
return self
def _get_oidc_provider(self, provider_id: Union[str, None] = None) -> Tuple[str, OidcProviderInfo]:
"""
Get OpenID Connect discovery URL for given provider_id
:param provider_id: id of OIDC provider as specified by backend (/credentials/oidc).
Can be None if there is just one provider.
:return: updated provider_id and provider info object
"""
oidc_info = self.get("/credentials/oidc", expected_status=200).json()
providers = OrderedDict((p["id"], p) for p in oidc_info["providers"])
if len(providers) < 1:
raise OpenEoClientException("Backend lists no OIDC providers.")
_log.info("Found OIDC providers: {p}".format(p=list(providers.keys())))
# TODO: also support specifying provider through issuer URL?
provider_id_from_env = os.environ.get("OPENEO_AUTH_PROVIDER_ID")
if provider_id:
if provider_id not in providers:
raise OpenEoClientException(
"Requested OIDC provider {r!r} not available. Should be one of {p}.".format(
r=provider_id, p=list(providers.keys())
)
)
provider = providers[provider_id]
elif provider_id_from_env and provider_id_from_env in providers:
_log.info(f"Using provider_id {provider_id_from_env!r} from OPENEO_AUTH_PROVIDER_ID env var")
provider_id = provider_id_from_env
provider = providers[provider_id]
elif len(providers) == 1:
provider_id, provider = providers.popitem()
_log.info(
f"No OIDC provider given, but only one available: {provider_id!r}. Using that one."
)
else:
# Check if there is a single provider in the config to use.
backend = self._orig_url
provider_configs = self._get_auth_config().get_oidc_provider_configs(
backend=backend
)
intersection = set(provider_configs.keys()).intersection(providers.keys())
if len(intersection) == 1:
provider_id = intersection.pop()
provider = providers[provider_id]
_log.info(
f"No OIDC provider given, but only one in config (for backend {backend!r}): {provider_id!r}. Using that one."
)
else:
provider_id, provider = providers.popitem(last=False)
_log.info(
f"No OIDC provider given. Using first provider {provider_id!r} as advertised by backend."
)
provider = OidcProviderInfo.from_dict(provider)
return provider_id, provider
def _get_oidc_provider_and_client_info(
self,
provider_id: str,
client_id: Union[str, None],
client_secret: Union[str, None],
default_client_grant_check: Union[None, GrantsChecker] = None,
) -> Tuple[str, OidcClientInfo]:
"""
Resolve provider_id and client info (as given or from config)
:param provider_id: id of OIDC provider as specified by backend (/credentials/oidc).
Can be None if there is just one provider.
:return: OIDC provider id and client info
"""
provider_id, provider = self._get_oidc_provider(provider_id)
if client_id is None:
_log.debug("No client_id: checking config for preferred client_id")
client_id, client_secret = self._get_auth_config().get_oidc_client_configs(
backend=self._orig_url, provider_id=provider_id
)
if client_id:
_log.info("Using client_id {c!r} from config (provider {p!r})".format(c=client_id, p=provider_id))
if client_id is None and default_client_grant_check:
# Try "default_clients" from backend's provider info.
_log.debug("No client_id given: checking default clients in backend's provider info")
client_id = provider.get_default_client_id(grant_check=default_client_grant_check)
if client_id:
_log.info("Using default client_id {c!r} from OIDC provider {p!r} info.".format(
c=client_id, p=provider_id
))
if client_id is None:
raise OpenEoClientException("No client_id found.")
client_info = OidcClientInfo(client_id=client_id, client_secret=client_secret, provider=provider)
return provider_id, client_info
def _authenticate_oidc(
self,
authenticator: OidcAuthenticator,
*,
provider_id: str,
store_refresh_token: bool = False,
fallback_refresh_token_to_store: Optional[str] = None,
oidc_auth_renewer: Optional[OidcAuthenticator] = None,
) -> Connection:
"""
Authenticate through OIDC and set up bearer token (based on OIDC access_token) for further requests.
"""
tokens = authenticator.get_tokens(request_refresh_token=store_refresh_token)
_log.info("Obtained tokens: {t}".format(t=[k for k, v in tokens._asdict().items() if v]))
if store_refresh_token:
refresh_token = tokens.refresh_token or fallback_refresh_token_to_store
if refresh_token:
self._get_refresh_token_store().set_refresh_token(
issuer=authenticator.provider_info.issuer,
client_id=authenticator.client_id,
refresh_token=refresh_token
)
if not oidc_auth_renewer:
oidc_auth_renewer = OidcRefreshTokenAuthenticator(
client_info=authenticator.client_info, refresh_token=refresh_token
)
else:
_log.warning("No OIDC refresh token to store.")
token = tokens.access_token
self.auth = OidcBearerAuth(provider_id=provider_id, access_token=token)
self._oidc_auth_renewer = oidc_auth_renewer
return self
def authenticate_oidc_authorization_code(
self,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
provider_id: Optional[str] = None,
timeout: Optional[int] = None,
server_address: Optional[Tuple[str, int]] = None,
webbrowser_open: Optional[Callable] = None,
store_refresh_token=False,
) -> Connection:
"""
OpenID Connect Authorization Code Flow (with PKCE).
.. deprecated:: 0.19.0
Usage of the Authorization Code flow is deprecated (because of its complexity) and will be removed.
It is recommended to use the Device Code flow with :py:meth:`authenticate_oidc_device`
or Client Credentials flow with :py:meth:`authenticate_oidc_client_credentials`.
"""
provider_id, client_info = self._get_oidc_provider_and_client_info(
provider_id=provider_id, client_id=client_id, client_secret=client_secret,
default_client_grant_check=[DefaultOidcClientGrant.AUTH_CODE_PKCE],
)
authenticator = OidcAuthCodePkceAuthenticator(
client_info=client_info,
webbrowser_open=webbrowser_open, timeout=timeout, server_address=server_address
)
return self._authenticate_oidc(authenticator, provider_id=provider_id, store_refresh_token=store_refresh_token)
def authenticate_oidc_client_credentials(
self,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
provider_id: Optional[str] = None,
) -> Connection:
"""
Authenticate with :ref:`OIDC Client Credentials flow <authenticate_oidc_client_credentials>`
Client id, secret and provider id can be specified directly through the available arguments.
It is also possible to leave these arguments empty and specify them through
environment variables ``OPENEO_AUTH_CLIENT_ID``,
``OPENEO_AUTH_CLIENT_SECRET`` and ``OPENEO_AUTH_PROVIDER_ID`` respectively
as discussed in :ref:`authenticate_oidc_client_credentials_env_vars`.
:param client_id: client id to use
:param client_secret: client secret to use
:param provider_id: provider id to use
Fallback value can be set through environment variable ``OPENEO_AUTH_PROVIDER_ID``.
.. versionchanged:: 0.18.0 Allow specifying client id, secret and provider id through environment variables.
"""
# TODO: option to get client id/secret from a config file too?
if client_id is None and "OPENEO_AUTH_CLIENT_ID" in os.environ and "OPENEO_AUTH_CLIENT_SECRET" in os.environ:
client_id = os.environ.get("OPENEO_AUTH_CLIENT_ID")
client_secret = os.environ.get("OPENEO_AUTH_CLIENT_SECRET")
_log.debug(f"Getting client id ({client_id}) and secret from environment")
provider_id, client_info = self._get_oidc_provider_and_client_info(
provider_id=provider_id, client_id=client_id, client_secret=client_secret
)
authenticator = OidcClientCredentialsAuthenticator(client_info=client_info)
return self._authenticate_oidc(
authenticator, provider_id=provider_id, store_refresh_token=False, oidc_auth_renewer=authenticator
)
def authenticate_oidc_resource_owner_password_credentials(
self,
username: str,
password: str,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
provider_id: Optional[str] = None,
store_refresh_token: bool = False,
) -> Connection:
"""
OpenId Connect Resource Owner Password Credentials
"""
provider_id, client_info = self._get_oidc_provider_and_client_info(
provider_id=provider_id, client_id=client_id, client_secret=client_secret
)
# TODO: also get username and password from config?
authenticator = OidcResourceOwnerPasswordAuthenticator(
client_info=client_info, username=username, password=password
)
return self._authenticate_oidc(authenticator, provider_id=provider_id, store_refresh_token=store_refresh_token)
def authenticate_oidc_refresh_token(
self,
client_id: Optional[str] = None,
refresh_token: Optional[str] = None,
client_secret: Optional[str] = None,
provider_id: Optional[str] = None,
*,
store_refresh_token: bool = False,
) -> Connection:
"""
Authenticate with :ref:`OIDC Refresh Token flow <authenticate_oidc_client_credentials>`
:param client_id: client id to use
:param refresh_token: refresh token to use
:param client_secret: client secret to use
:param provider_id: provider id to use.
Fallback value can be set through environment variable ``OPENEO_AUTH_PROVIDER_ID``.
:param store_refresh_token: whether to store the received refresh token automatically
.. versionchanged:: 0.19.0 Support fallback provider id through environment variable ``OPENEO_AUTH_PROVIDER_ID``.
"""
provider_id, client_info = self._get_oidc_provider_and_client_info(
provider_id=provider_id, client_id=client_id, client_secret=client_secret,
default_client_grant_check=[DefaultOidcClientGrant.REFRESH_TOKEN],
)
if refresh_token is None:
refresh_token = self._get_refresh_token_store().get_refresh_token(
issuer=client_info.provider.issuer,
client_id=client_info.client_id
)
if refresh_token is None:
raise OpenEoClientException("No refresh token given or found")
authenticator = OidcRefreshTokenAuthenticator(client_info=client_info, refresh_token=refresh_token)
return self._authenticate_oidc(
authenticator,
provider_id=provider_id,
store_refresh_token=store_refresh_token,
fallback_refresh_token_to_store=refresh_token,
oidc_auth_renewer=authenticator,
)
def authenticate_oidc_device(
self,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
provider_id: Optional[str] = None,
*,
store_refresh_token: bool = False,
use_pkce: Optional[bool] = None,
max_poll_time: float = OidcDeviceAuthenticator.DEFAULT_MAX_POLL_TIME,
**kwargs,
) -> Connection:
"""
Authenticate with the :ref:`OIDC Device Code flow <authenticate_oidc_device>`
:param client_id: client id to use instead of the default one
:param client_secret: client secret to use instead of the default one
:param provider_id: provider id to use.
Fallback value can be set through environment variable ``OPENEO_AUTH_PROVIDER_ID``.
:param store_refresh_token: whether to store the received refresh token automatically
:param use_pkce: Use PKCE instead of client secret.
If not set explicitly to `True` (use PKCE) or `False` (use client secret),
it will be attempted to detect the best mode automatically.
Note that PKCE for device code is not widely supported among OIDC providers.
:param max_poll_time: maximum time in seconds to keep polling for successful authentication.
.. versionchanged:: 0.5.1 Add :py:obj:`use_pkce` argument
.. versionchanged:: 0.17.0 Add :py:obj:`max_poll_time` argument
.. versionchanged:: 0.19.0 Support fallback provider id through environment variable ``OPENEO_AUTH_PROVIDER_ID``.
"""
_g = DefaultOidcClientGrant # alias for compactness
provider_id, client_info = self._get_oidc_provider_and_client_info(
provider_id=provider_id, client_id=client_id, client_secret=client_secret,
default_client_grant_check=(lambda grants: _g.DEVICE_CODE in grants or _g.DEVICE_CODE_PKCE in grants),
)
authenticator = OidcDeviceAuthenticator(
client_info=client_info, use_pkce=use_pkce, max_poll_time=max_poll_time, **kwargs
)
return self._authenticate_oidc(authenticator, provider_id=provider_id, store_refresh_token=store_refresh_token)
def authenticate_oidc(
self,
provider_id: Optional[str] = None,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
*,
store_refresh_token: bool = True,
use_pkce: Optional[bool] = None,
display: Callable[[str], None] = print,
max_poll_time: float = OidcDeviceAuthenticator.DEFAULT_MAX_POLL_TIME,
):
"""
Generic method to do OpenID Connect authentication.
In the context of interactive usage, this method first tries to use refresh tokens
and falls back on device code flow.
For non-interactive, machine-to-machine contexts, it is also possible to trigger
the usage of the "client_credentials" flow through environment variables.
Assuming you have set up a OIDC client (with a secret):
set ``OPENEO_AUTH_METHOD`` to ``client_credentials``,
set ``OPENEO_AUTH_CLIENT_ID`` to the client id,
and set ``OPENEO_AUTH_CLIENT_SECRET`` to the client secret.
See :ref:`authenticate_oidc_automatic` for more details.
:param provider_id: provider id to use
:param client_id: client id to use
:param client_secret: client secret to use
:param max_poll_time: maximum time in seconds to keep polling for successful authentication.
.. versionadded:: 0.6.0
.. versionchanged:: 0.17.0 Add :py:obj:`max_poll_time` argument
.. versionchanged:: 0.18.0 Add support for client credentials flow.
"""
# TODO: unify `os.environ.get` with `get_config_option`?
# TODO also support OPENEO_AUTH_CLIENT_ID, ... env vars for refresh token and device code auth?
auth_method = os.environ.get("OPENEO_AUTH_METHOD")
if auth_method == "client_credentials":
_log.debug("authenticate_oidc: going for 'client_credentials' authentication")
return self.authenticate_oidc_client_credentials(
client_id=client_id, client_secret=client_secret, provider_id=provider_id
)
elif auth_method:
raise ValueError(f"Unhandled auth method {auth_method}")
_g = DefaultOidcClientGrant # alias for compactness
provider_id, client_info = self._get_oidc_provider_and_client_info(
provider_id=provider_id, client_id=client_id, client_secret=client_secret,
default_client_grant_check=lambda grants: (
_g.REFRESH_TOKEN in grants and (_g.DEVICE_CODE in grants or _g.DEVICE_CODE_PKCE in grants)
)
)
# Try refresh token first.
refresh_token = self._get_refresh_token_store().get_refresh_token(
issuer=client_info.provider.issuer,
client_id=client_info.client_id
)
if refresh_token:
try:
_log.info("Found refresh token: trying refresh token based authentication.")
authenticator = OidcRefreshTokenAuthenticator(client_info=client_info, refresh_token=refresh_token)
con = self._authenticate_oidc(
authenticator,
provider_id=provider_id,
store_refresh_token=store_refresh_token,
fallback_refresh_token_to_store=refresh_token,
)
# TODO: pluggable/jupyter-aware display function?
print("Authenticated using refresh token.")
return con
except OidcException as e:
_log.info("Refresh token based authentication failed: {e}.".format(e=e))
# Fall back on device code flow
# TODO: make it possible to do other fallback flows too?
_log.info("Trying device code flow.")
authenticator = OidcDeviceAuthenticator(
client_info=client_info, use_pkce=use_pkce, display=display, max_poll_time=max_poll_time
)
con = self._authenticate_oidc(
authenticator,
provider_id=provider_id,
store_refresh_token=store_refresh_token,
)
print("Authenticated using device code flow.")
return con
def request(
self,
method: str,
path: str,
headers: Optional[dict] = None,
auth: Optional[AuthBase] = None,
check_error: bool = True,
expected_status: Optional[Union[int, Iterable[int]]] = None,
**kwargs,
):
# Do request, but with retry when access token has expired and refresh token is available.
def _request():
return super(Connection, self).request(
method=method, path=path, headers=headers, auth=auth,
check_error=check_error, expected_status=expected_status, **kwargs,
)
try:
# Initial request attempt
return _request()
except OpenEoApiError as api_exc:
if api_exc.http_status_code == 403 and api_exc.code == "TokenInvalid":
# Auth token expired: can we refresh?
if isinstance(self.auth, OidcBearerAuth) and self._oidc_auth_renewer:
msg = f"OIDC access token expired ({api_exc.http_status_code} {api_exc.code})."
try:
self._authenticate_oidc(
authenticator=self._oidc_auth_renewer,
provider_id=self._oidc_auth_renewer.provider_info.id,
store_refresh_token=False,
oidc_auth_renewer=self._oidc_auth_renewer,
)
_log.info(f"{msg} Obtained new access token (grant {self._oidc_auth_renewer.grant_type!r}).")
except OpenEoClientException as auth_exc:
_log.error(
f"{msg} Failed to obtain new access token (grant {self._oidc_auth_renewer.grant_type!r}): {auth_exc!r}."
)
else:
# Retry request.
return _request()
raise
def describe_account(self) -> dict:
"""
Describes the currently authenticated user account.
"""
return self.get('/me', expected_status=200).json()
@deprecated("use :py:meth:`list_jobs` instead", version="0.4.10")
def user_jobs(self) -> List[dict]:
return self.list_jobs()
def list_collections(self) -> List[dict]:
"""
List basic metadata of all collections provided by the back-end.
.. caution::
Only the basic collection metadata will be returned.
To obtain full metadata of a particular collection,
it is recommended to use :py:meth:`~openeo.rest.connection.Connection.describe_collection` instead.
:return: list of dictionaries with basic collection metadata.
"""
# TODO: add caching #383
data = self.get('/collections', expected_status=200).json()["collections"]
return VisualList("collections", data=data)
def list_collection_ids(self) -> List[str]:
"""
List all collection ids provided by the back-end.
.. seealso::
:py:meth:`~openeo.rest.connection.Connection.describe_collection`
to get the metadata of a particular collection.
:return: list of collection ids
"""
return [collection['id'] for collection in self.list_collections() if 'id' in collection]
def capabilities(self) -> RESTCapabilities:
"""
Loads all available capabilities.
"""
return self._capabilities_cache.get(
"capabilities",
load=lambda: RESTCapabilities(data=self.get('/', expected_status=200).json(), url=self._orig_url)
)
def list_input_formats(self) -> dict:
return self.list_file_formats().get("input", {})
def list_output_formats(self) -> dict:
return self.list_file_formats().get("output", {})
list_file_types = legacy_alias(
list_output_formats, "list_file_types", since="0.4.6"
)
def list_file_formats(self) -> dict:
"""
Get available input and output formats
"""
formats = self._capabilities_cache.get(
key="file_formats",
load=lambda: self.get('/file_formats', expected_status=200).json()
)
return VisualDict("file-formats", data=formats)
def list_service_types(self) -> dict:
"""
Loads all available service types.
:return: data_dict: Dict All available service types
"""
types = self._capabilities_cache.get(
key="service_types",
load=lambda: self.get('/service_types', expected_status=200).json()
)
return VisualDict("service-types", data=types)
def list_udf_runtimes(self) -> dict:
"""
Loads all available UDF runtimes.
:return: data_dict: Dict All available UDF runtimes
"""
runtimes = self._capabilities_cache.get(
key="udf_runtimes",
load=lambda: self.get('/udf_runtimes', expected_status=200).json()
)
return VisualDict("udf-runtimes", data=runtimes)
def list_services(self) -> dict:
"""
Loads all available services of the authenticated user.
:return: data_dict: Dict All available services
"""
# TODO return parsed service objects
services = self.get('/services', expected_status=200).json()["services"]
return VisualList("data-table", data=services, parameters={'columns': 'services'})
def describe_collection(self, collection_id: str) -> dict:
"""
Get full collection metadata for given collection id.
.. seealso::
:py:meth:`~openeo.rest.connection.Connection.list_collection_ids`
to list all collection ids provided by the back-end.
:param collection_id: collection id
:return: collection metadata.
"""
# TODO: duplication with `Connection.collection_metadata`: deprecate one or the other?
# TODO: add caching #383
data = self.get(f"/collections/{collection_id}", expected_status=200).json()
return VisualDict("collection", data=data)
def collection_items(
self,
name,
spatial_extent: Optional[List[float]] = None,
temporal_extent: Optional[List[Union[str, datetime.datetime]]] = None,
limit: Optional[int] = None,
) -> Iterator[dict]:
"""
Loads items for a specific image collection.
May not be available for all collections.
This is an experimental API and is subject to change.
:param name: String Id of the collection
:param spatial_extent: Limits the items to the given bounding box in WGS84:
1. Lower left corner, coordinate axis 1
2. Lower left corner, coordinate axis 2
3. Upper right corner, coordinate axis 1
4. Upper right corner, coordinate axis 2
:param temporal_extent: Limits the items to the specified temporal interval.
:param limit: The amount of items per request/page. If None, the back-end decides.
The interval has to be specified as an array with exactly two elements (start, end).
Also supports open intervals by setting one of the boundaries to None, but never both.
:return: data_list: List A list of items
"""
url = '/collections/{}/items'.format(name)
params = {}
if spatial_extent:
params["bbox"] = ",".join(str(c) for c in spatial_extent)
if temporal_extent:
params["datetime"] = "/".join(".." if t is None else rfc3339.normalize(t) for t in temporal_extent)
if limit is not None and limit > 0:
params['limit'] = limit
return paginate(self, url, params, lambda response, page: VisualDict("items", data = response, parameters = {'show-map': True, 'heading': 'Page {} - Items'.format(page)}))
def collection_metadata(self, name) -> CollectionMetadata:
# TODO: duplication with `Connection.describe_collection`: deprecate one or the other?
return CollectionMetadata(metadata=self.describe_collection(name))
def list_processes(self, namespace: Optional[str] = None) -> List[dict]:
# TODO: Maybe format the result dictionary so that the process_id is the key of the dictionary.
"""
Loads all available processes of the back end.
:param namespace: The namespace for which to list processes.
:return: processes_dict: Dict All available processes of the back end.
"""
if namespace is None:
processes = self._capabilities_cache.get(
key=("processes", "backend"),
load=lambda: self.get('/processes', expected_status=200).json()["processes"]
)
else:
processes = self.get('/processes/' + namespace, expected_status=200).json()["processes"]
return VisualList("processes", data=processes, parameters={'show-graph': True, 'provide-download': False})
def describe_process(self, id: str, namespace: Optional[str] = None) -> dict:
"""
Returns a single process from the back end.
:param id: The id of the process.
:param namespace: The namespace of the process.
:return: The process definition.
"""
processes = self.list_processes(namespace)
for process in processes:
if process["id"] == id:
return VisualDict("process", data=process, parameters={'show-graph': True, 'provide-download': False})
raise OpenEoClientException("Process does not exist.")
def list_jobs(self) -> List[dict]:
"""
Lists all jobs of the authenticated user.
:return: job_list: Dict of all jobs of the user.
"""
# TODO: Parse the result so that there get Job classes returned?
resp = self.get('/jobs', expected_status=200).json()
if resp.get("federation:missing"):
_log.warning("Partial user job listing due to missing federation components: {c}".format(
c=",".join(resp["federation:missing"])
))
jobs = resp["jobs"]
return VisualList("data-table", data=jobs, parameters={'columns': 'jobs'})
def assert_user_defined_process_support(self):
"""
Capabilities document based verification that back-end supports user-defined processes.
.. versionadded:: 0.23.0
"""
if not self.capabilities().supports_endpoint("/process_graphs"):
raise CapabilitiesException("Backend does not support user-defined processes.")
def save_user_defined_process(
self, user_defined_process_id: str,
process_graph: Union[dict, ProcessBuilderBase],
parameters: List[Union[dict, Parameter]] = None,
public: bool = False,
summary: Optional[str] = None,
description: Optional[str] = None,