- 
                Notifications
    You must be signed in to change notification settings 
- Fork 55
CM-23451 - Add "user-agent" global option to CLI #118
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from 2 commits
      Commits
    
    
            Show all changes
          
          
            13 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      a3a5958
              
                Add machine_id util
              
              
                MarshalX 9583c8f
              
                add caching
              
              
                MarshalX c1a5bb3
              
                add tests
              
              
                MarshalX 5c28e18
              
                reuse existed shell function
              
              
                MarshalX 7bdca07
              
                add cache tests
              
              
                MarshalX c3467c6
              
                assert isinstance
              
              
                MarshalX 80cc817
              
                move registry key to arg
              
              
                MarshalX c435539
              
                fix tests, log mid
              
              
                MarshalX 5067fe6
              
                enable pytest live log
              
              
                MarshalX fc7aeb6
              
                Merge branch 'main' into CM-23451-Add-user-agent-global-option
              
              
                MarshalX 4b8aa2a
              
                add user-agent option
              
              
                MarshalX 3d91641
              
                use uuid instead of machine id
              
              
                MarshalX 1c6d105
              
                Merge branch 'main' into CM-23451-Add-user-agent-global-option
              
              
                MarshalX File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| """Get the unique machine id of any host (without admin privileges) | ||
|  | ||
| Based on methods from: https://github.com/denisbrodbeck/machineid | ||
| The MIT License (MIT) | ||
| """ | ||
|  | ||
| import hashlib | ||
| import hmac | ||
| import subprocess | ||
| from sys import platform | ||
| from typing import Optional | ||
| from functools import lru_cache | ||
|  | ||
| from cycode.cli.exceptions.custom_exceptions import CycodeError | ||
|  | ||
|  | ||
| def _read_cmd(cmd: str) -> Optional[str]: | ||
| try: | ||
| return subprocess.run(cmd, shell=True, capture_output=True, check=True, encoding='UTF-8').stdout.strip() | ||
|         
                  MarshalX marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved         
                  MarshalX marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| except: # noqa | ||
| return None | ||
|  | ||
|  | ||
| def _read_registry(registry: str, key: str) -> Optional[str]: | ||
| import winreg | ||
|  | ||
| with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as reg: | ||
| with winreg.OpenKey(reg, registry) as key_object: | ||
| try: | ||
| value, _ = winreg.QueryValueEx(key_object, key) | ||
| return value | ||
| except WindowsError: | ||
| pass | ||
|  | ||
| return None | ||
|  | ||
|  | ||
| def _read_file(path: str) -> Optional[str]: | ||
| try: | ||
| with open(path, encoding='UTF-8') as f: | ||
| return f.read() | ||
| except: # noqa | ||
| return None | ||
|  | ||
|  | ||
| def _get_darwin_machine_id() -> str: | ||
| return _read_cmd("ioreg -d2 -c IOPlatformExpertDevice | awk -F\\\" '/IOPlatformUUID/{print $(NF-1)}'") | ||
|  | ||
|  | ||
| def _get_windows_machine_id() -> str: | ||
| mid = _read_registry('SOFTWARE\\MICROSOFT\\CRYPTOGRAPHY', 'MachineGuid') | ||
| if not mid: | ||
| mid = _read_cmd('wmic csproduct get uuid').split('\n')[2].strip() | ||
|  | ||
| return mid | ||
|  | ||
|  | ||
| def _get_linux_machine_id() -> str: | ||
| mid = _read_file('/var/lib/dbus/machine-id') | ||
|  | ||
| if not mid: | ||
| mid = _read_file('/etc/machine-id') | ||
|  | ||
| if not mid: | ||
| cgroup = _read_file('/proc/self/cgroup') | ||
| if cgroup and 'docker' in cgroup: | ||
| mid = _read_cmd('head -1 /proc/self/cgroup | cut -d/ -f3') | ||
|  | ||
| if not mid: | ||
| mountinfo = _read_file('/proc/self/mountinfo') | ||
| if mountinfo and 'docker' in mountinfo: | ||
| mid = _read_cmd("grep 'systemd' /proc/self/mountinfo | cut -d/ -f3") | ||
|  | ||
| return mid | ||
|  | ||
|  | ||
| def _get_bsd_machine_id() -> str: | ||
| mid = _read_file('/etc/hostid') | ||
| if not mid: | ||
| mid = _read_cmd('kenv -q smbios.system.uuid') | ||
|  | ||
| return mid | ||
|  | ||
|  | ||
| def _get_machine_id() -> str: | ||
| if platform == 'darwin': | ||
| mid = _get_darwin_machine_id() | ||
| elif platform in {'win32', 'cygwin', 'msys'}: | ||
| mid = _get_windows_machine_id() | ||
| elif platform.startswith('linux'): | ||
| mid = _get_linux_machine_id() | ||
| elif platform.startswith('openbsd') or platform.startswith('freebsd'): | ||
| mid = _get_bsd_machine_id() | ||
| else: | ||
| raise CycodeError('Unknown platform') | ||
|  | ||
| if mid is None: | ||
| raise CycodeError("Can't get Machine ID") | ||
|  | ||
| return mid | ||
|  | ||
|  | ||
| @lru_cache(maxsize=None) | ||
| def machine_id() -> str: | ||
| return _get_machine_id() | ||
|  | ||
|  | ||
| @lru_cache(maxsize=None) | ||
| def protected_machine_id(app_id: str) -> str: | ||
| """Calculates HMAC-SHA256 of the app ID, keyed by the machine ID and returns a hex-encoded str.""" | ||
| app_id = app_id.encode() | ||
| mid = _get_machine_id().encode() | ||
| return hmac.new(key=mid, msg=app_id, digestmod=hashlib.sha256).hexdigest() | ||
|  | ||
|  | ||
| if __name__ == '__main__': | ||
| print('Machine ID:', machine_id()) | ||
| print('Protected Machine ID:', protected_machine_id('CycodeCLI')) | ||
|  | ||
| for _ in range(100): | ||
| machine_id() | ||
|  | ||
| print('Cache info:', machine_id.cache_info()) | ||
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.