|
| 1 | +import jwt |
| 2 | +import concurrent.futures |
| 3 | +import grpc |
| 4 | +import time |
| 5 | +import http.server |
| 6 | +import urllib |
| 7 | +import threading |
| 8 | +import json |
| 9 | + |
| 10 | +import ydb.iam |
| 11 | + |
| 12 | +from yandex.cloud.iam.v1 import iam_token_service_pb2_grpc |
| 13 | +from yandex.cloud.iam.v1 import iam_token_service_pb2 |
| 14 | + |
| 15 | +SERVICE_ACCOUNT_ID = "sa_id" |
| 16 | +ACCESS_KEY_ID = "key_id" |
| 17 | +PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC75/JS3rMcLJxv\nFgpOzF5+2gH+Yig3RE2MTl9uwC0BZKAv6foYr7xywQyWIK+W1cBhz8R4LfFmZo2j\nM0aCvdRmNBdW0EDSTnHLxCsFhoQWLVq+bI5f5jzkcoiioUtaEpADPqwgVULVtN/n\nnPJiZ6/dU30C3jmR6+LUgEntUtWt3eq3xQIn5lG3zC1klBY/HxtfH5Hu8xBvwRQT\nJnh3UpPLj8XwSmriDgdrhR7o6umWyVuGrMKlLHmeivlfzjYtfzO1MOIMG8t2/zxG\nR+xb4Vwks73sH1KruH/0/JMXU97npwpe+Um+uXhpldPygGErEia7abyZB2gMpXqr\nWYKMo02NAgMBAAECggEAO0BpC5OYw/4XN/optu4/r91bupTGHKNHlsIR2rDzoBhU\nYLd1evpTQJY6O07EP5pYZx9mUwUdtU4KRJeDGO/1/WJYp7HUdtxwirHpZP0lQn77\nuccuX/QQaHLrPekBgz4ONk+5ZBqukAfQgM7fKYOLk41jgpeDbM2Ggb6QUSsJISEp\nzrwpI/nNT/wn+Hvx4DxrzWU6wF+P8kl77UwPYlTA7GsT+T7eKGVH8xsxmK8pt6lg\nsvlBA5XosWBWUCGLgcBkAY5e4ZWbkdd183o+oMo78id6C+PQPE66PLDtHWfpRRmN\nm6XC03x6NVhnfvfozoWnmS4+e4qj4F/emCHvn0G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MliCvltXAYc/EeC3xZmaNozNGgr3U\nZjQXVtBA0k5xy8QrBYaEFi1avmyOX+Y85HKIoqFLWhKQAz6sIFVC1bTf55zyYmev\n3VN9At45kevi1IBJ7VLVrd3qt8UCJ+ZRt8wtZJQWPx8bXx+R7vMQb8EUEyZ4d1KT\ny4/F8Epq4g4Ha4Ue6OrplslbhqzCpSx5nor5X842LX8ztTDiDBvLdv88RkfsW+Fc\nJLO97B9Sq7h/9PyTF1Pe56cKXvlJvrl4aZXT8oBhKxImu2m8mQdoDKV6q1mCjKNN\njQIDAQAB\n-----END PUBLIC KEY-----\n" # noqa: E501 |
| 19 | + |
| 20 | + |
| 21 | +def test_metadata_credentials(): |
| 22 | + credentials = ydb.iam.MetadataUrlCredentials() |
| 23 | + raised = False |
| 24 | + try: |
| 25 | + credentials.auth_metadata() |
| 26 | + except Exception: |
| 27 | + raised = True |
| 28 | + |
| 29 | + assert raised |
| 30 | + |
| 31 | + |
| 32 | +class IamTokenServiceForTest(iam_token_service_pb2_grpc.IamTokenServiceServicer): |
| 33 | + def Create(self, request, context): |
| 34 | + print("IAM token service request: {}".format(request)) |
| 35 | + # Validate jwt: |
| 36 | + decoded = jwt.decode( |
| 37 | + request.jwt, key=PUBLIC_KEY, algorithms=["PS256"], audience="https://iam.api.cloud.yandex.net/iam/v1/tokens" |
| 38 | + ) |
| 39 | + assert decoded["iss"] == SERVICE_ACCOUNT_ID |
| 40 | + assert decoded["aud"] == "https://iam.api.cloud.yandex.net/iam/v1/tokens" |
| 41 | + assert abs(decoded["iat"] - time.time()) <= 60 |
| 42 | + assert abs(decoded["exp"] - time.time()) <= 3600 |
| 43 | + |
| 44 | + response = iam_token_service_pb2.CreateIamTokenResponse(iam_token="test_token") |
| 45 | + response.expires_at.seconds = int(time.time() + 42) |
| 46 | + return response |
| 47 | + |
| 48 | + |
| 49 | +class IamTokenServiceTestServer(object): |
| 50 | + def __init__(self): |
| 51 | + self.server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=2)) |
| 52 | + iam_token_service_pb2_grpc.add_IamTokenServiceServicer_to_server(IamTokenServiceForTest(), self.server) |
| 53 | + self.server.add_insecure_port(self.get_endpoint()) |
| 54 | + self.server.start() |
| 55 | + |
| 56 | + def stop(self): |
| 57 | + self.server.stop(1) |
| 58 | + self.server.wait_for_termination() |
| 59 | + |
| 60 | + def get_endpoint(self): |
| 61 | + return "localhost:54321" |
| 62 | + |
| 63 | + |
| 64 | +class TestServiceAccountCredentials(ydb.iam.ServiceAccountCredentials): |
| 65 | + def _channel_factory(self): |
| 66 | + return grpc.insecure_channel(self._iam_endpoint) |
| 67 | + |
| 68 | + def get_expire_time(self): |
| 69 | + return self._expires_in - time.time() |
| 70 | + |
| 71 | + |
| 72 | +class TestNebiusServiceAccountCredentials(ydb.iam.NebiusServiceAccountCredentials): |
| 73 | + def get_expire_time(self): |
| 74 | + return self._expires_in - time.time() |
| 75 | + |
| 76 | + |
| 77 | +class NebiusTokenServiceHandler(http.server.BaseHTTPRequestHandler): |
| 78 | + def do_POST(self): |
| 79 | + assert self.headers["Content-Type"] == "application/x-www-form-urlencoded" |
| 80 | + assert self.path == "/token/exchange" |
| 81 | + content_length = int(self.headers["Content-Length"]) |
| 82 | + post_data = self.rfile.read(content_length).decode("utf8") |
| 83 | + print("NebiusTokenServiceHandler.POST data: {}".format(post_data)) |
| 84 | + parsed_request = urllib.parse.parse_qs(str(post_data)) |
| 85 | + assert len(parsed_request["grant_type"]) == 1 |
| 86 | + assert parsed_request["grant_type"][0] == "urn:ietf:params:oauth:grant-type:token-exchange" |
| 87 | + |
| 88 | + assert len(parsed_request["requested_token_type"]) == 1 |
| 89 | + assert parsed_request["requested_token_type"][0] == "urn:ietf:params:oauth:token-type:access_token" |
| 90 | + |
| 91 | + assert len(parsed_request["subject_token_type"]) == 1 |
| 92 | + assert parsed_request["subject_token_type"][0] == "urn:ietf:params:oauth:token-type:jwt" |
| 93 | + |
| 94 | + assert len(parsed_request["subject_token"]) == 1 |
| 95 | + jwt_token = parsed_request["subject_token"][0] |
| 96 | + decoded = jwt.decode( |
| 97 | + jwt_token, key=PUBLIC_KEY, algorithms=["RS256"], audience="token-service.iam.new.nebiuscloud.net" |
| 98 | + ) |
| 99 | + assert decoded["iss"] == SERVICE_ACCOUNT_ID |
| 100 | + assert decoded["sub"] == SERVICE_ACCOUNT_ID |
| 101 | + assert decoded["aud"] == "token-service.iam.new.nebiuscloud.net" |
| 102 | + assert abs(decoded["iat"] - time.time()) <= 60 |
| 103 | + assert abs(decoded["exp"] - time.time()) <= 3600 |
| 104 | + |
| 105 | + response = { |
| 106 | + "access_token": "test_nebius_token", |
| 107 | + "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", |
| 108 | + "token_type": "Bearer", |
| 109 | + "expires_in": 42, |
| 110 | + } |
| 111 | + |
| 112 | + self.send_response(200) |
| 113 | + self.send_header("Content-type", "application/json") |
| 114 | + self.end_headers() |
| 115 | + self.wfile.write(json.dumps(response).encode("utf8")) |
| 116 | + |
| 117 | + |
| 118 | +class NebiusTokenServiceForTest(http.server.HTTPServer): |
| 119 | + def __init__(self): |
| 120 | + http.server.HTTPServer.__init__(self, ("localhost", 54322), NebiusTokenServiceHandler) |
| 121 | + |
| 122 | + def endpoint(self): |
| 123 | + return "http://localhost:54322/token/exchange" |
| 124 | + |
| 125 | + |
| 126 | +def test_yandex_service_account_credentials(): |
| 127 | + server = IamTokenServiceTestServer() |
| 128 | + credentials = TestServiceAccountCredentials(SERVICE_ACCOUNT_ID, ACCESS_KEY_ID, PRIVATE_KEY, server.get_endpoint()) |
| 129 | + t = credentials.get_auth_token() |
| 130 | + assert t == "test_token" |
| 131 | + assert credentials.get_expire_time() <= 42 |
| 132 | + server.stop() |
| 133 | + |
| 134 | + |
| 135 | +def test_nebius_service_account_credentials(): |
| 136 | + server = NebiusTokenServiceForTest() |
| 137 | + |
| 138 | + def serve(s): |
| 139 | + s.handle_request() |
| 140 | + |
| 141 | + serve_thread = threading.Thread(target=serve, args=(server,)) |
| 142 | + serve_thread.start() |
| 143 | + |
| 144 | + credentials = TestNebiusServiceAccountCredentials(SERVICE_ACCOUNT_ID, ACCESS_KEY_ID, PRIVATE_KEY, server.endpoint()) |
| 145 | + t = credentials.get_auth_token() |
| 146 | + assert t == "test_nebius_token" |
| 147 | + assert credentials.get_expire_time() <= 42 |
| 148 | + |
| 149 | + serve_thread.join() |
0 commit comments