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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
# MinIO Python Library for Amazon S3 Compatible Cloud Storage,
# (C) 2020 MinIO, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Credential providers."""

import configparser
import ipaddress
import json
import os
import socket
import sys
import time
from abc import ABCMeta, abstractmethod
from datetime import datetime, timedelta
from urllib.parse import urlencode, urlsplit
from xml.etree import ElementTree

import urllib3

from minio.helpers import sha256_hash, strptime_rfc3339
from minio.signer import AMZ_DATE_FORMAT, sign_v4_sts

from .credentials import Credentials

_MIN_DURATION_SECONDS = timedelta(minutes=15).total_seconds()
_MAX_DURATION_SECONDS = timedelta(days=7).total_seconds()
_DEFAULT_DURATION_SECONDS = timedelta(hours=1).total_seconds()
_XML_NS = {
    "s3": "http://s3.amazonaws.com/doc/2006-03-01/",
    "sts": "https://sts.amazonaws.com/doc/2011-06-15/",
}


def _parse_credentials(data, result_path):
    """Parse data containing credentials XML."""

    root = ElementTree.fromstring(data)
    credentials = root.find("sts:" + result_path, _XML_NS).find(
        "sts:Credentials", _XML_NS)

    access_key = credentials.find("sts:AccessKeyId", _XML_NS).text
    secret_key = credentials.find("sts:SecretAccessKey", _XML_NS).text
    session_token = credentials.find("sts:SessionToken", _XML_NS).text
    expiration = strptime_rfc3339(
        credentials.find("sts:Expiration", _XML_NS).text,
    )

    return Credentials(access_key, secret_key, session_token, expiration)


def _urlopen(http_client, method, url, body=None, headers=None):
    """Wrapper of urlopen() handles HTTP status code."""
    res = http_client.urlopen(method, url, body=body, headers=headers)
    if res.status not in [200, 204, 206]:
        raise ValueError(
            "{0} failed with HTTP status code {1}".format(url, res.status),
        )
    return res


class Provider:  # pylint: disable=too-few-public-methods
    """Credential retriever."""
    __metaclass__ = ABCMeta

    @abstractmethod
    def retrieve(self):
        """Retrieve credentials and its expiry if available."""


class AssumeRoleProvider(Provider):
    """Assume-role credential provider."""

    def __init__(
            self, sts_endpoint, access_key, secret_key, duration_seconds=0,
            policy=None, region=None, role_arn=None, role_session_name=None,
            external_id=None, http_client=None,
    ):
        self._sts_endpoint = sts_endpoint
        self._access_key = access_key
        self._secret_key = secret_key
        self._region = region or ""
        self._http_client = http_client or urllib3.PoolManager(
            retries=urllib3.Retry(
                total=5,
                backoff_factor=0.2,
                status_forcelist=[500, 502, 503, 504],
            ),
        )

        query_params = {
            "Action": "AssumeRole",
            "Version": "2011-06-15",
            "DurationSeconds": str(
                duration_seconds
                if duration_seconds > _DEFAULT_DURATION_SECONDS
                else _DEFAULT_DURATION_SECONDS
            ),
        }

        if role_arn:
            query_params["RoleArn"] = role_arn
        if role_session_name:
            query_params["RoleSessionName"] = role_session_name
        if policy:
            query_params["Policy"] = policy
        if external_id:
            query_params["ExternalId"] = external_id

        self._body = urlencode(query_params)
        self._content_sha256 = sha256_hash(self._body)
        url = urlsplit(sts_endpoint)
        self._host = url.netloc
        if (
                (url.scheme == "http" and url.port == 80) or
                (url.scheme == "https" and url.port == 443)
        ):
            self._host = url.hostname
        self._credentials = None

    def retrieve(self):
        """Retrieve credentials."""
        if self._credentials and not self._credentials.is_expired():
            return self._credentials

        utcnow = datetime.utcnow()
        headers = sign_v4_sts(
            "POST",
            urlsplit(self._sts_endpoint),
            self._region,
            {
                "Content-Type": "application/x-www-form-urlencoded",
                "Host": self._host,
                "X-Amz-Date": utcnow.strftime(AMZ_DATE_FORMAT),
            },
            Credentials(self._access_key, self._secret_key),
            self._content_sha256,
            utcnow,
        )

        res = _urlopen(
            self._http_client,
            "POST",
            self._sts_endpoint,
            body=self._body,
            headers=headers,
        )

        self._credentials = _parse_credentials(
            res.data.decode(), "AssumeRoleResult",
        )

        return self._credentials


