Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -383,11 +383,16 @@ MigrationBackup/
# pytest-azurepipelines
test-output.xml

# pytest-cov
coverage.xml
htmlcov/

# Other
*.ini
*.json
azure-quantum/azure/quantum/version.py
azure-quantum/dist
azure-quantum/build
!azure-quantum/tests/unit/recordings/*.yaml
qdk/dist
qdk/build
7 changes: 7 additions & 0 deletions azure-quantum/azure/quantum/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import time
import io
import json
import uuid

from typing import List, TYPE_CHECKING
from urllib.parse import urlparse
Expand Down Expand Up @@ -82,3 +83,9 @@ def get_results(self):

result = json.loads(payload.decode('utf8'))
return result

@staticmethod
def create_job_id() -> str:
"""Create a unique id for a new job.
"""
return str(uuid.uuid1())
4 changes: 2 additions & 2 deletions azure-quantum/azure/quantum/optimization/solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# Licensed under the MIT License.
##
import logging
import uuid, io
import io
import azure.quantum

from typing import List, Union, Any, Optional
Expand Down Expand Up @@ -54,7 +54,7 @@ def submit(self, problem: Union[str, Problem]) -> Job:
of a Problem has been uploaded.
"""
## Create a container URL:
job_id = uuid.uuid1()
job_id = Job.create_job_id()
logger.info(f"Submitting job with id: {job_id}")

container_name = f"job-{job_id}"
Expand Down
13 changes: 7 additions & 6 deletions azure-quantum/azure/quantum/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ def initialize_cache(self):

self.token_cache = msal.SerializableTokenCache()
if os.path.exists(self.cache_path):
self.token_cache.deserialize(open(self.cache_path, "r").read())
with open(self.cache_path, "r") as cache:
self.token_cache.deserialize(cache.read())

def write_out_cache(self):
logger.debug(f"Updating AAD token cache at '{self.cache_path}'")
Expand All @@ -80,7 +81,8 @@ def write_out_cache(self):
if not os.path.isdir(cache_folder):
os.makedirs(cache_folder)

open(self.cache_path, "w").write(self.token_cache.serialize())
with open(self.cache_path, "w") as afile:
afile.write(self.token_cache.serialize())

class MsalWrapper:
def __init__(self, subscription_id: str, refresh: bool):
Expand Down Expand Up @@ -371,10 +373,9 @@ def login(self, refresh:bool=False) -> Authentication:
:returns:
the user credentials to authenticate with Azure Quantum
"""

if refresh or (self.credentials is None):
self.credentials = None
msal_wrapper = MsalWrapper(self.subscription_id, refresh=refresh)
auth_token = msal_wrapper.acquire_auth_token()
return BasicTokenAuthentication(auth_token)
self.credentials = msal_wrapper.acquire_auth_token()

return self.credentials
return BasicTokenAuthentication(self.credentials)
1 change: 1 addition & 0 deletions azure-quantum/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
azure-storage-blob
msrestazure
msal
azure-devtools
11 changes: 11 additions & 0 deletions azure-quantum/tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Unit tests

- Workspace.login() authentication
- Problem
- Solver
- SimulatedAnnealing
- Tabu
- QuantumMonteCarlo
- ParallelTempering
- Jobs

70 changes: 70 additions & 0 deletions azure-quantum/tests/unit/recording_updater.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#!/bin/env python
# -*- coding: utf-8 -*-
##
# recording_updater.py: Updates test recordings with dummy values
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##

## IMPORTS ##

import glob
import os
import re


class RecordingUpdater:
"""RecordingUpdater

Replaces secrets with dummy values in network recordings.
"""
dummy_uid = "00000000-0000-0000-0000-000000000000"
dummy_rg = "dummy-rg"
dummy_ws = "dummy-ws"

def __init__(self, recording_directory: str, recording_glob: str):
"""RecordingUpdater constructor

:param recording_directory: Directory name where recording files are found.
:type recording_directory: str
:param recording_glob: A file name glob used to find recordings in the recording-directory. For example, '*.yaml'
:type recording_glob: str
"""
super().__init__()
path = os.path.join(recording_directory, recording_glob)
self._recording_file_names = glob.glob(path)
self._auth_prog = re.compile(r'authorization_uri="https://login.windows.net/(?P<authid>([a-f0-9]+[-]){4}[a-f0-9]+)"')

def update_recordings_with_dummy_values(self):
"""Uses regular expressions to replace secrets with dummy values in network recordings.
"""
progs = self._get_regex_programs()
for file_name in self._recording_file_names:
with open(file_name) as afile:
contents = afile.read()
for prog, replacement in progs:
contents = prog.sub(replacement, contents)
contents = self._replace_auth_with_dummy_values(contents)
with open(file_name, 'w') as afile:
afile.write(contents)

def _get_regex_programs(self) -> list:
progs = []
# progs.append((re.compile(<regex>), <replacemnt-string>))
progs.append((re.compile(r'/subscriptions/([a-f0-9]+[-]){4}[a-f0-9]+'), "/subscriptions/" + self.dummy_uid))
progs.append((re.compile(r'job-([a-f0-9]+[-]){4}[a-f0-9]+'), "job-" + self.dummy_uid))
progs.append((re.compile(r'jobs/([a-f0-9]+[-]){4}[a-f0-9]+'), "jobs/" + self.dummy_uid))
progs.append((re.compile(r'"id":\s*"([a-f0-9]+[-]){4}[a-f0-9]+"'), '"id": "{}"'. format(self.dummy_uid)))
progs.append((re.compile(r'/resourceGroups/[a-z0-9-]+/'), "/resourceGroups/dummy-rg/"))
progs.append((re.compile(r'/workspaces/[a-z0-9-]+/'), "/workspaces/dummy-ws/"))
progs.append((re.compile(r'sig=[0-9a-zA-Z%]+\&'), "sig=sanitized&"))
return progs

def _replace_auth_with_dummy_values(self, contents: str) -> str:
match = self._auth_prog.search(contents)
if match:
info = match.groupdict()
auth_id = info["authid"]
contents = contents.replace(auth_id, self.dummy_uid)
return contents
Loading