Module: AppleDEPClient::Token

Defined in:
lib/apple_dep_client/token.rb

Constant Summary collapse

SERVER_TOKEN_KEYS =
[:consumer_key, :consumer_secret, :access_token, :access_secret, :access_token_expiry]

Class Method Summary collapse

Class Method Details

.create_temp_file(name, data, binary: false) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/apple_dep_client/token.rb', line 33

def self.create_temp_file(name, data, binary: false)
  file = Tempfile.new name
  file.binmode if binary
  file.write data
  file.size # flush data to disk
  file
end

.decode_token(smime_data) ⇒ Object

Given an S/MIME encrypted Server Token, return a hash of token values From the MDM Protocol information, it seems all tokens are PKCS7-MIME encrypted



15
16
17
18
# File 'lib/apple_dep_client/token.rb', line 15

def self.decode_token(smime_data)
  data = decrypt_data(smime_data)
  parse_data data
end

.decrypt_data(smime_data) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/apple_dep_client/token.rb', line 20

def self.decrypt_data(smime_data)
  data = create_temp_file("data", smime_data)
  private_key = create_temp_file("key", AppleDEPClient.private_key)
  command = "openssl smime -decrypt -in #{data.path} -inkey #{private_key.path} -text"
  decrypted_data, errors = run_command command
  remove_temp_file data
  remove_temp_file private_key
  if decrypted_data == "" || errors != ""
    raise AppleDEPClient::Error::TokenError, "Incorrect data #{errors}"
  end
  decrypted_data
end

.parse_data(data) ⇒ Object



51
52
53
54
55
56
# File 'lib/apple_dep_client/token.rb', line 51

def self.parse_data(data)
  data = strip_wrappers data
  data = JSON.parse(data, symbolize_names: true)
  save_data data
  data
end

.remove_temp_file(file) ⇒ Object



41
42
43
44
# File 'lib/apple_dep_client/token.rb', line 41

def self.remove_temp_file(file)
  file.close
  file.unlink
end

.run_command(command) ⇒ Object



46
47
48
49
# File 'lib/apple_dep_client/token.rb', line 46

def self.run_command(command)
  stdin, stdout, stderr = Open3.popen3 command
  [stdout.read, stderr.read]
end

.save_data(data) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/apple_dep_client/token.rb', line 63

def self.save_data(data)
  SERVER_TOKEN_KEYS.each do |k|
    if not AppleDEPClient.instance_variable_get("@#{k}").respond_to? :call
      AppleDEPClient.instance_variable_set("@#{k}", data[k])
    end
  end
end

.strip_wrappers(data) ⇒ Object



58
59
60
61
# File 'lib/apple_dep_client/token.rb', line 58

def self.strip_wrappers(data)
  data = data.sub("-----BEGIN MESSAGE-----", "").sub("-----END MESSAGE-----", "")
  data.strip
end