class ChainedProvider(Provider):
    """Chained credential provider."""

    def __init__(self, providers):
        self._providers = providers
        self._provider = None
        self._credentials = None

    def retrieve(self):
        """Retrieve credentials from one of available provider."""
        if self._credentials and not self._credentials.is_expired():
            return self._credentials

        if self._provider:
            try:
                self._credentials = self._provider.retrieve()
                return self._credentials
            except ValueError:
                # Ignore this error and iterate other providers.
                pass

        for provider in self._providers:
            try:
                self._credentials = provider.retrieve()
                self._provider = provider
                return self._credentials
            except ValueError:
                # Ignore this error and iterate other providers.
                pass

        return ValueError("All providers fail to fetch credentials")


class EnvAWSProvider(Provider):
    """Credential provider from AWS environment variables."""

    def __init__(self):
        access_key = (
            os.environ.get("AWS_ACCESS_KEY_ID") or
            os.environ.get("AWS_ACCESS_KEY")
        )
        secret_key = (
            os.environ.get("AWS_SECRET_ACCESS_KEY") or
            os.environ.get("AWS_SECRET_KEY")
        )
        self._credentials = Credentials(
            access_key,
            secret_key,
            session_token=os.environ.get("AWS_SESSION_TOKEN"),
        )

    def retrieve(self):
        """Retrieve credentials."""
        return self._credentials


class EnvMinioProvider(Provider):
    """Credential provider from MinIO environment variables."""

    def __init__(self):
        self._credentials = Credentials(
            os.environ.get("MINIO_ACCESS_KEY"),
            os.environ.get("MINIO_SECRET_KEY"),
        )

    def retrieve(self):
        """Retrieve credentials."""
        return self._credentials


class AWSConfigProvider(Provider):
    """Credential provider from AWS credential file."""

    def __init__(self, filename=None, profile=None):
        self._filename = (
            filename or
            os.environ.get("AWS_SHARED_CREDENTIALS_FILE") or
            os.path.join(os.environ.get("HOME"), ".aws", "credentials")
        )
        self._profile = profile or os.environ.get("AWS_PROFILE") or "default"

    def retrieve(self):
        """Retrieve credentials from AWS configuration file."""
        parser = configparser.ConfigParser()
        parser.read(self._filename)
        access_key = parser.get(
            self._profile,
            "aws_access_key_id",
            fallback=None,
        )
        secret_key = parser.get(
            self._profile,
            "aws_secret_access_key",
            fallback=None,
        )
        session_token = parser.get(
            self._profile,
            "aws_session_token",
            fallback=None,
        )

        if not access_key:
            raise ValueError(
                (
                    "access key does not exist in profile "
                    "{0} in AWS credential file {1}"
                ).format(
                    self._profile, self._filename,
                ),
            )

        if not secret_key:
            raise ValueError(
                (
                    "secret key does not exist in profile "
                    "{0} in AWS credential file {1}"
                ).format(
                    self._profile, self._filename,
                ),
            )

        return Credentials(
            access_key,
            secret_key,
            session_token=session_token,
        )


class MinioClientConfigProvider(Provider):
    """Credential provider from MinIO Client configuration file."""

    def __init__(self, filename=None, alias=None):
        self._filename = (
            filename or
            os.path.join(
                os.environ.get("HOME"),
                "mc" if sys.platform == "win32" else ".mc",
                "config.json",
            )
        )
        self._alias = alias or os.environ.get("MINIO_ALIAS") or "s3"

    def retrieve(self):
        """Retrieve credential value from MinIO client configuration file."""
        try:
            with open(self._filename) as conf_file:
                config = json.load(conf_file)
            if not config.get("hosts"):
                raise ValueError(
                    "invalid configuration in file {0}".format(
                        self._filename,
                    ),
                )
            creds = config.get("hosts").get(self._alias)
            if not creds:
                raise ValueError(
                    (
                        "alias {0} not found in MinIO client"
                        "configuration file {1}"
                    ).format(
                        self._alias, self._filename,
                    ),
                )
            return Credentials(creds.get("accessKey"), creds.get("secretKey"))
        except (IOError, OSError) as exc:
            raise ValueError(
                "error in reading file {0}".format(self._filename),
            ) from exc


