Class: Legion::Extensions::MicrosoftTeams::Helpers::TokenCache

Inherits:
Object
  • Object
show all
Includes:
Crypt::Helper, Helpers::Lex
Defined in:
lib/legion/extensions/microsoft_teams/helpers/token_cache.rb

Constant Summary collapse

REFRESH_BUFFER =
60
DEFAULT_LOCAL_DIR =
File.join(Dir.home, '.legionio', 'tokens')
DEFAULT_LOCAL_FILE =
File.join(DEFAULT_LOCAL_DIR, 'microsoft_teams.json')

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTokenCache

Returns a new instance of TokenCache.



38
39
40
41
42
43
44
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 38

def initialize
  @token_cache = nil
  @delegated_cache = nil
  @mutex = Mutex.new
  @app_token_warned = false
  log.debug('TokenCache initialized')
end

Class Method Details

.instanceObject



23
24
25
26
27
28
29
30
31
32
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 23

def self.instance
  @instance_mutex.synchronize do
    @instance ||= begin
      cache = new
      cache.load_from_vault
      log.info('[Teams::TokenCache] Shared instance created and loaded')
      cache
    end
  end
end

.reset_instance!Object



34
35
36
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 34

def self.reset_instance!
  @instance_mutex.synchronize { @instance = nil }
end

Instance Method Details

#authenticated?Boolean

Returns:

  • (Boolean)


125
126
127
128
129
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 125

def authenticated?
  result = @mutex.synchronize { !@delegated_cache.nil? }
  log.debug("authenticated? => #{result}")
  result
end

#cached_app_tokenObject Also known as: cached_graph_token

— Application token (client_credentials) —



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 48

def cached_app_token
  @mutex.synchronize do
    # Phase 8: Broker-managed Entra app token (short-circuits cache path)
    if defined?(Legion::Identity::Broker)
      token = Legion::Identity::Broker.token_for(:entra)
      return token if token
    end

    # Legacy: self-managed client_credentials + cache
    if @token_cache && !token_expired?(@token_cache)
      log.debug('Using cached app token')
      return @token_cache[:token]
    end

    result = refresh_app_token
    return result if result

    unless @app_token_warned
      log.warn('No app token available for Graph API calls')
      @app_token_warned = true
    end
    nil
  end
end

#cached_delegated_tokenObject

— Delegated token (user auth) —



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 85

def cached_delegated_token
  needs_refresh = @mutex.synchronize do
    unless @delegated_cache
      log.debug('No delegated token in cache')
      return nil
    end

    unless token_expired?(@delegated_cache)
      log.debug("Using cached delegated token (expires #{@delegated_cache[:expires_at]})")
      return @delegated_cache[:token]
    end

    true
  end

  return unless needs_refresh

  log.info('Delegated token expired, attempting refresh')
  refresh_delegated
end

#clear_delegated_token!Object



120
121
122
123
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 120

def clear_delegated_token!
  @mutex.synchronize { @delegated_cache = nil }
  log.debug('Delegated token cache cleared')
end

#clear_token_cache!Object



75
76
77
78
79
80
81
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 75

def clear_token_cache!
  @mutex.synchronize do
    @token_cache = nil
    @app_token_warned = false
  end
  log.debug('App token cache cleared')
end

#load_from_localObject



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 192

def load_from_local
  path = local_token_path
  unless File.exist?(path)
    log.debug("Local token file not found: #{path}")
    return false
  end

  log.info("Loading delegated token from local file: #{path}")
  raw = File.read(path)
  data = ::JSON.parse(raw)
  unless data['access_token'] && data['refresh_token']
    log.warn('Local token file missing access_token or refresh_token')
    return false
  end

  expires_at = Time.parse(data['expires_at'])
  @mutex.synchronize do
    @delegated_cache = {
      token:         data['access_token'],
      refresh_token: data['refresh_token'],
      expires_at:    expires_at,
      scopes:        data['scopes']
    }
  end
  log.info("Delegated token loaded from local file (expires_at=#{expires_at})")
  true
rescue StandardError => e
  log.error("Failed to load delegated token from local file: #{e.message}")
  false
end

#load_from_vaultObject



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 138

def load_from_vault
  if vault_available?
    log.info("Loading delegated token from Vault (#{vault_path})")
    data = vault_get(vault_path)
    if data && data[:access_token]
      @mutex.synchronize do
        @delegated_cache = {
          token:         data[:access_token],
          refresh_token: data[:refresh_token],
          expires_at:    Time.parse(data[:expires_at]),
          scopes:        data[:scopes]
        }
      end
      log.info('Delegated token loaded from Vault')
      true
    else
      log.warn('Vault had no delegated token, falling back to local')
      load_from_local
    end
  else
    log.debug('Vault not available, loading from local file')
    load_from_local
  end
rescue StandardError => e
  log.error("Failed to load delegated token from Vault: #{e.message}")
  load_from_local
end

#previously_authenticated?Boolean

Returns:

  • (Boolean)


131
132
133
134
135
136
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 131

def previously_authenticated?
  path = local_token_path
  result = File.exist?(path)
  log.debug("previously_authenticated? => #{result} (#{path})")
  result
end

#save_to_localObject



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 223

def save_to_local
  data = @mutex.synchronize { @delegated_cache&.dup }
  unless data
    log.warn('No delegated token to save locally')
    return false
  end

  path = local_token_path
  FileUtils.mkdir_p(File.dirname(path))
  File.write(path, ::JSON.pretty_generate(
                     'access_token'  => data[:token],
                     'refresh_token' => data[:refresh_token],
                     'expires_at'    => data[:expires_at].utc.iso8601,
                     'scopes'        => data[:scopes]
                   ))
  File.chmod(0o600, path)
  log.info("Delegated token saved to local file: #{path}")
  true
rescue StandardError => e
  log.error("Failed to save delegated token to local file: #{e.message}")
  false
end

#save_to_vaultObject



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 166

def save_to_vault
  save_to_local

  unless vault_available?
    log.debug('Vault not available, skipping Vault save')
    return false
  end

  data = @mutex.synchronize { @delegated_cache&.dup }
  unless data
    log.warn('No delegated token to save to Vault')
    return false
  end

  log.info("Saving delegated token to Vault (#{vault_path})")
  vault_write(vault_path, access_token:  data[:token],
                          refresh_token: data[:refresh_token],
                          expires_at:    data[:expires_at].utc.iso8601,
                          scopes:        data[:scopes])
  log.info('Delegated token saved to Vault')
  true
rescue StandardError => e
  log.error("Failed to save delegated token to Vault: #{e.message}")
  false
end

#store_delegated_token(access_token:, refresh_token:, expires_in:, scopes:) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/legion/extensions/microsoft_teams/helpers/token_cache.rb', line 106

def store_delegated_token(access_token:, refresh_token:, expires_in:, scopes:)
  expires_at = Time.now + expires_in.to_i
  @mutex.synchronize do
    @delegated_cache = {
      token:         access_token,
      refresh_token: refresh_token,
      expires_at:    expires_at,
      scopes:        scopes
    }
    @app_token_warned = false
  end
  log.info("Delegated token stored (expires_in=#{expires_in}s, expires_at=#{expires_at})")
end