1# frozen_string_literal: true 2 3module Gitlab 4 module JwtAuthenticatable 5 # Supposedly the effective key size for HMAC-SHA256 is 256 bits, i.e. 32 6 # bytes https://tools.ietf.org/html/rfc4868#section-2.6 7 SECRET_LENGTH = 32 8 9 def self.included(base) 10 base.extend(ClassMethods) 11 end 12 13 module ClassMethods 14 include Gitlab::Utils::StrongMemoize 15 16 def decode_jwt_for_issuer(issuer, encoded_message) 17 JWT.decode( 18 encoded_message, 19 secret, 20 true, 21 { iss: issuer, verify_iss: true, algorithm: 'HS256' } 22 ) 23 end 24 25 def secret 26 strong_memoize(:secret) do 27 Base64.strict_decode64(File.read(secret_path).chomp).tap do |bytes| 28 raise "#{secret_path} does not contain #{SECRET_LENGTH} bytes" if bytes.length != SECRET_LENGTH 29 end 30 end 31 end 32 33 def write_secret 34 bytes = SecureRandom.random_bytes(SECRET_LENGTH) 35 File.open(secret_path, 'w:BINARY', 0600) do |f| 36 f.chmod(0600) # If the file already existed, the '0600' passed to 'open' above was a no-op. 37 f.write(Base64.strict_encode64(bytes)) 38 end 39 end 40 end 41 end 42end 43