def _check_loopback_host(url):
    """Check whether host in url points only to localhost."""
    host = urllib3.util.parse_url(url).host
    try:
        addrs = set(info[4][0] for info in socket.getaddrinfo(host, None))
        for addr in addrs:
            if not ipaddress.ip_address(addr).is_loopback:
                raise ValueError(host + " is not loopback only host")
    except socket.gaierror as exc:
        raise ValueError("Host " + host + " is not loopback address") from exc


def _get_jwt_token(token_file):
    """Read and return content of token file. """
    try:
        with open(token_file) as file:
            return {"access_token": file.read(), "expires_in": "0"}
    except (IOError, OSError) as exc:
        raise ValueError(
            "error in reading file {0}".format(token_file),
        ) from exc


class IamAwsProvider(Provider):
    """Credential provider using IAM roles for Amazon EC2/ECS."""

    def __init__(self, custom_endpoint=None, http_client=None):
        self._custom_endpoint = custom_endpoint
        self._http_client = http_client or urllib3.PoolManager(
            retries=urllib3.Retry(
                total=5,
                backoff_factor=0.2,
                status_forcelist=[500, 502, 503, 504],
            ),
        )
        self._token_file = os.environ.get("AWS_WEB_IDENTITY_TOKEN_FILE")
        self._aws_region = os.environ.get("AWS_REGION")
        self._role_arn = os.environ.get("AWS_ROLE_ARN")
        self._role_session_name = os.environ.get("AWS_ROLE_SESSION_NAME")
        self._relative_uri = os.environ.get(
            "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
        )
        if self._relative_uri and not self._relative_uri.startswith("/"):
            self._relative_uri = "/" + self._relative_uri
        self._full_uri = os.environ.get("AWS_CONTAINER_CREDENTIALS_FULL_URI")
        self._credentials = None

    def fetch(self, url):
        """Fetch credentials from EC2/ECS. """

        res = _urlopen(self._http_client, "GET", url)
        data = json.loads(res.data)
        if data["Code"] != "Success":
            raise ValueError(
                "{0} failed with code {1} message {2}".format(
                    url, data["Code"], data["Message"],
                ),
            )
        data["Expiration"] = strptime_rfc3339(data["Expiration"])

        return Credentials(
            data["AccessKeyId"],
            data["SecretAccessKey"],
            data["Token"],
            data["Expiration"],
        )

    def retrieve(self):
        """Retrieve credentials from WebIdentity/EC2/ECS."""

        if self._credentials and not self._credentials.is_expired():
            return self._credentials

        url = self._custom_endpoint
        if self._token_file:
            if not url:
                url = "https://sts.{0}{1}amazonaws.com".format(
                    self._aws_region, "." if self._aws_region else "",
                )

            provider = WebIdentityProvider(
                lambda: _get_jwt_token(self._token_file),
                url,
                role_arn=self._role_arn,
                role_session_name=self._role_session_name,
                http_client=self._http_client,
            )
            self._credentials = provider.retrieve()
            return self._credentials

        if self._relative_uri:
            if not url:
                url = "http://169.254.170.2" + self._relative_uri
        elif self._full_uri:
            if not url:
                url = self._full_uri
            _check_loopback_host(url)
        else:
            if not url:
                url = (
                    "http://169.254.169.254" +
                    "/latest/meta-data/iam/security-credentials/"
                )

            res = _urlopen(self._http_client, "GET", url)
            role_names = res.data.decode("utf-8").split("\n")
            if not role_names:
                raise ValueError(
                    "no IAM roles attached to EC2 service {0}".format(url),
                )
            url += "/" + role_names[0].strip("\r")

        self._credentials = self.fetch(url)
        return self._credentials


