|
| 1 | +# coding: utf-8 |
| 2 | + |
| 3 | +# Copyright 2021 IBM All Rights Reserved. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +import logging |
| 18 | +from typing import Dict, Optional |
| 19 | + |
| 20 | +from .iam_request_based_token_manager import IAMRequestBasedTokenManager |
| 21 | + |
| 22 | + |
| 23 | +class ContainerTokenManager(IAMRequestBasedTokenManager): |
| 24 | + """The ContainerTokenManager takes a compute resource token and performs the necessary interactions with |
| 25 | + the IAM token service to obtain and store a suitable bearer token. Additionally, the ContainerTokenManager |
| 26 | + will retrieve bearer tokens via basic auth using a supplied client_id and client_secret pair. |
| 27 | +
|
| 28 | + If the current stored bearer token has expired a new bearer token will be retrieved. |
| 29 | +
|
| 30 | + Attributes: |
| 31 | + container_token_filename(str): The name of the file containing the injected CR token value |
| 32 | + (applies to IKS-managed compute resources). |
| 33 | + iam_profile_name (str): The name of the linked trusted IAM profile to be used when obtaining the |
| 34 | + IAM access token (a CR token might map to multiple IAM profiles). |
| 35 | + One of IAMProfileName or IAMProfileID must be specified. |
| 36 | + iam_profile_id (str): The id of the linked trusted IAM profile to be used when obtaining the IAM access token |
| 37 | + (a CR token might map to multiple IAM profiles). One of IAMProfileName or IAMProfileID must be specified. |
| 38 | + url (str): The IAM endpoint to token requests. |
| 39 | + client_id (str): The client_id and client_secret fields are used to form |
| 40 | + a "basic auth" Authorization header for interactions with the IAM token server. |
| 41 | + client_secret (str): The client_id and client_secret fields are used to form |
| 42 | + a "basic auth" Authorization header for interactions with the IAM token server. |
| 43 | + headers (dict): Default headers to be sent with every IAM token request. |
| 44 | + proxies (dict): Proxies to use for communicating with IAM. |
| 45 | + proxies.http (str): The proxy endpoint to use for HTTP requests. |
| 46 | + proxies.https (str): The proxy endpoint to use for HTTPS requests. |
| 47 | + http_config (dict): A dictionary containing values that control the timeout, proxies, and etc of HTTP requests. |
| 48 | + scope (str): The "scope" to use when fetching the bearer token from the IAM token server. |
| 49 | + This can be used to obtain an access token with a specific scope. |
| 50 | +
|
| 51 | + Keyword Args: |
| 52 | + container_token_filename: The name of the file containing the injected CR token value |
| 53 | + (applies to IKS-managed compute resources). Defaults to "/var/run/secrets/tokens/vault-token". |
| 54 | + iam_profile_name: The name of the linked trusted IAM profile to be used when obtaining the IAM access token |
| 55 | + (a CR token might map to multiple IAM profiles). One of IAMProfileName or IAMProfileID must be specified. |
| 56 | + sDefaults to None. |
| 57 | + iam_profile_id: The id of the linked trusted IAM profile to be used when obtaining the IAM access token |
| 58 | + (a CR token might map to multiple IAM profiles). One of IAMProfileName or IAMProfileID must be specified. |
| 59 | + Defaults to None. |
| 60 | + url: The IAM endpoint to token requests. Defaults to None. |
| 61 | + client_id: The client_id and client_secret fields are used to form |
| 62 | + a "basic auth" Authorization header for interactions with the IAM token server. |
| 63 | + Defaults to None. |
| 64 | + client_secret: The client_id and client_secret fields are used to form |
| 65 | + a "basic auth" Authorization header for interactions with the IAM token server. |
| 66 | + Defaults to None. |
| 67 | + disable_ssl_verification: A flag that indicates whether verification of |
| 68 | + the server's SSL certificate should be disabled or not. Defaults to False. |
| 69 | + headers: Default headers to be sent with every IAM token request. Defaults to None. |
| 70 | + proxies: Proxies to use for communicating with IAM. Defaults to None. |
| 71 | + proxies.http: The proxy endpoint to use for HTTP requests. |
| 72 | + proxies.https: The proxy endpoint to use for HTTPS requests. |
| 73 | + scope: The "scope" to use when fetching the bearer token from the IAM token server. |
| 74 | + This can be used to obtain an access token with a specific scope. |
| 75 | + """ |
| 76 | + DEFAULT_CR_TOKEN_FILENAME = '/var/run/secrets/tokens/vault-token' |
| 77 | + |
| 78 | + def __init__(self, |
| 79 | + cr_token_filename: Optional[str] = None, |
| 80 | + iam_profile_name: Optional[str] = None, |
| 81 | + iam_profile_id: Optional[str] = None, |
| 82 | + url: Optional[str] = None, |
| 83 | + client_id: Optional[str] = None, |
| 84 | + client_secret: Optional[str] = None, |
| 85 | + disable_ssl_verification: bool = False, |
| 86 | + scope: Optional[str] = None, |
| 87 | + proxies: Optional[Dict[str, str]] = None, |
| 88 | + headers: Optional[Dict[str, str]] = None) -> None: |
| 89 | + super().__init__( |
| 90 | + url=url, client_id=client_id, client_secret=client_secret, |
| 91 | + disable_ssl_verification=disable_ssl_verification, headers=headers, proxies=proxies, scope=scope) |
| 92 | + |
| 93 | + self.cr_token_filename = cr_token_filename |
| 94 | + self.iam_profile_name = iam_profile_name |
| 95 | + self.iam_profile_id = iam_profile_id |
| 96 | + |
| 97 | + self.request_payload['grant_type'] = 'urn:ibm:params:oauth:grant-type:cr-token' |
| 98 | + |
| 99 | + def retrieve_cr_token(self) -> str: |
| 100 | + """Retrieves the CR token for the current compute resource by reading it from the local file system. |
| 101 | +
|
| 102 | + Raises: |
| 103 | + Exception: Cannot retrieve the compute resource token from. |
| 104 | +
|
| 105 | + Returns: |
| 106 | + A string which contains the compute resource token. |
| 107 | + """ |
| 108 | + cr_token_filename = self.cr_token_filename if self.cr_token_filename else self.DEFAULT_CR_TOKEN_FILENAME |
| 109 | + |
| 110 | + logging.debug('Attempting to read CR token from file: %s', cr_token_filename) |
| 111 | + |
| 112 | + try: |
| 113 | + with open(cr_token_filename, 'r') as file: |
| 114 | + cr_token = file.read() |
| 115 | + return cr_token |
| 116 | + # pylint: disable=broad-except |
| 117 | + except Exception as ex: |
| 118 | + raise Exception('Unable to retrieve the CR token value from file {}: {}'.format(cr_token_filename, ex)) |
| 119 | + |
| 120 | + def request_token(self) -> dict: |
| 121 | + """Retrieves a CR token value from the current compute resource, |
| 122 | + then uses that to obtain a new IAM access token from the IAM token server. |
| 123 | +
|
| 124 | + Returns: |
| 125 | + A dictionary containing the bearer token to be subsequently used service requests. |
| 126 | + """ |
| 127 | + # Retrieve the CR token for this compute resource. |
| 128 | + cr_token = self.retrieve_cr_token() |
| 129 | + |
| 130 | + # Set the request payload. |
| 131 | + self.request_payload['cr_token'] = cr_token |
| 132 | + |
| 133 | + if self.iam_profile_id: |
| 134 | + self.request_payload['profile_id'] = self.iam_profile_id |
| 135 | + if self.iam_profile_name: |
| 136 | + self.request_payload['profile_name'] = self.iam_profile_name |
| 137 | + |
| 138 | + return super().request_token() |
| 139 | + |
| 140 | + def set_cr_token_filename(self, cr_token_filename: str) -> None: |
| 141 | + """Set the location of the compute resource token on the local filesystem. |
| 142 | +
|
| 143 | + Args: |
| 144 | + cr_token_filename: path to the compute resource token |
| 145 | + """ |
| 146 | + self.cr_token_filename = cr_token_filename |
| 147 | + |
| 148 | + def set_iam_profile_name(self, iam_profile_name: str) -> None: |
| 149 | + """Set the name of the IAM profile. |
| 150 | +
|
| 151 | + Args: |
| 152 | + iam_profile_name: name of the linked trusted IAM profile to be used when obtaining the IAM access token |
| 153 | + """ |
| 154 | + self.iam_profile_name = iam_profile_name |
| 155 | + |
| 156 | + def set_iam_profile_id(self, iam_profile_id: str) -> None: |
| 157 | + """Set the id of the IAM profile. |
| 158 | +
|
| 159 | + Args: |
| 160 | + iam_profile_id: id of the linked trusted IAM profile to be used when obtaining the IAM access token |
| 161 | + """ |
| 162 | + self.iam_profile_id = iam_profile_id |
0 commit comments