class LdapIdentityProvider(Provider):
    """Credential provider using AssumeRoleWithLDAPIdentity API."""

    def __init__(
            self, sts_endpoint, ldap_username, ldap_password, http_client=None,
    ):
        self._sts_endpoint = sts_endpoint + "?" + urlencode(
            {
                "Action": "AssumeRoleWithLDAPIdentity",
                "Version": "2011-06-15",
                "LDAPUsername": ldap_username,
                "LDAPPassword": ldap_password,
            },
        )
        self._http_client = http_client or urllib3.PoolManager(
            retries=urllib3.Retry(
                total=5,
                backoff_factor=0.2,
                status_forcelist=[500, 502, 503, 504],
            ),
        )
        self._credentials = None

    def retrieve(self):
        """Retrieve credentials."""

        if self._credentials and not self._credentials.is_expired():
            return self._credentials

        res = _urlopen(
            self._http_client,
            "POST",
            self._sts_endpoint,
        )

        self._credentials = _parse_credentials(
            res.data.decode(), "AssumeRoleWithLDAPIdentityResult",
        )

        return self._credentials


class StaticProvider(Provider):
    """Fixed credential provider."""

    def __init__(self, access_key, secret_key, session_token=None):
        self._credentials = Credentials(access_key, secret_key, session_token)

    def retrieve(self):
        """Return passed credentials."""
        return self._credentials


class WebIdentityClientGrantsProvider(Provider):
    """Base class for WebIdentity and ClientGrants credentials provider."""
    __metaclass__ = ABCMeta

    def __init__(
            self, jwt_provider_func, sts_endpoint,
            duration_seconds=0, policy=None, role_arn=None,
            role_session_name=None, http_client=None,
    ):
        self._jwt_provider_func = jwt_provider_func
        self._sts_endpoint = sts_endpoint
        self._duration_seconds = duration_seconds
        self._policy = policy
        self._role_arn = role_arn
        self._role_session_name = role_session_name
        self._http_client = http_client or urllib3.PoolManager(
            retries=urllib3.Retry(
                total=5,
                backoff_factor=0.2,
                status_forcelist=[500, 502, 503, 504],
            ),
        )
        self._credentials = None

    @abstractmethod
    def _is_web_identity(self):
        """Check if derived class deal with WebIdentity."""

    def _get_duration_seconds(self, expiry):
        """Get DurationSeconds optimal value."""

        if self._duration_seconds:
            expiry = self._duration_seconds

        if expiry > _MAX_DURATION_SECONDS:
            return _MAX_DURATION_SECONDS

        if expiry <= 0:
            return expiry

        return (
            _MIN_DURATION_SECONDS if expiry < _MIN_DURATION_SECONDS else expiry
        )

    def retrieve(self):
        """Retrieve credentials."""

        if self._credentials and not self._credentials.is_expired():
            return self._credentials

        jwt = self._jwt_provider_func()

        query_params = {"Version": "2011-06-15"}
        duration_seconds = self._get_duration_seconds(
            int(jwt.get("expires_in", "0")),
        )
        if duration_seconds:
            query_params["DurationSeconds"] = str(duration_seconds)
        if self._policy:
            query_params["Policy"] = self._policy

        if self._is_web_identity():
            query_params["Action"] = "AssumeRoleWithWebIdentity"
            query_params["WebIdentityToken"] = jwt.get("access_token")
            if self._role_arn:
                query_params["RoleArn"] = self._role_arn
                query_params["RoleSessionName"] = (
                    self._role_session_name
                    if self._role_session_name
                    else str(time.time()).replace(".", "")
                )
        else:
            query_params["Action"] = "AssumeRoleWithClientGrants"
            query_params["Token"] = jwt.get("access_token")

        url = self._sts_endpoint + "?" + urlencode(query_params)
        res = _urlopen(self._http_client, "POST", url)

        self._credentials = _parse_credentials(
            res.data.decode(),
            (
                "AssumeRoleWithWebIdentityResult"
                if self._is_web_identity()
                else "AssumeRoleWithClientGrantsResult"
            ),
        )

        return self._credentials


class ClientGrantsProvider(WebIdentityClientGrantsProvider):
    """Credential provider using AssumeRoleWithClientGrants API."""

    def __init__(
            self, jwt_provider_func, sts_endpoint,
            duration_seconds=0, policy=None, http_client=None,
    ):
        super().__init__(
            jwt_provider_func, sts_endpoint, duration_seconds, policy,
            http_client=http_client,
        )

    def _is_web_identity(self):
        return False


class WebIdentityProvider(WebIdentityClientGrantsProvider):
    """Credential provider using AssumeRoleWithWebIdentity API."""

    def _is_web_identity(self):
        return True